hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
c75b30d5389f1392c668041cf1671f6f277f72c9
5,194
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model; import hudson.remoting.Channel; import hudson.remoting.PingThread; import hudson.remoting.Channel.Mode; import hudson.util.ChunkedOutputStream; import hudson.util.ChunkedInputStream; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; /** * Builds a {@link Channel} on top of two HTTP streams (one used for each direction.) * * @author Kohsuke Kawaguchi */ abstract public class FullDuplexHttpChannel { private Channel channel; private InputStream upload; private final UUID uuid; private final boolean restricted; private boolean completed; public FullDuplexHttpChannel(UUID uuid, boolean restricted) throws IOException { this.uuid = uuid; this.restricted = restricted; } /** * This is where we send the data to the client. * * <p> * If this connection is lost, we'll abort the channel. */ public synchronized void download(StaplerRequest req, StaplerResponse rsp) throws InterruptedException, IOException { rsp.setStatus(HttpServletResponse.SC_OK); // server->client channel. // this is created first, and this controls the lifespan of the channel rsp.addHeader("Transfer-Encoding", "chunked"); OutputStream out = rsp.getOutputStream(); if (DIY_CHUNKING) out = new ChunkedOutputStream(out); // send something out so that the client will see the HTTP headers out.write("Starting HTTP duplex channel".getBytes()); out.flush(); // wait until we have the other channel while(upload==null) wait(); try { channel = new Channel("HTTP full-duplex channel " + uuid, Computer.threadPoolForRemoting, Mode.BINARY, upload, out, null, restricted); // so that we can detect dead clients, periodically send something PingThread ping = new PingThread(channel) { @Override protected void onDead(Throwable diagnosis) { LOGGER.log(Level.INFO,"Duplex-HTTP session " + uuid + " is terminated",diagnosis); // this will cause the channel to abort and subsequently clean up try { upload.close(); } catch (IOException e) { // this can never happen throw new AssertionError(e); } } @Override protected void onDead() { onDead(null); } }; ping.start(); main(channel); channel.join(); ping.interrupt(); } finally { // publish that we are done completed=true; notify(); } } protected abstract void main(Channel channel) throws IOException, InterruptedException; /** * This is where we receive inputs from the client. */ public synchronized void upload(StaplerRequest req, StaplerResponse rsp) throws InterruptedException, IOException { rsp.setStatus(HttpServletResponse.SC_OK); InputStream in = req.getInputStream(); if(DIY_CHUNKING) in = new ChunkedInputStream(in); // publish the upload channel upload = in; notify(); // wait until we are done while (!completed) wait(); } public Channel getChannel() { return channel; } private static final Logger LOGGER = Logger.getLogger(FullDuplexHttpChannel.class.getName()); /** * Set to true if the servlet container doesn't support chunked encoding. */ public static boolean DIY_CHUNKING = Boolean.getBoolean("hudson.diyChunking"); }
34.85906
121
0.651328
34b52a91eeb273131899734083c8b04cb44c92c9
2,553
package org.jetbrains.java.decompiler.util; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; public class VarHelper { private static final Map<String, String[]> switches = new HashMap<String, String[]>(); static { switches.put("byte", new String[]{ "b" }); switches.put("char", new String[]{ "c" }); switches.put("short", new String[]{ "short" }); switches.put("int", new String[]{ "i", "j", "k", "l" }); switches.put("long", new String[]{ "i", "j", "k", "l" }); switches.put("boolean", new String[]{ "flag" }); switches.put("double", new String[]{ "d" }); switches.put("float", new String[]{ "f", "f" // Add twice because the original script is inconsistent }); switches.put("String", new String[]{ "s", "s" // Add twice because the original script is inconsistent }); switches.put("Class", new String[]{ "oclass" }); switches.put("Long", new String[]{ "olong" }); switches.put("Byte", new String[]{ "obyte" }); switches.put("Short", new String[]{ "oshort" }); switches.put("Boolean", new String[]{ "obool" }); switches.put("Double", new String[]{ "odouble" }); switches.put("Float", new String[]{ "ofloat" }); switches.put("Long", new String[]{ "olong" }); switches.put("Enum", new String[]{ "oenum" }); } private final Set<String> used = new HashSet<String>(); public String help(String name, String type, boolean varArgs) { if (type == null || !name.startsWith("var")) { return name; } while (type.contains( "<" )) { type = type.substring(0, type.indexOf('<')) + type.substring(type.lastIndexOf('>') + 1); } type = type.replace( '.', '_' ); if (type.endsWith("]")) { type = "a" + type.substring(0, type.indexOf('[')); } else if (varArgs) { type = "a" + type; } String[] remap = switches.get(type); if (remap == null) { remap = new String[]{ type.toLowerCase(Locale.ENGLISH) }; } for (int counter = 0;; counter++) { for (String subMap : remap) { String attempt = subMap + ((counter == 0 && !subMap.equals("short") && (remap.length > 1 || subMap.length() > 1)) ? "" : counter); if (!used.contains(attempt)) { used.add(attempt); return attempt; } } } } }
24.314286
138
0.534665
75355cb658d7f00fb1cb86620dd8884b795debac
752
package com.xing.apidemo.newvolley; import android.graphics.Bitmap; import android.util.LruCache; import com.android.volley.toolbox.ImageLoader; public class BitmapCache implements ImageLoader.ImageCache { private LruCache<String,Bitmap> mCache; public BitmapCache(){ //10M int maxSize = 10*1024*1024; mCache = new LruCache<String,Bitmap>(maxSize){ @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getByteCount(); } }; } @Override public Bitmap getBitmap(String url) { return mCache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { mCache.put(url,bitmap); } }
22.787879
61
0.634309
e30da8392ff819dee78350daa712bd2e86251815
1,466
package br.com.zup.propostas.proposalregistration; import br.com.zup.propostas.proposalanalisys.ProposalAnalysisService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import javax.validation.Valid; import java.net.URI; @RestController @RequestMapping("/api/proposals") public class ProposalRegistrationController { @Autowired private CheckCpfCnpjValidator checkCpfCnpjValidator; @Autowired private ProposalRepository proposalRepository; @Autowired private ProposalAnalysisService proposalAnalysisService; @InitBinder public void init (WebDataBinder binder) { binder.addValidators(checkCpfCnpjValidator); } @PostMapping public ResponseEntity create (@RequestBody @Valid NewProposalRequestDto request, UriComponentsBuilder uriBuilder) throws InterruptedException { Proposal proposal = request.toModel(); proposalRepository.save(proposal); proposalAnalysisService.processProposalAnalysis(proposal); proposalRepository.save(proposal); URI uri = uriBuilder.path("/api/proposal/{id}").buildAndExpand(proposal.getId()).toUri(); return ResponseEntity.created(uri).build(); } }
33.318182
147
0.783765
793e5614e5f3e8fd81085dbc43dfaeb771966a67
974
package cn.ttplatform.wh.group; import java.net.InetSocketAddress; import lombok.AllArgsConstructor; import lombok.Data; import lombok.ToString; /** * @author Wang Hao * @date 2021/4/21 13:30 */ @Data @ToString @AllArgsConstructor public class EndpointMetaData { private String nodeId; private String host; private int connectorPort; public EndpointMetaData(String metaData) { String[] pieces = metaData.split(","); if (pieces.length != 4) { throw new IllegalArgumentException("illegal node info [" + metaData + "]"); } nodeId = pieces[0]; host = pieces[1]; try { connectorPort = Integer.parseInt(pieces[3]); } catch (NumberFormatException e) { throw new IllegalArgumentException("illegal port in node info [" + metaData + "]"); } } public InetSocketAddress getAddress() { return new InetSocketAddress(host, connectorPort); } }
23.756098
95
0.63963
1a551732f064758ef19f2bfd12eed6a587a67992
1,608
import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import sun.reflect.generics.tree.Tree; import java.io.IOException; import java.util.Map; import java.util.TreeMap; public class TFReducer extends Reducer<NullWritable, Text, Text, FloatWritable> { private TreeMap<Float, String> tmap2; @Override protected void setup(Context context) throws IOException, InterruptedException { tmap2 = new TreeMap<Float, String>(); } @Override protected void reduce(NullWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException { for (Text val : values){ String combined = val.toString(); String[] combineArray = combined.split("/"); String name = combineArray[0]; float pct = Float.parseFloat(combineArray[1]); tmap2.put(pct, name); if (tmap2.size() > 50){ tmap2.remove(tmap2.firstEntry()); } } for (Map.Entry<Float, String> entry: tmap2.entrySet()){ context.write(new Text(entry.getValue()), new FloatWritable(entry.getKey())); } } // @Override // protected void cleanup(Context context) throws IOException, InterruptedException { // for (Map.Entry<Float, String> entry: tmap2.entrySet()){ // float pct = entry.getKey(); // String name = entry.getValue(); // // context.write(new Text(name), new FloatWritable(pct)); // } // } }
32.16
126
0.63806
df182b63813267dd3a502c582c0a757f56694c10
2,937
package com.jia.modeling.controller; import com.alibaba.fastjson.JSON; import com.google.gson.Gson; import com.jia.common.entity.relation; import com.jia.modeling.service.relationService; import com.jia.modeling.service.relationServiceImpl; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; @Controller @RequestMapping("/relation") @CrossOrigin @Api("relation service") public class RelationController { @Autowired private relationServiceImpl relationService; @ResponseBody @RequestMapping("/insert") @ApiOperation("insert a relation") // 插入一条关系 public String insert(@RequestBody @ApiParam("要插入的关系") relation relation) throws JSONException { try { relationService.save(relation); } catch (Exception e) { e.printStackTrace(); return "error"; } return "success"; } @RequestMapping("update") @ResponseBody public String update(@RequestParam("result") String message) throws JSONException, UnsupportedEncodingException { String message2= URLDecoder.decode(message,"UTF-8"); System.out.println("message.toString() = " + message2.toString()); JSONObject result = new JSONObject(message2); // JSONArray result = jsonObject.getJSONArray("result"); ArrayList<relation> relations = new ArrayList<>(); JSONArray names = result.names(); for (int i = 0; i < names.length(); i++) { relation relation = new Gson().fromJson(result.getString(names.getString(i)), relation.class); System.out.println("relation.toString() = " + relation.toString()); relations.add(relation); } return relationService.update(relations); } @ResponseBody @RequestMapping("deleteOne") public String deleteOne(@RequestBody relation relation){ return relationService.delete(relation); } // 找到某个用户在某个领域下的所有标注并以字符串的形式返回。 @ResponseBody @RequestMapping("/findOne") public String findOne(@RequestParam("field") String field, @RequestParam("author") String author){ return relationService.findOne(field,author); } @ResponseBody @RequestMapping("/findFields") public String findFields(@RequestParam("account") String author){ return relationService.findFields(author); } @ResponseBody @RequestMapping("startTag") public String startTag(@RequestParam String field){ return relationService.tagInfo(field); } }
33.375
117
0.707184
bee9e67a2b91685d50588fe08d94c73cd76896c3
5,194
/*- * #%L * Bricks Dashboard * %% * Copyright (C) 2018 - 2019 Ingo Griebsch * %% * 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. * #L% */ package com.github.ingogriebsch.bricks.dashboard; import java.io.InputStream; import com.github.ingogriebsch.bricks.assemble.collector.ApplicationCollector; import com.github.ingogriebsch.bricks.assemble.collector.ApplicationIdCollector; import com.github.ingogriebsch.bricks.assemble.collector.ComponentCollector; import com.github.ingogriebsch.bricks.assemble.collector.ComponentIdCollector; import com.github.ingogriebsch.bricks.assemble.collector.yaml.ApplicationIdOrigin; import com.github.ingogriebsch.bricks.assemble.collector.yaml.ComponentIdOrigin; import com.github.ingogriebsch.bricks.assemble.collector.yaml.YamlExtractingApplicationIdCollector; import com.github.ingogriebsch.bricks.assemble.collector.yaml.YamlExtractingComponentIdCollector; import com.github.ingogriebsch.bricks.assemble.collector.yaml.YamlResourceLoader; import com.github.ingogriebsch.bricks.assemble.loader.ResourceLoader; import com.github.ingogriebsch.bricks.assemble.loader.spring.SpringResourceBasedResourceLoader; import com.github.ingogriebsch.bricks.assemble.loader.spring.StaticResourceLocationProvider; import com.github.ingogriebsch.bricks.assemble.loader.yaml.YamlExtractingResourceLoader; import com.github.ingogriebsch.bricks.assemble.reader.ApplicationReader; import com.github.ingogriebsch.bricks.assemble.reader.ComponentReader; import com.github.ingogriebsch.bricks.assemble.reader.common.SimpleApplicationReader; import com.github.ingogriebsch.bricks.assemble.reader.common.SimpleComponentReader; import com.github.ingogriebsch.bricks.assemble.reader.common.StaticApplicationReaderFactory; import com.github.ingogriebsch.bricks.assemble.reader.common.StaticComponentReaderFactory; import com.github.ingogriebsch.bricks.converter.yaml.YamlBasedApplicationConverter; import com.github.ingogriebsch.bricks.converter.yaml.YamlBasedComponentConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; @Configuration @RequiredArgsConstructor public class ServiceConfiguration { private static final String SAMPLE_APPLICATIONS_LOCATION = "classpath:/example-applications.yml"; private static final String[] YAML_PATH_APPLICATIONS = new String[] { "applications" }; private static final String[] YAML_PATH_COMPONENTS = new String[] { "applications", "components" }; private static final String YAML_KEY_ID = "id"; @NonNull private final org.springframework.core.io.ResourceLoader resourceLoader; @Bean public ApplicationCollector applicationCollector() { return new ApplicationCollector(applicationIdCollector(), new StaticApplicationReaderFactory(applicationReader())); } @Bean public ComponentCollector componentCollector() { return new ComponentCollector(componentIdCollector(), new StaticComponentReaderFactory(componentReader())); } private ApplicationIdCollector applicationIdCollector() { return new YamlExtractingApplicationIdCollector(yamlResourceLoader(), applicationIdOrigin()); } private ComponentIdCollector componentIdCollector() { return new YamlExtractingComponentIdCollector(yamlResourceLoader(), componentIdOrigin()); } private ApplicationReader applicationReader() { return new SimpleApplicationReader(resourceLoader(YAML_PATH_APPLICATIONS), new YamlBasedApplicationConverter()); } private ComponentReader componentReader() { return new SimpleComponentReader(resourceLoader(YAML_PATH_COMPONENTS), new YamlBasedComponentConverter()); } private ResourceLoader resourceLoader(String... parents) { return new YamlExtractingResourceLoader(new SpringResourceBasedResourceLoader(resourceLoader, new StaticResourceLocationProvider(SAMPLE_APPLICATIONS_LOCATION)), YAML_KEY_ID, parents); } private ApplicationIdOrigin applicationIdOrigin() { return ApplicationIdOrigin.builder().parents(YAML_PATH_APPLICATIONS).build(); } private ComponentIdOrigin componentIdOrigin() { return ComponentIdOrigin.builder().applicationIdOrigin(applicationIdOrigin()).build(); } private YamlResourceLoader yamlResourceLoader() { return new YamlResourceLoader() { @Override @SneakyThrows public InputStream load() { return resourceLoader.getResource(SAMPLE_APPLICATIONS_LOCATION).getInputStream(); } }; } }
44.775862
123
0.793223
ed11cb0398c578d508b5ebfb7b241224d11cbf9b
4,165
package com.gempukku.swccgo.cards.set1.dark; import com.gempukku.swccgo.cards.AbstractSite; import com.gempukku.swccgo.cards.GameConditions; import com.gempukku.swccgo.cards.conditions.ControlsCondition; import com.gempukku.swccgo.common.Icon; import com.gempukku.swccgo.common.Side; import com.gempukku.swccgo.common.Title; import com.gempukku.swccgo.filters.Filters; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.game.SwccgGame; import com.gempukku.swccgo.logic.TriggerConditions; import com.gempukku.swccgo.logic.actions.CancelCardActionBuilder; import com.gempukku.swccgo.logic.actions.RequiredGameTextTriggerAction; import com.gempukku.swccgo.logic.modifiers.DeploysFreeModifier; import com.gempukku.swccgo.logic.modifiers.ForceDrainModifier; import com.gempukku.swccgo.logic.modifiers.Modifier; import com.gempukku.swccgo.logic.timing.Effect; import com.gempukku.swccgo.logic.timing.EffectResult; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Set: Premiere * Type: Location * Subtype: Site * Title: Death Star: Central Core */ public class Card1_283 extends AbstractSite { public Card1_283() { super(Side.DARK, Title.Death_Star_Central_Core, Title.Death_Star); setLocationDarkSideGameText("If you control, Wrong Turn and Retract The Bridge deploy for free."); setLocationLightSideGameText("If you control, Force drain +1 here and Death Star Tractor Beam is canceled."); addIcon(Icon.DARK_FORCE, 1); addIcons(Icon.INTERIOR_SITE, Icon.MOBILE, Icon.SCOMP_LINK); } @Override protected List<Modifier> getGameTextDarkSideWhileActiveModifiers(String playerOnDarkSideOfLocation, SwccgGame game, PhysicalCard self) { List<Modifier> modifiers = new LinkedList<Modifier>(); modifiers.add(new DeploysFreeModifier(self, Filters.or(Filters.Wrong_Turn, Filters.Retract_The_Bridge), new ControlsCondition(playerOnDarkSideOfLocation, self))); return modifiers; } @Override protected List<Modifier> getGameTextLightSideWhileActiveModifiers(String playerOnLightSideOfLocation, SwccgGame game, PhysicalCard self) { List<Modifier> modifiers = new LinkedList<Modifier>(); modifiers.add(new ForceDrainModifier(self, new ControlsCondition(playerOnLightSideOfLocation, self), 1, playerOnLightSideOfLocation)); return modifiers; } @Override protected List<RequiredGameTextTriggerAction> getGameTextLightSideRequiredBeforeTriggers(String playerOnLightSideOfLocation, SwccgGame game, Effect effect, PhysicalCard self, int gameTextSourceCardId) { // Check condition(s) if (TriggerConditions.isPlayingCard(game, effect, Filters.Death_Star_Tractor_Beam) && GameConditions.canCancelCardBeingPlayed(game, self, effect) && GameConditions.controls(game, playerOnLightSideOfLocation, self)) { RequiredGameTextTriggerAction action = new RequiredGameTextTriggerAction(self, gameTextSourceCardId); // Build action using common utility CancelCardActionBuilder.buildCancelCardBeingPlayedAction(action, effect); return Collections.singletonList(action); } return null; } @Override protected List<RequiredGameTextTriggerAction> getGameTextLightSideRequiredAfterTriggers(String playerOnLightSideOfLocation, SwccgGame game, EffectResult effectResult, PhysicalCard self, int gameTextSourceCardId) { // Check condition(s) if (TriggerConditions.isTableChanged(game, effectResult) && GameConditions.canTargetToCancel(game, self, Filters.Death_Star_Tractor_Beam) && GameConditions.controls(game, playerOnLightSideOfLocation, self)) { final RequiredGameTextTriggerAction action = new RequiredGameTextTriggerAction(self, gameTextSourceCardId); // Build action using common utility CancelCardActionBuilder.buildCancelCardAction(action, Filters.Death_Star_Tractor_Beam, Title.Death_Star_Tractor_Beam); return Collections.singletonList(action); } return null; } }
50.180723
217
0.764946
8c574f49b886b415d8338ac2186be7c2f55fe93b
5,688
package com.github.ansonliao.selenium.utils; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; import com.jayway.jsonpath.spi.json.GsonJsonProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.util.Strings; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import static com.github.ansonliao.selenium.utils.MyFileUtils.isFileExisted; import static com.github.ansonliao.selenium.utils.PlatformUtils.getPlatform; import static com.github.ansonliao.selenium.utils.PlatformUtils.isWindows; import static com.github.ansonliao.selenium.utils.config.SEConfigs.getConfigInstance; import static com.jayway.jsonpath.Option.DEFAULT_PATH_LEAF_TO_NULL; public class CapsUtils { public static final String CLI_ARGS_KEY = "cli_args"; public static final String DESIRED_CAPABILITIES_KEY = "caps"; public static final String EXTENSIONS_KEY = "extensions"; public static Configuration GSON_CONFIGURATION = Configuration.builder().jsonProvider(new GsonJsonProvider()) .options(DEFAULT_PATH_LEAF_TO_NULL).build(); private static Logger logger = LoggerFactory.getLogger(CapsUtils.class); private static String wdCapsFilePath; private static DocumentContext documentContext; static { wdCapsFilePath = isWindows(getPlatform().toString()) ? getConfigInstance().capsPath().replace("\\", "/") : getConfigInstance().capsPath(); try { documentContext = isFileExisted(wdCapsFilePath) ? JsonPath.parse(new File(wdCapsFilePath)) : null; } catch (IOException e) { e.printStackTrace(); } } public synchronized static boolean isJsonFileEmpty() { if (documentContext == null) { return true; } return Strings.isNullOrEmpty(documentContext.read("$").toString().trim()); } public synchronized static boolean isPathExists(String path) { if (isJsonFileEmpty()) { return false; } String fullPath = path.trim().startsWith("$.") ? path : "$.".concat(path); try { documentContext.read(fullPath); return true; } catch (PathNotFoundException e) { return false; } } public synchronized static Map<String, Object> getCaps(String browser) { if (isJsonFileEmpty()) { return Maps.newHashMap(); } String path = "$.".concat(browser).concat(".").concat(DESIRED_CAPABILITIES_KEY); return isPathExists(path) ? documentContext.read(path, Map.class) : Maps.newHashMap(); } public synchronized static List<Object> getCliArgs(String browser) { if (isJsonFileEmpty()) { return Lists.newArrayList(); } String path = "$.".concat(browser).concat(".").concat(CLI_ARGS_KEY); return isPathExists(path) ? documentContext.read(path, List.class) : Lists.newArrayList(); } public synchronized static List<Object> getExtensions(String browser) { if (isJsonFileEmpty()) { return Lists.newArrayList(); } String path = "$.".concat(browser).concat(".").concat(EXTENSIONS_KEY); return isPathExists(path) ? documentContext.read(path, List.class) : Lists.newArrayList(); } public synchronized static Map<String, Object> getEmulation(String browser) { if (isJsonFileEmpty()) { return Maps.newHashMap(); } String path = "$.".concat(browser).concat(".").concat("emulation"); return isPathExists(path) ? documentContext.read(path, Map.class) : Maps.newHashMap(); } // public synchronized static JsonElement getCaps() { // if (!isCapsExisted(wdCapsFilePath)) { // logger.info("No webdriver desired capabilities Json file found from path : " // + wdCapsFilePath); // return JsonNull.INSTANCE; // } // // capsJsonReader = getCapsJsonReader(wdCapsFilePath); // JsonObject object = getGsonInstance().fromJson(capsJsonReader, JsonObject.class); // JsonElement element = JsonParser.getJsonElement(object, ""); // if (element == null) { // logger.info( // "WebDriver desired capabilities Json file was found from path: {}, but no Json data retrieved.", // wdCapsFilePath); // return null; // } // return element; // } // // public synchronized static boolean isCapsExisted(String file) { // return Files.exists(Paths.get(file)); // } // // public synchronized static BufferedReader getCapsJsonReader(String file) { // if (isCapsExisted(file)) { // try { // return new BufferedReader(new FileReader(file)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // return null; // } // } else { // return null; // } // } public static void main(String[] args) throws IOException { System.out.println(getEmulation("chrome")); // System.out.println(JsonPath.using(Configuration.builder().jsonProvider(new GsonJsonProvider()) // .options(DEFAULT_PATH_LEAF_TO_NULL).build()) // .parse(new File(wdCapsFilePath)).read("$.chrome.emulation").toString()); } }
37.92
119
0.637834
68db3f6a15693c1ece68a6ff2cceaeeeca1678cd
3,162
/* */ package com.fasterxml.jackson.core; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public enum StreamWriteFeature /* */ { /* 30 */ AUTO_CLOSE_TARGET(JsonGenerator.Feature.AUTO_CLOSE_TARGET), /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 43 */ AUTO_CLOSE_CONTENT(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT), /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 56 */ FLUSH_PASSED_TO_STREAM(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM), /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 72 */ WRITE_BIGDECIMAL_AS_PLAIN(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN), /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 89 */ STRICT_DUPLICATE_DETECTION(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION), /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 109 */ IGNORE_UNKNOWN(JsonGenerator.Feature.IGNORE_UNKNOWN); /* */ /* */ /* */ /* */ private final boolean _defaultState; /* */ /* */ /* */ /* */ private final int _mask; /* */ /* */ /* */ /* */ private final JsonGenerator.Feature _mappedFeature; /* */ /* */ /* */ /* */ /* */ StreamWriteFeature(JsonGenerator.Feature mappedTo) { /* 127 */ this._mappedFeature = mappedTo; /* 128 */ this._mask = mappedTo.getMask(); /* 129 */ this._defaultState = mappedTo.enabledByDefault(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static int collectDefaults() { /* 138 */ int flags = 0; /* 139 */ for (StreamWriteFeature f : values()) { /* 140 */ if (f.enabledByDefault()) { /* 141 */ flags |= f.getMask(); /* */ } /* */ } /* 144 */ return flags; /* */ } /* */ /* 147 */ public boolean enabledByDefault() { return this._defaultState; } /* 148 */ public boolean enabledIn(int flags) { return ((flags & this._mask) != 0); } public int getMask() { /* 149 */ return this._mask; /* */ } public JsonGenerator.Feature mappedFeature() { /* 151 */ return this._mappedFeature; /* */ } /* */ } /* Location: C:\Users\Main\AppData\Roaming\StreamCraf\\updates\Launcher.jar!\com\fasterxml\jackson\core\StreamWriteFeature.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
19.886792
141
0.367805
0c5e5238080e8239822b955540033ca0a6edebdc
4,049
package com.okcoin.commons.okex.open.api.test.swap; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.okcoin.commons.okex.open.api.bean.swap.param.LevelRateParam; import com.okcoin.commons.okex.open.api.bean.swap.result.ApiAccountsVO; import com.okcoin.commons.okex.open.api.bean.swap.result.ApiDealDetailVO; import com.okcoin.commons.okex.open.api.bean.swap.result.ApiPositionsVO; import com.okcoin.commons.okex.open.api.bean.swap.result.ApiUserRiskVO; import com.okcoin.commons.okex.open.api.service.swap.SwapUserAPIServive; import com.okcoin.commons.okex.open.api.service.swap.impl.SwapUserAPIServiceImpl; import org.junit.Before; import org.junit.Test; import java.math.BigDecimal; import java.util.List; public class SwapUserTest extends SwapBaseTest { private SwapUserAPIServive swapUserAPIServive; @Before public void before() { config = config(); swapUserAPIServive = new SwapUserAPIServiceImpl(config); } @Test public void getPosition() { String jsonObject = swapUserAPIServive.getPosition("LTC-USD-SWAP"); ApiPositionsVO apiPositionsVO = JSONObject.parseObject(jsonObject, ApiPositionsVO.class); System.out.println("success"); apiPositionsVO.getHolding().forEach(vp -> System.out.println(apiPositionsVO.getMargin_mode())); } @Test public void getAccounts() { String jsonObject = swapUserAPIServive.getAccounts(); ApiAccountsVO apiAccountsVO = JSONObject.parseObject(jsonObject, ApiAccountsVO.class); System.out.println("success"); apiAccountsVO.getInfo().forEach(vo -> System.out.println(vo.getInstrument_id())); } @Test public void selectAccount() { String jsonObject = swapUserAPIServive.selectAccount(instrument_id); System.out.println("success"); System.out.println(jsonObject); } @Test public void selectContractSettings() { String jsonObject = swapUserAPIServive.selectContractSettings(instrument_id); ApiUserRiskVO apiUserRiskVO = JSONObject.parseObject(jsonObject, ApiUserRiskVO.class); System.out.println("success"); System.out.println(apiUserRiskVO.getInstrument_id()); } @Test public void updateLevelRate() { LevelRateParam levelRateParam = new LevelRateParam(); levelRateParam.setLevelRate(new BigDecimal(1)); levelRateParam.setSide(1); String jsonObject = swapUserAPIServive.updateLevelRate(instrument_id, levelRateParam); ApiUserRiskVO apiUserRiskVO = JSONObject.parseObject(jsonObject, ApiUserRiskVO.class); System.out.println("success"); System.out.println(apiUserRiskVO.getInstrument_id()); } @Test public void selectOrders() { String jsonObject = swapUserAPIServive.selectOrders(instrument_id, "1", "", "", "20"); System.out.println("success"); System.out.println(jsonObject); } @Test public void selectOrder() { String jsonObject = swapUserAPIServive.selectOrder(instrument_id, "123123"); System.out.println("success"); System.out.println(jsonObject); } @Test public void selectDealDetail(){ String jsonArray = swapUserAPIServive.selectDealDetail(instrument_id,"123123","","",""); if(jsonArray.startsWith("{")){ System.out.println(jsonArray); } else { List<ApiDealDetailVO> apiDealDetailVOS = JSONArray.parseArray(jsonArray, ApiDealDetailVO.class); apiDealDetailVOS.forEach(vo -> System.out.println(vo.getInstrument_id())); } } @Test public void getLedger() { String jsonArray = swapUserAPIServive.getLedger(instrument_id, "1", "", "30"); System.out.println("success"); System.out.println(jsonArray); } @Test public void getHolds() { String jsonObject = swapUserAPIServive.getHolds(instrument_id); System.out.println("success"); System.out.println(jsonObject); } }
36.809091
108
0.701408
c82e0733f6306972860e85d665aa00cf2b29f8aa
1,477
package security.x509; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.CertificateParsingException; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.TBSCertificateStructure; import org.bouncycastle.asn1.x509.X509CertificateStructure; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.provider.X509CertificateObject; public class X509CertificaateGenerator { static { Security.addProvider(new BouncyCastleProvider()); } public static Certificate generator( TBSCertificateStructure v3TBSCertificate, AlgorithmIdentifier algSign, byte[] v3TBSCertSignature) throws CertificateParsingException { // SM2 Alg oid: 1.2.156.10197.1.301 // SM3withSM2 Alg oid: 1.2.156.10197.1.501 if (v3TBSCertificate.getSubjectPublicKeyInfo().getAlgorithmId().getAlgorithm().getId().equals("1.2.156.10197.1.301")) { algSign = new AlgorithmIdentifier("1.2.156.10197.1.501"); } ASN1EncodableVector asn1encodablevector = new ASN1EncodableVector(); asn1encodablevector.add(v3TBSCertificate); asn1encodablevector.add(algSign); asn1encodablevector.add(new DERBitString(v3TBSCertSignature)); return new X509CertificateObject(new X509CertificateStructure( new DERSequence(asn1encodablevector))); } }
38.868421
120
0.811104
dedc2f6ce6518c42eba34600551c2cdad43bfd59
27,657
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.content.integration.crosswalks; import static org.dspace.builder.CollectionBuilder.createCollection; import static org.dspace.builder.CommunityBuilder.createCommunity; import static org.dspace.builder.ItemBuilder.createItem; import static org.dspace.core.CrisConstants.PLACEHOLDER_PARENT_METADATA_VALUE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.nio.charset.Charset; import java.sql.SQLException; import java.util.Arrays; import org.apache.commons.io.IOUtils; import org.dspace.AbstractIntegrationTestWithDatabase; import org.dspace.app.util.DCInputsReader; import org.dspace.app.util.DCInputsReaderException; import org.dspace.authorize.AuthorizeException; import org.dspace.builder.ItemBuilder; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.content.Item; import org.dspace.core.CrisConstants; import org.dspace.utils.DSpace; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Integration tests for the {@link CsvCrosswalkIT}. * * @author Luca Giamminonni (luca.giamminonni at 4science.it) * */ public class CsvCrosswalkIT extends AbstractIntegrationTestWithDatabase { private static final String BASE_OUTPUT_DIR_PATH = "./target/testing/dspace/assetstore/crosswalk/"; private Community community; private Collection collection; private StreamDisseminationCrosswalkMapper crosswalkMapper; private CsvCrosswalk csvCrosswalk; private DCInputsReader dcInputsReader; @Before public void setup() throws SQLException, AuthorizeException, DCInputsReaderException { this.crosswalkMapper = new DSpace().getSingletonService(StreamDisseminationCrosswalkMapper.class); assertThat(crosswalkMapper, notNullValue()); context.turnOffAuthorisationSystem(); community = createCommunity(context).build(); collection = createCollection(context, community).withAdminGroup(eperson).build(); context.restoreAuthSystemState(); dcInputsReader = mock(DCInputsReader.class); when(dcInputsReader.hasFormWithName("traditional-oairecerif-identifier-url")).thenReturn(true); when(dcInputsReader.getAllFieldNamesByFormName("traditional-oairecerif-identifier-url")) .thenReturn(Arrays.asList("oairecerif.identifier.url", "crisrp.site.title")); when(dcInputsReader.hasFormWithName("traditional-oairecerif-person-affiliation")).thenReturn(true); when(dcInputsReader.getAllFieldNamesByFormName("traditional-oairecerif-person-affiliation")) .thenReturn(Arrays.asList("oairecerif.person.affiliation", "oairecerif.affiliation.startDate", "oairecerif.affiliation.endDate", "oairecerif.affiliation.role")); when(dcInputsReader.hasFormWithName("traditional-crisrp-education")).thenReturn(true); when(dcInputsReader.getAllFieldNamesByFormName("traditional-crisrp-education")) .thenReturn(Arrays.asList("crisrp.education", "crisrp.education.start", "crisrp.education.end", "crisrp.education.role")); when(dcInputsReader.hasFormWithName("traditional-crisrp-qualification")).thenReturn(true); when(dcInputsReader.getAllFieldNamesByFormName("traditional-crisrp-qualification")) .thenReturn(Arrays.asList("crisrp.qualification", "crisrp.qualification.start", "crisrp.qualification.end")); when(dcInputsReader.hasFormWithName("traditional-dc-contributor-author")).thenReturn(true); when(dcInputsReader.getAllFieldNamesByFormName("traditional-dc-contributor-author")) .thenReturn(Arrays.asList("dc.contributor.author", "oairecerif.author.affiliation")); when(dcInputsReader.hasFormWithName("traditional-dc-contributor-editor")).thenReturn(true); when(dcInputsReader.getAllFieldNamesByFormName("traditional-dc-contributor-editor")) .thenReturn(Arrays.asList("dc.contributor.editor", "oairecerif.editor.affiliation")); } @After public void after() throws DCInputsReaderException { if (this.csvCrosswalk != null) { this.csvCrosswalk.setDCInputsReader(new DCInputsReader()); } } @Test public void testDisseminateManyPersons() throws Exception { context.turnOffAuthorisationSystem(); Item firstItem = createFullPersonItem(); Item secondItem = createItem(context, collection) .withEntityType("Person") .withTitle("Edward Red") .withGivenName("Edward") .withFamilyName("Red") .withBirthDate("1982-05-21") .withGender("M") .withPersonAffiliation("OrgUnit") .withPersonAffiliationStartDate("2015-01-01") .withPersonAffiliationRole("Developer") .withPersonAffiliationEndDate(PLACEHOLDER_PARENT_METADATA_VALUE) .build(); Item thirdItem = createItem(context, collection) .withTitle("Adam White") .withEntityType("Person") .withGivenName("Adam") .withFamilyName("White") .withBirthDate("1962-03-23") .withGender("M") .withJobTitle("Researcher") .withPersonMainAffiliation("University of Rome") .withPersonKnowsLanguages("English") .withPersonKnowsLanguages("Italian") .withPersonEducation("School") .withPersonEducationStartDate("2000-01-01") .withPersonEducationEndDate("2005-01-01") .withPersonEducationRole("Student") .build(); context.restoreAuthSystemState(); csvCrosswalk = (CsvCrosswalk) crosswalkMapper.getByType("person-csv"); assertThat(csvCrosswalk, notNullValue()); csvCrosswalk.setDCInputsReader(dcInputsReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); csvCrosswalk.disseminate(context, Arrays.asList(firstItem, secondItem, thirdItem).iterator(), out); try (FileInputStream fis = getFileInputStream("persons.csv")) { String expectedCsv = IOUtils.toString(fis, Charset.defaultCharset()); assertThat(out.toString(), equalTo(expectedCsv)); } } @Test public void testDisseminateSinglePerson() throws Exception { context.turnOffAuthorisationSystem(); Item item = createItem(context, collection) .withEntityType("Person") .withTitle("Walter White") .withVariantName("Heisenberg") .withVariantName("W.W.") .withGivenName("Walter") .withFamilyName("White") .withBirthDate("1962-03-23") .withGender("M") .withJobTitle("Professor") .withPersonMainAffiliation("High School") .withPersonKnowsLanguages("English") .withPersonEducation("School") .withPersonEducationStartDate("1968-09-01") .withPersonEducationEndDate("1973-06-10") .withPersonEducationRole("Student") .withPersonEducation("University") .withPersonEducationStartDate("1980-09-01") .withPersonEducationEndDate("1985-06-10") .withPersonEducationRole("Student") .withOrcidIdentifier("0000-0002-9079-5932") .withPersonQualification("Qualification") .withPersonQualificationStartDate(PLACEHOLDER_PARENT_METADATA_VALUE) .withPersonQualificationEndDate(PLACEHOLDER_PARENT_METADATA_VALUE) .build(); context.restoreAuthSystemState(); csvCrosswalk = (CsvCrosswalk) crosswalkMapper.getByType("person-csv"); assertThat(csvCrosswalk, notNullValue()); csvCrosswalk.setDCInputsReader(dcInputsReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); csvCrosswalk.disseminate(context, item, out); try (FileInputStream fis = getFileInputStream("person.csv")) { String expectedCsv = IOUtils.toString(fis, Charset.defaultCharset()); assertThat(out.toString(), equalTo(expectedCsv)); } } @Test public void testDisseminatePublications() throws Exception { context.turnOffAuthorisationSystem(); Item firstItem = createFullPublicationItem(); Item secondItem = ItemBuilder.createItem(context, collection) .withEntityType("Publication") .withTitle("Second Publication") .withDoiIdentifier("doi:222.222/publication") .withType("Controlled Vocabulary for Resource Type Genres::learning object") .withIssueDate("2019-12-31") .withAuthor("Edward Smith") .withAuthorAffiliation("Company") .withAuthor("Walter White") .withVolume("V-02") .withCitationStartPage("1") .withCitationEndPage("20") .withAuthorAffiliation(CrisConstants.PLACEHOLDER_PARENT_METADATA_VALUE) .build(); Item thirdItem = ItemBuilder.createItem(context, collection) .withEntityType("Publication") .withTitle("Another Publication") .withDoiIdentifier("doi:333.333/publication") .withType("Controlled Vocabulary for Resource Type Genres::clinical trial") .withIssueDate("2010-02-01") .withAuthor("Jessie Pinkman") .withDescriptionAbstract("Description of publication") .build(); context.restoreAuthSystemState(); csvCrosswalk = (CsvCrosswalk) crosswalkMapper.getByType("publication-csv"); assertThat(csvCrosswalk, notNullValue()); csvCrosswalk.setDCInputsReader(dcInputsReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); csvCrosswalk.disseminate(context, Arrays.asList(firstItem, secondItem, thirdItem).iterator(), out); try (FileInputStream fis = getFileInputStream("publications.csv")) { String expectedCsv = IOUtils.toString(fis, Charset.defaultCharset()); assertThat(out.toString(), equalTo(expectedCsv)); } } @Test public void testDisseminateProjects() throws Exception { context.turnOffAuthorisationSystem(); Item firstItem = createFullProjectItem(); Item secondItem = ItemBuilder.createItem(context, collection) .withEntityType("Project") .withAcronym("STP") .withTitle("Second Test Project") .withOpenaireId("55-66-77") .withOpenaireId("11-33-22") .withUrlIdentifier("www.project.test") .withProjectStartDate("2010-01-01") .withProjectEndDate("2012-12-31") .withProjectStatus("Status") .withProjectCoordinator("Second Coordinator OrgUnit") .withProjectInvestigator("Second investigator") .withProjectCoinvestigators("Coinvestigator") .withRelationEquipment("Another test equipment") .withOAMandateURL("oamandate") .build(); Item thirdItem = ItemBuilder.createItem(context, collection) .withEntityType("Project") .withAcronym("TTP") .withTitle("Third Test Project") .withOpenaireId("88-22-33") .withUrlIdentifier("www.project.test") .withProjectStartDate("2020-01-01") .withProjectEndDate("2020-12-31") .withProjectStatus("OPEN") .withProjectCoordinator("Third Coordinator OrgUnit") .withProjectPartner("Partner OrgUnit") .withProjectOrganization("Member OrgUnit") .withProjectInvestigator("Investigator") .withProjectCoinvestigators("First coinvestigator") .withProjectCoinvestigators("Second coinvestigator") .withSubject("project") .withSubject("test") .withOAMandate("false") .withOAMandateURL("www.oamandate.com") .build(); context.restoreAuthSystemState(); csvCrosswalk = (CsvCrosswalk) crosswalkMapper.getByType("project-csv"); assertThat(csvCrosswalk, notNullValue()); csvCrosswalk.setDCInputsReader(dcInputsReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); csvCrosswalk.disseminate(context, Arrays.asList(firstItem, secondItem, thirdItem).iterator(), out); try (FileInputStream fis = getFileInputStream("projects.csv")) { String expectedCsv = IOUtils.toString(fis, Charset.defaultCharset()); assertThat(out.toString(), equalTo(expectedCsv)); } } @Test public void testDisseminateOrgUnits() throws Exception { context.turnOffAuthorisationSystem(); Item firstItem = ItemBuilder.createItem(context, collection) .withEntityType("OrgUnit") .withAcronym("TOU") .withTitle("Test OrgUnit") .withOrgUnitLegalName("Test OrgUnit LegalName") .withType("Strategic Research Insitute") .withParentOrganization("Parent OrgUnit") .withOrgUnitIdentifier("ID-01") .withOrgUnitIdentifier("ID-02") .withUrlIdentifier("www.orgUnit.com") .withUrlIdentifier("www.orgUnit.it") .build(); Item secondItem = ItemBuilder.createItem(context, collection) .withEntityType("OrgUnit") .withAcronym("ATOU") .withTitle("Another Test OrgUnit") .withType("Private non-profit") .withParentOrganization("Parent OrgUnit") .withOrgUnitIdentifier("ID-03") .build(); Item thirdItem = ItemBuilder.createItem(context, collection) .withEntityType("OrgUnit") .withAcronym("TTOU") .withTitle("Third Test OrgUnit") .withType("Private non-profit") .withOrgUnitIdentifier("ID-03") .withUrlIdentifier("www.orgUnit.test") .build(); context.restoreAuthSystemState(); csvCrosswalk = (CsvCrosswalk) crosswalkMapper.getByType("orgUnit-csv"); assertThat(csvCrosswalk, notNullValue()); csvCrosswalk.setDCInputsReader(dcInputsReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); csvCrosswalk.disseminate(context, Arrays.asList(firstItem, secondItem, thirdItem).iterator(), out); try (FileInputStream fis = getFileInputStream("orgUnits.csv")) { String expectedCsv = IOUtils.toString(fis, Charset.defaultCharset()); assertThat(out.toString(), equalTo(expectedCsv)); } } @Test public void testDisseminateEquipments() throws Exception { context.turnOffAuthorisationSystem(); Item firstItem = ItemBuilder.createItem(context, collection) .withEntityType("Equipment") .withAcronym("FT-EQ") .withTitle("First Test Equipment") .withInternalId("ID-01") .withDescription("This is an equipment to test the export functionality") .withEquipmentOwnerOrgUnit("Test OrgUnit") .withEquipmentOwnerPerson("Walter White") .build(); Item secondItem = ItemBuilder.createItem(context, collection) .withEntityType("Equipment") .withAcronym("ST-EQ") .withTitle("Second Test Equipment") .withInternalId("ID-02") .withDescription("This is another equipment to test the export functionality") .withEquipmentOwnerPerson("John Smith") .build(); Item thirdItem = ItemBuilder.createItem(context, collection) .withEntityType("Equipment") .withAcronym("TT-EQ") .withTitle("Third Test Equipment") .withInternalId("ID-03") .build(); context.restoreAuthSystemState(); csvCrosswalk = (CsvCrosswalk) crosswalkMapper.getByType("equipment-csv"); assertThat(csvCrosswalk, notNullValue()); csvCrosswalk.setDCInputsReader(dcInputsReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); csvCrosswalk.disseminate(context, Arrays.asList(firstItem, secondItem, thirdItem).iterator(), out); try (FileInputStream fis = getFileInputStream("equipments.csv")) { String expectedCsv = IOUtils.toString(fis, Charset.defaultCharset()); assertThat(out.toString(), equalTo(expectedCsv)); } } @Test public void testDisseminateFundings() throws Exception { context.turnOffAuthorisationSystem(); Item firstItem = ItemBuilder.createItem(context, collection) .withEntityType("Funding") .withAcronym("T-FU") .withTitle("Test Funding") .withType("Gift") .withInternalId("ID-01") .withFundingIdentifier("0001") .withDescription("Funding to test export") .withAmount("30.000,00") .withAmountCurrency("EUR") .withFunder("OrgUnit Funder") .withFundingStartDate("2015-01-01") .withFundingEndDate("2020-01-01") .withOAMandate("true") .withOAMandateURL("www.mandate.url") .build(); Item secondItem = ItemBuilder.createItem(context, collection) .withEntityType("Funding") .withAcronym("AT-FU") .withTitle("Another Test Funding") .withType("Grant") .withInternalId("ID-02") .withFundingIdentifier("0002") .withAmount("10.000,00") .withFunder("Test Funder") .withFundingStartDate("2020-01-01") .withOAMandate("true") .withOAMandateURL("www.mandate.url") .build(); Item thirdItem = ItemBuilder.createItem(context, collection) .withEntityType("Funding") .withAcronym("TT-FU") .withTitle("Third Test Funding") .withType("Grant") .withInternalId("ID-03") .withFundingIdentifier("0003") .withAmount("20.000,00") .withAmountCurrency("EUR") .withFundingEndDate("2010-01-01") .withOAMandate("false") .withOAMandateURL("www.mandate.com") .build(); context.restoreAuthSystemState(); csvCrosswalk = (CsvCrosswalk) crosswalkMapper.getByType("funding-csv"); assertThat(csvCrosswalk, notNullValue()); csvCrosswalk.setDCInputsReader(dcInputsReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); csvCrosswalk.disseminate(context, Arrays.asList(firstItem, secondItem, thirdItem).iterator(), out); try (FileInputStream fis = getFileInputStream("fundings.csv")) { String expectedCsv = IOUtils.toString(fis, Charset.defaultCharset()); assertThat(out.toString(), equalTo(expectedCsv)); } } @Test public void testDisseminatePatents() throws Exception { context.turnOffAuthorisationSystem(); Item firstItem = ItemBuilder.createItem(context, collection) .withEntityType("Patent") .withTitle("First patent") .withDateAccepted("2020-01-01") .withIssueDate("2021-01-01") .withLanguage("en") .withType("patent") .withPublisher("First publisher") .withPublisher("Second publisher") .withPatentNo("12345-666") .withAuthor("Walter White", "b6ff8101-05ec-49c5-bd12-cba7894012b7") .withAuthorAffiliation("4Science") .withAuthor("Jesse Pinkman") .withAuthorAffiliation(PLACEHOLDER_PARENT_METADATA_VALUE) .withAuthor("John Smith", "will be referenced::ORCID::0000-0000-0012-3456") .withAuthorAffiliation("4Science") .withRightsHolder("Test Organization") .withDescriptionAbstract("This is a patent") .withRelationPatent("Another patent") .withSubject("patent") .withSubject("test") .withRelationFunding("Test funding") .withRelationProject("First project") .withRelationProject("Second project") .build(); Item secondItem = ItemBuilder.createItem(context, collection) .withEntityType("Patent") .withTitle("second patent") .withType("patent") .withPatentNo("12345-777") .withAuthor("Bruce Wayne") .withRelationPatent("Another patent") .withSubject("second") .withRelationFunding("Funding") .build(); Item thirdItem = ItemBuilder.createItem(context, collection) .withEntityType("Patent") .withTitle("Third patent") .withDateAccepted("2019-01-01") .withLanguage("ita") .withPublisher("Publisher") .withPatentNo("12345-888") .withRightsHolder("Organization") .withDescriptionAbstract("Patent description") .withRelationPatent("Another patent") .withRelationFunding("First funding") .withRelationFunding("Second funding") .build(); context.restoreAuthSystemState(); csvCrosswalk = (CsvCrosswalk) crosswalkMapper.getByType("patent-csv"); assertThat(csvCrosswalk, notNullValue()); csvCrosswalk.setDCInputsReader(dcInputsReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); csvCrosswalk.disseminate(context, Arrays.asList(firstItem, secondItem, thirdItem).iterator(), out); try (FileInputStream fis = getFileInputStream("patents.csv")) { String expectedCsv = IOUtils.toString(fis, Charset.defaultCharset()); assertThat(out.toString(), equalTo(expectedCsv)); } } private Item createFullPersonItem() { Item item = createItem(context, collection) .withTitle("John Smith") .withEntityType("Person") .withFullName("John Smith") .withVernacularName("JOHN SMITH") .withVariantName("J.S.") .withVariantName("Smith John") .withGivenName("John") .withFamilyName("Smith") .withBirthDate("1992-06-26") .withGender("M") .withJobTitle("Researcher") .withPersonMainAffiliation("University") .withWorkingGroup("First work group") .withWorkingGroup("Second work group") .withPersonalSiteUrl("www.test.com") .withPersonalSiteTitle("Test") .withPersonalSiteUrl("www.john-smith.com") .withPersonalSiteTitle(PLACEHOLDER_PARENT_METADATA_VALUE) .withPersonalSiteUrl("www.site.com") .withPersonalSiteTitle("Site") .withPersonEmail("[email protected]") .withSubject("Science") .withOrcidIdentifier("0000-0002-9079-5932") .withScopusAuthorIdentifier("111") .withResearcherIdentifier("r1") .withResearcherIdentifier("r2") .withPersonAffiliation("Company") .withPersonAffiliationStartDate("2018-01-01") .withPersonAffiliationRole("Developer") .withPersonAffiliationEndDate(PLACEHOLDER_PARENT_METADATA_VALUE) .withDescriptionAbstract("Biography: \n\t\"This is my biography\"") .withPersonCountry("England") .withPersonKnowsLanguages("English") .withPersonKnowsLanguages("Italian") .withPersonEducation("School") .withPersonEducationStartDate("2000-01-01") .withPersonEducationEndDate("2005-01-01") .withPersonEducationRole("Student") .withPersonQualification("First Qualification") .withPersonQualificationStartDate("2015-01-01") .withPersonQualificationEndDate("2016-01-01") .withPersonQualification("Second Qualification") .withPersonQualificationStartDate("2016-01-02") .withPersonQualificationEndDate(PLACEHOLDER_PARENT_METADATA_VALUE) .build(); return item; } private Item createFullPublicationItem() { return ItemBuilder.createItem(context, collection) .withEntityType("Publication") .withTitle("Test Publication") .withAlternativeTitle("Alternative publication title") .withRelationPublication("Published in publication") .withRelationDoi("doi:10.3972/test") .withDoiIdentifier("doi:111.111/publication") .withIsbnIdentifier("978-3-16-148410-0") .withIssnIdentifier("2049-3630") .withIsiIdentifier("111-222-333") .withScopusIdentifier("99999999") .withLanguage("en") .withPublisher("Publication publisher") .withVolume("V.01") .withIssue("Issue") .withSubject("test") .withSubject("export") .withType("Controlled Vocabulary for Resource Type Genres::text::review") .withIssueDate("2020-01-01") .withAuthor("John Smith") .withAuthorAffiliation(CrisConstants.PLACEHOLDER_PARENT_METADATA_VALUE) .withAuthor("Walter White") .withAuthorAffiliation("Company") .withEditor("Editor") .withEditorAffiliation("Editor Affiliation") .withRelationConference("The best Conference") .withRelationProduct("DataSet") .build(); } private Item createFullProjectItem() { return ItemBuilder.createItem(context, collection) .withEntityType("Project") .withAcronym("TP") .withTitle("Test Project") .withOpenaireId("11-22-33") .withUrlIdentifier("www.project.test") .withProjectStartDate("2020-01-01") .withProjectEndDate("2020-12-31") .withProjectStatus("OPEN") .withProjectCoordinator("Coordinator OrgUnit") .withProjectPartner("Partner OrgUnit") .withProjectPartner("Another Partner OrgUnit") .withProjectOrganization("First Member OrgUnit") .withProjectOrganization("Second Member OrgUnit") .withProjectOrganization("Third Member OrgUnit") .withProjectInvestigator("Investigator") .withProjectCoinvestigators("First coinvestigator") .withProjectCoinvestigators("Second coinvestigator") .withRelationEquipment("Test equipment") .withSubject("project") .withSubject("test") .withDescriptionAbstract("This is a project to test the export") .withOAMandate("true") .withOAMandateURL("oamandate-url") .build(); } private FileInputStream getFileInputStream(String name) throws FileNotFoundException { return new FileInputStream(new File(BASE_OUTPUT_DIR_PATH, name)); } }
41.652108
107
0.645623
8befdbcbbb9f347257868c22da1d6b2bd52dee2c
1,358
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.ap.checks; import java.util.Collections; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.TypeElement; import org.hibernate.validator.ap.util.CollectionHelper; import org.hibernate.validator.ap.util.ConstraintHelper; /** * Checks, that only constraint annotation types are annotated with other * constraint annotations ("constraint composition"), but not non-constraint * annotations. * * @author Gunnar Morling */ public class AnnotationTypeCheck extends AbstractConstraintCheck { private final ConstraintHelper constraintHelper; public AnnotationTypeCheck(ConstraintHelper constraintHelper) { this.constraintHelper = constraintHelper; } @Override public Set<ConstraintCheckIssue> checkAnnotationType(TypeElement element, AnnotationMirror annotation) { if ( !constraintHelper.isConstraintAnnotation( element ) ) { return CollectionHelper.asSet( ConstraintCheckIssue.error( element, annotation, "ONLY_CONSTRAINT_ANNOTATIONS_MAY_BE_ANNOTATED" ) ); } return Collections.emptySet(); } }
27.16
98
0.773196
4cc98e40276cb4fc412a18a60270804865d102f8
1,471
/** * Copyright (c) 2000-present Liferay, 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 com.liferay.blade.cli.util; /** * @author Gregory Amerson */ public class StringPool { public static final String ASTERISK = "*"; public static final String BLANK = ""; public static final String COLON = ":"; public static final String COMMA = ","; public static final String DASH = "-"; public static final String DOUBLE_ASTERISK = "**"; public static final String DOUBLE_QUOTE = "\""; public static final char DOUBLE_QUOTE_CHAR = '\"'; public static final String EMPTY = BLANK; public static final String EQUALS = "="; public static final String FORWARD_SLASH = "/"; public static final String PERIOD = "."; public static final String SINGLE_QUOTE = "\'"; public static final char SINGLE_QUOTE_CHAR = '\''; public static final String SPACE = " "; public static final String UNDERSCORE = "_"; }
26.267857
75
0.71312
6e2548d30f8480b7384ecece46791ac862ea96d5
1,020
package co.popapp.util.tree; import java.util.Comparator; import java.util.List; /** * Supplies the needed behaviour to buildTree a table from a list of entities. Essentially this is * providing a list with an Entity's parents and sorting them taking care of the parents. Ie: * * <pre> * Asuming: * * ENTITIES: E1, E2, E3, E4, E5 * * ENTITIES PARENTS: * - E1 -> P11, P22, P33 * - E2 -> P12, P21, P34 * - E3 -> P11, P22, P35 * - E4 -> P13, P23, P33 * * ORDERED TABLE: * - E1 -> P11, P22, P33 * - E3 -> P11, P22, P35 * - E2 -> P12, P21, P34 * - E4 -> P13, P23, P33 * * TREE: * * - ROOT * - P11 * - P22 * - P33 * - E1 * - P35 * - E3 * - P12 * - P21 * - P34 * - E2 * - P13 * - P23 * - P33 * - E4 * </pre> * * @param <E> Type of the entities from which the builder will arrange a tree (tree leaves). * @author jamming */ public interface TreeBuilder<E> extends Comparator<E>, TreeLeaf<E> {}
20.4
98
0.532353
d779b309fe6dc2e310ff47933b87993998b7e5c1
9,615
/* * Copyright 2017-2020 Frederic Thevenet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.binjr.core.data.adapters; import eu.binjr.common.logging.Logger; import eu.binjr.common.plugins.ServiceLoaderHelper; import eu.binjr.common.version.Version; import eu.binjr.core.data.exceptions.CannotInitializeDataAdapterException; import eu.binjr.core.data.exceptions.NoAdapterFoundException; import eu.binjr.core.data.workspace.ReflectionHelper; import eu.binjr.core.dialogs.DataAdapterDialog; import eu.binjr.core.preferences.AppEnvironment; import eu.binjr.core.preferences.UserPreferences; import javafx.scene.Node; import javafx.scene.control.Dialog; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * Defines methods to discover and create new instances of available {@link DataAdapter} classes * * @author Frederic Thevenet */ public class DataAdapterFactory { private static final Logger logger = Logger.create(DataAdapterFactory.class); private final Map<String, DataAdapterInfo> registeredAdapters = new ConcurrentHashMap<>(); private final static Version MINIMUM_API_LEVEL = Version.parseVersion(AppEnvironment.MINIMUM_PLUGIN_API_LEVEL); private final static Version CURRENT_API_LEVEL = Version.parseVersion(AppEnvironment.PLUGIN_API_LEVEL); /** * Initializes a new instance if the {@link DataAdapterFactory} class. */ private DataAdapterFactory() { // An exception here could prevent the app from starting try { var pluginPaths = new ArrayList<Path>(); var adapters = new HashSet<DataAdapterInfo>(); // Load from classpath ServiceLoaderHelper.loadFromClasspath(DataAdapterInfo.class, adapters); // Add system plugin location pluginPaths.add(AppEnvironment.getInstance().getSystemPluginPath()); // Add user plugin location if (UserPreferences.getInstance().loadPluginsFromExternalLocation.get()) { pluginPaths.add(UserPreferences.getInstance().userPluginsLocation.get()); } var ucl = ServiceLoaderHelper.loadFromPaths(DataAdapterInfo.class,adapters, pluginPaths); // Scan loaded plugins for serialisable types ReflectionHelper.INSTANCE.scanClassLoader(ucl); // register adapters for (var dataAdapterInfo : adapters) { if (dataAdapterInfo.getApiLevel().compareTo(MINIMUM_API_LEVEL) < 0) { logger.warn("Cannot load plugin " + dataAdapterInfo.getName() + ": Its target API level (" + dataAdapterInfo.getApiLevel() + ") is less than the minimum required (" + MINIMUM_API_LEVEL + ")"); } else if (dataAdapterInfo.getApiLevel().compareTo(CURRENT_API_LEVEL) > 0) { logger.warn("Cannot load plugin " + dataAdapterInfo.getName() + ": Its target API level (" + dataAdapterInfo.getApiLevel() + ") is higher than this version's level (" + CURRENT_API_LEVEL + ")"); } else { registeredAdapters.put(dataAdapterInfo.getKey(), dataAdapterInfo); } } } catch (Throwable e) { logger.error("Error loading adapters", e); } } /** * Gets the singleton instance of {@link DataAdapterFactory} * * @return the singleton instance of {@link DataAdapterFactory} */ public static DataAdapterFactory getInstance() { return DataAdapterFactoryHolder.instance; } /** * Gets a collection of {@link DataAdapterInfo} for all active (enabled) {@link DataAdapter} * * @return a collection of {@link DataAdapterInfo} for all active (enabled) {@link DataAdapter} */ public Collection<DataAdapterInfo> getActiveAdapters() { return registeredAdapters.values().stream() .filter(DataAdapterInfo::isEnabled) .sorted(Comparator.comparing(DataAdapterInfo::getName)) .collect(Collectors.toList()); } /** * Gets a collection of {@link DataAdapterInfo} for all registered {@link DataAdapter} * * @return a collection of {@link DataAdapterInfo} for all registered {@link DataAdapter} */ public Collection<DataAdapterInfo> getAllAdapters() { return registeredAdapters.values().stream() .sorted(Comparator.comparing(DataAdapterInfo::getName)) .collect(Collectors.toList()); } /** * Returns a new instance of a registered {@link DataAdapter} as identified by the specified key * * @param info a {@link DataAdapterInfo} instance used as a key * @return a new instance of {@link DataAdapter} * @throws NoAdapterFoundException if no registered {@link DataAdapter} could be found for the provided key * @throws CannotInitializeDataAdapterException if an error occurred while trying to create a new instance. */ public DataAdapter newAdapter(DataAdapterInfo info) throws NoAdapterFoundException, CannotInitializeDataAdapterException { return newAdapter(info.getKey()); } /** * Returns an instance of {@link DataAdapterDialog} used to gather source access parameters from the end user. * * @param key a string that uniquely identify the type of the {@link DataAdapter} * @param root the root node to act as the owner of the Dialog * @return an instance of {@link DataAdapterDialog} used to gather source access parameters from the end user. * @throws NoAdapterFoundException if no adapter matching the provided key could be found * @throws CannotInitializeDataAdapterException if an error occurred while trying to create a new instance. */ public Dialog<Collection<DataAdapter>> getDialog(String key, Node root) throws NoAdapterFoundException, CannotInitializeDataAdapterException { try { return getDataAdapterInfo(key).getAdapterDialog().getDeclaredConstructor(Node.class).newInstance(root); } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { throw new CannotInitializeDataAdapterException("Could not create instance of DataAdapterDialog for " + key, e); } } /** * Returns a new instance of a registered {@link DataAdapter} as identified by the specified key * * @param key a string used as a key * @return a new instance of {@link DataAdapter} * @throws NoAdapterFoundException if no registered {@link DataAdapter} could be found for the provided key * @throws CannotInitializeDataAdapterException if an error occurred while trying to create a new instance. */ public DataAdapter<?> newAdapter(String key) throws NoAdapterFoundException, CannotInitializeDataAdapterException { try { return getDataAdapterInfo(key).getAdapterClass().getDeclaredConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new CannotInitializeDataAdapterException("Could not create instance of adapter " + key, e); } } /** * Returns the {@link DataAdapterInfo} for the specified key * * @param key the key that identifies the {@link DataAdapterInfo} to return. * @return the {@link DataAdapterInfo} for the specified key * @throws NoAdapterFoundException if no registered adapter could be found for the specified key. */ public DataAdapterInfo getDataAdapterInfo(String key) throws NoAdapterFoundException { Objects.requireNonNull(key, "The parameter 'key' cannot be null!"); DataAdapterInfo info = registeredAdapters.get(key); if (info == null) { throw new NoAdapterFoundException("Could not find a registered adapter for key " + key); } return info; } /** * Returns the {@link DataAdapterPreferences} for the specified key * * @param key the key that identifies the {@link DataAdapterPreferences} to return. * @return the {@link DataAdapterPreferences} for the specified key * @throws NoAdapterFoundException if no registered adapter could be found for the specified key. */ public DataAdapterPreferences getAdapterPreferences(String key) throws NoAdapterFoundException { return (DataAdapterPreferences) getDataAdapterInfo(key).getPreferences(); } private static class DataAdapterFactoryHolder { private static final DataAdapterFactory instance = new DataAdapterFactory(); } }
47.364532
126
0.678211
b6663f6ec384a90870f770848d1b6174ebb9fd18
768
package calc; import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.URL; class CalcClient { public static void main(String args[]) throws Exception { URL url = new URL("http://127.0.0.1:9876/calc?wsdl"); QName qname = new QName("http://calc/", "CalcServerImplService"); Service ws = Service.create(url, qname); CalcServer calc = ws.getPort(CalcServer.class); System.out.println("Exemplo de soma entre os fatores 4 e 6: " + calc.soma(4, 6)); System.out.println("Exemplo de subtracao entre os fatores 5 e 3: " + calc.subtrai(5, 3)); System.out.println("Exemplo de divisao entre os fatores 21 e 3: " + calc.divide(21, 3)); System.out.println("Exemplo de multiplicacao entre os fatores 3 e 8: " + calc.multiplica(3, 8)); } }
40.421053
98
0.704427
799e500025da90049ba273271ea977d62610f1a2
1,543
package com.lelloman.lousyaudiolibrary.algorithm; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.DoubleBuffer; public class Fft { static { System.loadLibrary("mylib"); } // size of the output (complex) public final int size; ByteBuffer byteBuffer; public Fft(int size){ this.size = size; int nativeBufferSize = Double.SIZE / 8 * size; byteBuffer = ByteBuffer.allocateDirect(nativeBufferSize); byteBuffer.order(ByteOrder.nativeOrder()); } public void realForward(double[] data){ DoubleBuffer doubleBuffer = byteBuffer.asDoubleBuffer(); doubleBuffer.put(data); forward(byteBuffer, size/2); byteBuffer.asDoubleBuffer().get(data); } public void realForwardMagnitude(double[] data){ DoubleBuffer doubleBuffer = byteBuffer.asDoubleBuffer(); doubleBuffer.put(data); forwardMagnitude(byteBuffer, size/2); byteBuffer.asDoubleBuffer().get(data); } public void realInverse(double[] data){ DoubleBuffer doubleBuffer = byteBuffer.asDoubleBuffer(); doubleBuffer.put(data); inverse(byteBuffer, size/2, true); byteBuffer.asDoubleBuffer().get(data); } private native void forward(ByteBuffer byteBuffer, int size); private native void forwardMagnitude(ByteBuffer byteBuffer, int size); private native void inverse(ByteBuffer byteBuffer, int size, boolean scale); private native void dummy(ByteBuffer byteBuffer, int size); public native void testArrayCopySingleThread(int size, int iterations); public native void testArrayCopyMultiThread(int size, int iterations); }
26.152542
77
0.76604
d53f2013575bf8d39713afcffa0421b1356950bb
7,950
package com.example.jackson.step; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.jackson.step.database.DatabaseQuestionaire; public class QuestionnaireActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { private static final String TAG="tag"; private QuestionLibrary mQuestionLibrary = new QuestionLibrary(); private TextView myStageView; private TextView mQuestionView; private EditText specifyInput; private Button nextButton; private Button quitButton; private Spinner spinner; private String mAnswer; private String mAnswerFromSpinner; private String mSpecify; private int mQuestionNumber = 1; DatabaseQuestionaire dbQuestionaire; SQLiteDatabase myDB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_questionnaire); dbQuestionaire = new DatabaseQuestionaire(this); myDB = dbQuestionaire.getWritableDatabase(); dbQuestionaire.onCreate(myDB); myStageView = (TextView)findViewById(R.id.score); mQuestionView = (TextView)findViewById(R.id.question); nextButton = (Button)findViewById(R.id.next); quitButton = (Button)findViewById(R.id.quit); spinner = (Spinner) findViewById(R.id.spinner); specifyInput = (EditText)findViewById(R.id.specifyInput); specifyInput.setEnabled(false); specifyInput.setInputType(InputType.TYPE_NULL); specifyInput.setFocusable(false); spinner.setOnItemSelectedListener(this); updateQuestion(); nextButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ //My logic for Button goes in here if (mQuestionNumber == 6){ SharedPreferences mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE); SharedPreferences.Editor editor = mPreferences.edit(); editor.putBoolean("questionaire", true); editor.commit(); Intent intent = new Intent(QuestionnaireActivity.this, MainActivity.class); startActivity(intent); finish(); SaveToDatabase(5,spinner.getSelectedItem().toString()); } else{ if (needSpecify()){ Toast.makeText(QuestionnaireActivity.this, "Please enter your answer", Toast.LENGTH_SHORT).show(); specifyInput.setEnabled(true); specifyInput.setInputType(InputType.TYPE_CLASS_TEXT); specifyInput.setFocusableInTouchMode(true); specifyInput.setFocusable(true); } else { updateQuestion(); } } } }); quitButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ System.exit(0); finish(); } }); //End of Button Listener for Button3 } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } private void updateQuestion(){ if (mQuestionNumber!=1) { mAnswer = spinner.getSelectedItem().toString(); if (mAnswer.contains("(please specify)")){ mSpecify = specifyInput.getText().toString(); Toast.makeText(QuestionnaireActivity.this, mSpecify, Toast.LENGTH_SHORT).show(); SaveToDatabase(mQuestionNumber-1,spinner.getSelectedItem().toString()); specifyInput.getText().clear(); mSpecify=null; } else { Toast.makeText(QuestionnaireActivity.this, mAnswerFromSpinner, Toast.LENGTH_SHORT).show(); SaveToDatabase(mQuestionNumber-1,mAnswerFromSpinner); } } if(mQuestionNumber==1){ mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber-1)); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.question_1, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } else if(mQuestionNumber==2){ mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber-1)); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.question_2, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } else if(mQuestionNumber==3){ mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber-1)); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.question_3, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } else if(mQuestionNumber==4){ mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber-1)); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.question_4, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } else if(mQuestionNumber==5){ mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber-1)); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.question_5, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } specifyInput.setEnabled(false); specifyInput.setInputType(InputType.TYPE_NULL); specifyInput.setFocusable(false); myStageView.setText("" + mQuestionNumber+"/5"); mQuestionNumber++; } public boolean needSpecify(){ mAnswerFromSpinner = spinner.getSelectedItem().toString(); mSpecify = specifyInput.getText().toString(); if (mAnswerFromSpinner.contains("(please specify)" )&& mSpecify.matches("")){ return true; } else{ return false; } } public void SaveToDatabase(int Question, String Answer){ Log.i(TAG, "Adding question to dababase:" + Question); dbQuestionaire.insertData(Question, Answer); } @Override public void onPointerCaptureChanged(boolean hasCapture) { } }
36.46789
122
0.642893
4190349eedd2a54511256cb59acf57446b8c5fde
5,078
package aug.bueno.coffeeshop.reward.tests; import aug.bueno.coffeeshop.product.Product; import aug.bueno.coffeeshop.product.SpecialProductsEnum; import aug.bueno.coffeeshop.reward.RewardByGiftService; import aug.bueno.coffeeshop.reward.RewardInformation; import aug.bueno.coffeeshop.reward.tests.argument.converter.ProductArgumentConverter; import aug.bueno.coffeeshop.reward.tests.argument.provider.ProductIdArgumentsProvider; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.converter.ConvertWith; import org.junit.jupiter.params.provider.*; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertTrue; public class RewardByGiftServiceParameterizedTest { private RewardByGiftService reward = null; @BeforeEach void setUp() { reward = new RewardByGiftService(); reward.setNeededPoints(100); System.out.println("BeforeEach"); } @ParameterizedTest @ValueSource(longs = { 1, 2, 3, 4 }) void discountShouldBeApplied(long productId) { reward.setGiftProductId(productId); RewardInformation info = reward.applyReward( getSampleOrder(), 200); assertTrue(info.getDiscount() > 0); } @ParameterizedTest //@EnumSource(SpecialProductsEnum.class) //@EnumSource(value = SpecialProductsEnum.class, names = { "BIG_LATTE", "BIG_TEA" }) //@EnumSource(value = SpecialProductsEnum.class, names = { "BIG_LATTE", "BIG_TEA" }, mode = EnumSource.Mode.EXCLUDE) @EnumSource(value = SpecialProductsEnum.class, names = "^BIG.*", mode = EnumSource.Mode.MATCH_ALL) void discountShouldBeAppliedEnumSource(SpecialProductsEnum product) { reward.setGiftProductId(product.getProductId()); RewardInformation info = reward.applyReward( getSampleOrder(), 200); assertTrue(info.getDiscount() > 0); } @ParameterizedTest @MethodSource("productIds") void discountShouldBeAppliedMethodSource(long productId) { reward.setGiftProductId(productId); RewardInformation info = reward.applyReward( getSampleOrder(), 200); assertTrue(info.getDiscount() > 0); } @ParameterizedTest @MethodSource("productIdsCustomerPoints") void discountShouldBeAppliedMethodSourceMultipleParams(long productId, long customerPoints) { reward.setGiftProductId(productId); RewardInformation info = reward.applyReward( getSampleOrder(), customerPoints); assertTrue(info.getDiscount() > 0); } @ParameterizedTest @CsvSource({ "1, 200", "2, 150", "5, 100" }) void discountShouldBeAppliedCsvSource(long productId, long customerPoints) { reward.setGiftProductId(productId); RewardInformation info = reward.applyReward( getSampleOrder(), customerPoints); assertTrue(info.getDiscount() > 0); } @ParameterizedTest @CsvFileSource(resources = "/product-point-data.csv") void discountShouldBeAppliedCsvFileSource(long productId, long customerPoints) { reward.setGiftProductId(productId); RewardInformation info = reward.applyReward( getSampleOrder(), customerPoints); assertTrue(info.getDiscount() > 0); } @ParameterizedTest @ArgumentsSource(ProductIdArgumentsProvider.class) void discountShouldBeAppliedArgumentsSource(long productId, long customerPoints) { reward.setGiftProductId(productId); RewardInformation info = reward.applyReward( getSampleOrder(), customerPoints); assertTrue(info.getDiscount() > 0); } @ParameterizedTest @ValueSource(strings = { "1; Small Decaf; 1.99", "2; Big Decaf; 2.49" }) void discountShouldBeApplied( @ConvertWith(ProductArgumentConverter.class) Product product) { System.out.println("Testing product " + product.getName()); reward.setGiftProductId(product.getId()); RewardInformation info = reward.applyReward( getSampleOrder(), 200); assertTrue(info.getDiscount() > 0); } static Stream<Arguments> productIdsCustomerPoints() { return productIds() .mapToObj( productId -> Arguments.of(productId, 100 * productId) // Object ... arguments ); } private static LongStream productIds() { return LongStream.range(1, 6); } private List<Product> getSampleOrder() { Product smallDecaf = new Product(1, "Small Decaf", 1.99); Product bigDecaf = new Product(2, "Big Decaf", 2.49); Product bigLatte = new Product(3, "Big Latte", 2.99); Product bigTea = new Product(4, "Big Tea", 2.99); Product espresso = new Product(5, "Espresso", 2.99); return Arrays.asList( smallDecaf, bigDecaf, bigLatte, bigTea, espresso); } }
36.797101
120
0.681371
225569f9fea662f1d8b4d1597fa19e7ee281017b
106
package org.goodiemania.melinoe.framework.drivers; public interface ClosableDriver { void close(); }
17.666667
50
0.773585
736d21c625932c3debdf84d77031425898aea367
17,250
package me.ci.Community; import java.util.HashMap; import java.util.Map; import me.ci.WhCommunity; import me.ci.Conquest.Buildings.Constructors.Flag; import me.ci.Conquest.KingdomManagment.KingdomCommand; import me.ci.Conquest.KingdomManagment.KingdomMaker; import me.ci.Conquest.KingdomManagment.KingdomMg; import me.ci.Conquest.Misc.ToolBarActions; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockIgniteEvent.IgniteCause; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.EntityBreakDoorEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.painting.PaintingBreakByEntityEvent; import org.bukkit.event.painting.PaintingBreakEvent; import org.bukkit.event.painting.PaintingBreakEvent.RemoveCause; import org.bukkit.event.painting.PaintingPlaceEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerBucketFillEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; @SuppressWarnings("deprecation") public class AntiGreif{ public static Map<String,Integer> channels = new HashMap<String,Integer>(); public static void e(PlayerBucketEmptyEvent e){ Player p = e.getPlayer(); Block bc = e.getBlockClicked(); BlockFace bf = e.getBlockFace(); Location l = bc.getLocation(); if(bf.equals(BlockFace.UP))l.add(0, 1, 0); else if(bf.equals(BlockFace.DOWN))l.add(0, -1, 0); else if(bf.equals(BlockFace.EAST))l.add(1, 0, 0); else if(bf.equals(BlockFace.WEST))l.add(-1, 0, 0); else if(bf.equals(BlockFace.SOUTH))l.add(0, 0, 1); else if(bf.equals(BlockFace.NORTH))l.add(0, 0, -1); if(!PlayerMg.hasBuildPermission(l, p)){ e.setCancelled(true); yellAtPlayer(l, p); } } public static void yellAtPlayer(Location l, Player p){ p.sendMessage(ChatColor.RED+"No permission for area!"); try{ l.getWorld().playEffect(l, Effect.MOBSPAWNER_FLAMES, 0); l.getWorld().playEffect(l, Effect.EXTINGUISH, 0); }catch(Exception exception){} } public static void e(PlayerBucketFillEvent e){ Player p = e.getPlayer(); Location l = e.getBlockClicked().getLocation(); if(!PlayerMg.hasBuildPermission(l, p)){ e.setCancelled(true); yellAtPlayer(l, p); } } public static void e(PaintingBreakByEntityEvent e){ Entity mob = e.getRemover(); if(mob instanceof Player){ Player p = (Player)mob; Location l = e.getPainting().getLocation(); if(!PlayerMg.hasBuildPermission(l, p)){ e.setCancelled(true); yellAtPlayer(l, p); } }else e.setCancelled(true); } public static void e(PaintingBreakEvent e){ RemoveCause reason = e.getCause(); WorldSettings settings = WhCommunity.getWorldSettings(e.getPainting().getWorld().getName()); if(reason.equals(RemoveCause.FIRE) &&!settings.CONFIG_Fire_Spread)e.setCancelled(true); } public static void e(PaintingPlaceEvent e){ Player p = e.getPlayer(); Location l = e.getPainting().getLocation(); if(!PlayerMg.hasBuildPermission(l, p)){ e.setCancelled(true); yellAtPlayer(l, p); } } public static void e(BlockBreakEvent e){ Player p = e.getPlayer(); Location l = e.getBlock().getLocation(); if(!PlayerMg.hasBuildPermission(l, p)){ e.setCancelled(true); yellAtPlayer(l, p); } } public static void e(BlockPlaceEvent e){ final Player p = e.getPlayer(); final Block b = e.getBlock(); final Location l = b.getLocation(); if(!PlayerMg.hasBuildPermission(l, p)){ e.setCancelled(true); yellAtPlayer(l, p); }else{ if(p.hasPermission("whc.cmd.kingdom.savechunk") &&KingdomCommand.flagsPlanted.containsKey(p.getName()) &&KingdomCommand.flagsPlanted.get(p.getName())==null){ ItemStack item = p.getItemInHand(); if(item!=null&&item.getTypeId()==Material.FENCE.getId()){ KingdomCommand.flagsPlanted.put(p.getName(), l); e.setCancelled(true); } } } } public static void e(EntityBreakDoorEvent e){ e.setCancelled(true); } public static void e(EntityChangeBlockEvent e){ e.setCancelled(true); } public static void e(BlockBurnEvent e){ Location l = e.getBlock().getLocation(); WorldSettings settings = WhCommunity.getWorldSettings(l.getWorld().getName()); if(!settings.CONFIG_Fire_Spread)e.setCancelled(true); } public static void e(BlockIgniteEvent e){ IgniteCause reason = e.getCause(); Location l = e.getBlock().getLocation(); WorldSettings settings = WhCommunity.getWorldSettings(l.getWorld().getName()); if(reason.equals(IgniteCause.FLINT_AND_STEEL)){ Player p = e.getPlayer(); if(!PlayerMg.hasBuildPermission(l, p)){ e.setCancelled(true); yellAtPlayer(l, p); } }else if(!settings.CONFIG_Fire_Spread)e.setCancelled(true); } public static void e(BlockFromToEvent e){ Plot p1 = PlotMg.getPlotAt(e.getBlock().getChunk()); Plot p2 = PlotMg.getPlotAt(e.getToBlock().getChunk()); WorldSettings settings = WhCommunity.getWorldSettings(e.getBlock().getWorld().getName()); if(settings.CONFIG_Plot_Barrier_Liquid_Flow){ if(p1.getX()!=p2.getX() ||p1.getZ()!=p2.getZ() &&p2.isClaimed()){ if(p1.isClaimed()&&!p1.getOwner().equals(p2.getOwner()))return; else e.setCancelled(true); } } } public static void e(EntityExplodeEvent e){ WorldSettings settings = WhCommunity.getWorldSettings(e.getLocation().getWorld().getName()); if(!settings.CONFIG_Explosions)e.blockList().clear(); } public static void e(CreatureSpawnEvent e){ if(e.isCancelled())return; SpawnReason reason = e.getSpawnReason(); EntityType mob = e.getEntityType(); WorldSettings settings = WhCommunity.getWorldSettings(e.getLocation().getWorld().getName()); if(reason.equals(SpawnReason.CUSTOM)){ if(!settings.CONFIG_Spawn_Mobs_Plugin)e.setCancelled(true); }else{ boolean hostile = true; if(mob.equals(EntityType.BAT))hostile=false; else if(mob.equals(EntityType.CHICKEN))hostile=false; else if(mob.equals(EntityType.COW))hostile=false; else if(mob.equals(EntityType.IRON_GOLEM))hostile=false; else if(mob.equals(EntityType.MUSHROOM_COW))hostile=false; else if(mob.equals(EntityType.OCELOT))hostile=false; else if(mob.equals(EntityType.PIG))hostile=false; else if(mob.equals(EntityType.SHEEP))hostile=false; else if(mob.equals(EntityType.SNOWMAN))hostile=false; else if(mob.equals(EntityType.SQUID))hostile=false; else if(mob.equals(EntityType.VILLAGER))hostile=false; else if(mob.equals(EntityType.WOLF))hostile=false; if(hostile){ if(!settings.CONFIG_Spawn_Mobs_Naturally_Hostile)e.setCancelled(true); }else if(!settings.CONFIG_Spawn_Mobs_Naturally_Peaceful)e.setCancelled(true); } } public static void e(PlayerInteractEvent e){ try{ final Player p = e.getPlayer(); final Block b = e.getClickedBlock(); Action a = e.getAction(); if(b!=null){ Location l = b.getLocation(); int bid = b.getTypeId(); if(!PlayerMg.hasBuildPermission(l, p)){ if(!WhCommunity.getWorldSettings(p.getWorld().getName()).CONFIG_Conquest_Enabled &&bid==54 ||bid==84 ||bid==92 ||bid==120 ||bid==138 ||bid==145 ||bid==26 ||bid==96 ||bid==60 ||bid==23 ||bid==25 ||bid==107 ||bid==61 ||bid==122){ e.setCancelled(true); yellAtPlayer(l, p); }else{ ItemStack item = p.getItemInHand(); if(item!=null&&item.getTypeId()==Material.MONSTER_EGGS.getId()){ e.setCancelled(true); yellAtPlayer(l, p); } } }else{ WorldSettings settings = WhCommunity.getWorldSettings(p.getWorld().getName()); ItemStack item = p.getItemInHand(); if(item!=null){ if(item.getTypeId()==Material.EYE_OF_ENDER.getId()){ if(PlayerMg.hasPermission(p, "whc.action.eyeofender")){ if(a.equals(Action.LEFT_CLICK_BLOCK)){ if(AntiGreif.channels.containsKey(p.getName())){ int id = AntiGreif.channels.get(p.getName()); Channel c = PlayerMg.getChannel(p); if(c.getId()!=id){ if(id<=settings.CONFIG_Chat_Channels_Limit){ if(PlayerMg.hasPermission(p, "whc.chat.join."+p.getWorld().getName()+".*") ||PlayerMg.hasPermission(p, "whc.chat.join."+p.getWorld().getName()+"."+id)){ c.leaveChannel(p); Channel newc = settings.getChannelById(id); newc.joinChannel(p); AntiGreif.channels.remove(p.getName()); p.sendMessage(ChatColor.DARK_AQUA+"You have joined channel: "+newc); }else p.sendMessage(ChatColor.RED+"You do not have permission to join this chat channel!"); }else p.sendMessage(ChatColor.RED+"This channel does not exist for this world!"); }else p.sendMessage(ChatColor.RED+"You are already in this channel!"); }else p.sendMessage(ChatColor.RED+"You have not selected a channel yet, so you cannot join one! Right click to scroll through channels and then pick one by left clicking."); }else if(a.equals(Action.RIGHT_CLICK_BLOCK)){ if(settings.CONFIG_Chat_Channels_Limit==0)p.sendMessage(ChatColor.RED+"There are no chat channels for this world!"); else{ int c = -1; if(AntiGreif.channels.containsKey(p.getName()))c=AntiGreif.channels.get(p.getName()); c++; c%=settings.CONFIG_Chat_Channels_Limit; AntiGreif.channels.put(p.getName(), c); Channel channel = settings.getChannelById(c); p.sendMessage(ChatColor.DARK_AQUA+"Left click to join channel "+ChatColor.AQUA+channel+ChatColor.DARK_AQUA+"."); } } e.setCancelled(true); } } } } ItemStack item = p.getItemInHand(); if(item!=null){ if(item.getTypeId()==Material.INK_SACK.getId()){ if(KingdomMaker.colorflag.containsKey(p.getName())){ Byte[] flaginfo = KingdomMaker.colorflag.get(p.getName()); Block flagbase = KingdomMg.getCreateFlagLocation(b.getWorld(), flaginfo[0]).getBlock(); final byte data = getWoolColor(item.getData().getData()); if(Flag.isPartOfWool(flagbase, b, flaginfo[0])){ Flag.addColor(flaginfo, flagbase, b, data); e.setCancelled(true); new Thread(new Runnable(){ public void run(){ try{ Thread.sleep(5); }catch(Exception exception){} p.sendBlockChange(b.getLocation(), Material.WOOL, data); } }).start(); } } }else if(item.getTypeId()==Material.LAVA_BUCKET.getId()){ if(KingdomMaker.colorflag.containsKey(p.getName())){ final Byte[] flaginfo = KingdomMaker.colorflag.get(p.getName()); final Block flagbase = KingdomMg.getCreateFlagLocation(b.getWorld(), flaginfo[0]).getBlock(); if(Flag.isPartOfWool(flagbase, b, flaginfo[0])){ for(int i = 1; i<flaginfo.length; i++){ flaginfo[i]=(byte)(Math.random()*16); } e.setCancelled(true); new Thread(new Runnable(){ public void run(){ try{ Thread.sleep(5); }catch(Exception exception){} for(int i = 1; i<flaginfo.length; i++){ p.sendBlockChange(Flag.getBlockAt(flaginfo, flagbase, i).getLocation(), Material.WOOL, flaginfo[i]); } } }).start(); } } }else if(item.getTypeId()==Material.WATER_BUCKET.getId()){ if(KingdomMaker.colorflag.containsKey(p.getName())){ final Byte[] flaginfo = KingdomMaker.colorflag.get(p.getName()); final Block flagbase = KingdomMg.getCreateFlagLocation(b.getWorld(), flaginfo[0]).getBlock(); if(Flag.isPartOfWool(flagbase, b, flaginfo[0])){ e.setCancelled(true); new Thread(new Runnable(){ public void run(){ try{ Thread.sleep(5); }catch(Exception exception){} for(int i = 1; i<flaginfo.length; i++){ p.sendBlockChange(Flag.getBlockAt(flaginfo, flagbase, i).getLocation(), Material.WOOL, (byte)0); } } }).start(); } } } } if(KingdomMaker.chooseflag.containsKey(p.getName())){ byte id = (byte)-1; if(Flag.isPartOfFlag(KingdomMg.getCreateFlagLocation(b.getWorld(), (byte)0).getBlock(), b, (byte)0))id=(byte)0; else if(Flag.isPartOfFlag(KingdomMg.getCreateFlagLocation(b.getWorld(), (byte)1).getBlock(), b, (byte)1))id=(byte)1; else if(Flag.isPartOfFlag(KingdomMg.getCreateFlagLocation(b.getWorld(), (byte)2).getBlock(), b, (byte)2))id=(byte)2; else if(Flag.isPartOfFlag(KingdomMg.getCreateFlagLocation(b.getWorld(), (byte)3).getBlock(), b, (byte)3))id=(byte)3; else if(Flag.isPartOfFlag(KingdomMg.getCreateFlagLocation(b.getWorld(), (byte)4).getBlock(), b, (byte)4))id=(byte)4; if(id>-1){ KingdomMaker.chooseflag.put(p.getName(), id); e.setCancelled(true); } } } if(WhCommunity.getWorldSettings(p.getWorld().getName()).CONFIG_Conquest_Enabled){ ToolBarActions.go(p, e.getAction()); e.setCancelled(true); } }catch(final Exception exception){ exception.printStackTrace(); } } private static byte getWoolColor(byte dye){ if(dye==15)return 0; if(dye==7)return 8; if(dye==8)return 7; if(dye==0)return 15; if(dye==3)return 12; if(dye==1)return 14; if(dye==14)return 1; if(dye==11)return 4; if(dye==10)return 5; if(dye==2)return 13; if(dye==6)return 9; if(dye==12)return 3; if(dye==4)return 11; if(dye==5)return 10; if(dye==13)return 2; if(dye==9)return 6; return 15; } public static void e(EntityDamageByEntityEvent e){ Entity attacker = e.getDamager(); Entity victum = e.getEntity(); if(attacker instanceof Player){ if(!simulateAttack((Player)attacker, victum))e.setCancelled(true); }else if(attacker instanceof Arrow){ Entity shooter = ((Arrow)attacker).getShooter(); if(shooter!=null&&shooter instanceof Player){ if(!simulateAttack((Player)shooter, victum))e.setCancelled(true); } } } public static boolean simulateAttack(Player p, Entity e){ if(e instanceof Player){ Player v = (Player)e; WorldSettings settings = WhCommunity.getWorldSettings(e.getWorld().getName()); if(settings.CONFIG_Pvp_Global)return true; if(PlayerMg.hasPvpEnabled(p)&&PlayerMg.hasPvpEnabled(v))return true; else{ if(PlayerMg.hasPvpEnabled(p))p.sendMessage(ChatColor.RED+"You do not have Pvp turned on, you cannot attack that player!"); else p.sendMessage(ChatColor.RED+"That player does not have Pvp turned on, you cannot attack them!"); return false; } }else{ EntityType type = e.getType(); boolean hostile = true; if(type.equals(EntityType.BAT))hostile=false; else if(type.equals(EntityType.CHICKEN))hostile=false; else if(type.equals(EntityType.COW))hostile=false; else if(type.equals(EntityType.IRON_GOLEM))hostile=false; else if(type.equals(EntityType.MUSHROOM_COW))hostile=false; else if(type.equals(EntityType.OCELOT))hostile=false; else if(type.equals(EntityType.PIG))hostile=false; else if(type.equals(EntityType.SHEEP))hostile=false; else if(type.equals(EntityType.SNOWMAN))hostile=false; else if(type.equals(EntityType.SQUID))hostile=false; else if(type.equals(EntityType.VILLAGER))hostile=false; else if(type.equals(EntityType.WOLF))hostile=false; if(!hostile){ if(PlayerMg.hasBuildPermission(e.getLocation(), p))return true; else{ p.sendMessage(ChatColor.RED+"You cannot attack peaceful mobs in areas you do not have permission for!"); return false; } } } return true; } public static void e(BlockPhysicsEvent e){ WorldSettings settings = WhCommunity.getWorldSettings(e.getBlock().getWorld().getName()); if(settings.CONFIG_Conquest_Enabled)e.setCancelled(true); } public static void e(EntityDamageEvent e){ Entity mob = e.getEntity(); if(mob instanceof Player){ Player p = (Player)mob; if(WhCommunity.getWorldSettings(p.getWorld().getName()).CONFIG_Conquest_Enabled)e.setCancelled(true); } } }
40.116279
183
0.671768
937433999eaa3d04eff3e1f615a6788be80391b0
12,597
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package foodprofile.view; import foodmood.controller.NavigationCntl; import foodmood.view.UserInterface; import foodprofile.controller.FoodCntl; import foodprofile.model.Food; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import javafx.scene.control.DatePicker; import javax.swing.*; import ui.utils.DateInputPanel; /** * * @author mpk5206 */ public class FoodUI extends JPanel { private Food sourceFood; private FoodCntl parentCntl; private JLabel foodName; private JTextField foodInput; private JLabel foodGroup; private JComboBox foodGroupInput; private DateInputPanel dateInputPanel; private JLabel time; private JTextField timeInput; private JButton submitBtn; private JComboBox monthsBox; private JComboBox daysBox; private JButton foodListBtn; private JButton homeButton; private JButton deleteButton; private JPanel buttonPanel; /** * Default Constructor for empty FoodView * @param parentController the parentController */ public FoodUI(FoodCntl foodController) { System.out.println("Creating FoodUI"); this.parentCntl = foodController; //initializeComponents(); setLayout(new GridBagLayout()); addComponents(); } public FoodUI(FoodCntl foodCntl, Food sourceFood) { System.out.println("Creating FoodUI with source food"); this.parentCntl = foodCntl; this.sourceFood = sourceFood; setLayout(new GridBagLayout()); addComponents(); if(this.sourceFood != null) { populateFields(); } } public String getFoodName() { return this.foodInput.getText(); } public String getFoodCategory() { return (String) this.foodGroupInput.getSelectedItem(); } public GregorianCalendar getTime() { // System.err.println("This is technically a stub (FoodUI.getTime())."); return dateInputPanel.getCalendar(); } private void addComponents() { GridBagConstraints gbc = new GridBagConstraints(); JPanel leftMargin = new JPanel(); //leftMargin.setBackground(Color.BLUE); gbc.gridx = 0; gbc.gridy = 0; gbc.gridheight = 2; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = .5; gbc.weighty = .5; this.add(leftMargin, gbc); gbc.gridx = 1; gbc.gridy = 0; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = .5; gbc.weighty = 1; this.add(buildInputPanel(), gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = .5; gbc.weighty = .5; this.add(buildButtonPanel(), gbc); JPanel rightMargin = new JPanel(); //rightMargin.setBackground(Color.MAGENTA); gbc.gridx = 2; gbc.gridy = 0; gbc.gridheight = 2; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = .5; gbc.weighty = .5; this.add(rightMargin, gbc); } private JPanel buildInputPanel() { JPanel inputPanel = new JPanel(); // inputPanel.setBackground(Color.CYAN); // For Testing Purposes inputPanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); homeButton = new JButton("Home"); homeButton.addActionListener((ActionEvent ae) -> { parentCntl.requestHomeView(); }); c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.weighty = .25; c.anchor = GridBagConstraints.WEST; inputPanel.add(homeButton, c); JLabel dateLbl = new JLabel("Date:"); c.anchor = GridBagConstraints.EAST; c.gridx = 0; c.insets = new Insets(10,10,10,10); c.gridwidth = 1; c.weighty = .0; c.gridy = 1; inputPanel.add(dateLbl, c); dateInputPanel = new DateInputPanel(); c.anchor = GridBagConstraints.WEST; c.gridx = 1; c.gridwidth = 1; c.gridy = 1; inputPanel.add(dateInputPanel, c); time = new JLabel("Time:"); c.gridx = 0; c.gridy = 2; c.weightx = .25; c.anchor = GridBagConstraints.EAST; inputPanel.add(time, c); timeInput = new JTextField(25); c.gridx = 1; c.gridy = 2; c.weightx = 1; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.NONE; inputPanel.add(timeInput, c); foodGroup = new JLabel("Food Group:"); c.gridx = 0; c.gridy = 3; c.anchor = GridBagConstraints.EAST; c.weightx = .25; c.fill = GridBagConstraints.NONE; inputPanel.add(foodGroup, c); String[] foodGroupOptions = {"Dairy", "Fruits", "Grains", "Protein", "Vegetables"}; foodGroupInput = new JComboBox(foodGroupOptions); foodGroupInput.setBounds(200, 125, 100, 25); c.gridx = 1; c.gridy = 3; c.anchor = GridBagConstraints.WEST; inputPanel.add(foodGroupInput, c); foodName = new JLabel("Food:"); //foodName.setBounds(100, 150, 80, 25); c.gridx = 0; c.gridy = 4; c.weightx = .25; c.weighty = .5; c.anchor = GridBagConstraints.NORTHEAST; inputPanel.add(foodName, c); foodInput = new JTextField(25); c.gridx = 1; c.gridy = 4; c.fill = GridBagConstraints.NONE; c.weighty = .5; c.anchor = GridBagConstraints.NORTHWEST; inputPanel.add(foodInput, c); return inputPanel; } private JPanel buildButtonPanel() { buttonPanel = new JPanel(); // buttonPanel.setBackground(Color.PINK); // For Testing Purposes GridBagConstraints c = new GridBagConstraints(); submitBtn = new JButton("Submit"); submitBtn.addActionListener((ActionEvent ae) -> { System.out.println("submitBtn ClickEvent Registered"); if(sourceFood == null) { parentCntl.addFood(this); } else { parentCntl.updateFood(this); } }); submitBtn.setSize(10, 25); c.gridx = 0; c.gridy = 5; c.anchor = GridBagConstraints.EAST; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; buttonPanel.add(submitBtn, c); foodListBtn = new JButton("Food List"); foodListBtn.addActionListener((ActionEvent ae) -> { System.out.println("foodListBtn Click Event Registered."); parentCntl.requestListView(); }); foodListBtn.setSize(10, 25); c.gridx = 1; c.gridy = 5; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; buttonPanel.add(foodListBtn, c); if(sourceFood != null) { JButton deleteBtn = new JButton("Delete"); deleteBtn.addActionListener((ActionEvent ae) -> { System.out.println("deleteBtn Click Event Registered"); parentCntl.deleteSelectedFood(); parentCntl.requestListView(); }); c.gridx = 0; c.gridy = 1; buttonPanel.add(deleteBtn, c); } return buttonPanel; } private void populateFields() { this.foodInput.setText(sourceFood.getName()); this.dateInputPanel.setDate(sourceFood.getTime()); this.foodGroupInput.setSelectedItem(sourceFood.getFoodCategories().get(0)); this.timeInput.setText(String.valueOf(sourceFood.getTime().get(GregorianCalendar.HOUR)) + ":" + String.valueOf(sourceFood.getTime().get(GregorianCalendar.MINUTE))); } private void initializeComponents() { setVisible(true); foodListBtn.addActionListener((ActionEvent ae) -> { parentCntl.goListView(); }); } public void initView(){ // // //The text field option for date //// dateInput = new JTextField(50); //// dateInput.setBounds(200, 75, 80, 25); //// add(dateInput); // // //Makes the date drop downs to elliminate user entering error // String[] months = new String[13]; // for (int i = 1; i < 12; i++) { // months[i] = (i)+""; // } // months[0] = sourceFood.getTime().getTime().getMonth()+""; // String[] days = new String[32]; // for (int i = 1; i < 31; i++) { // days[i] = (i)+""; // } // days[0] = sourceFood.getTime().getTime().getDate()+""; // JPanel dateInputPanel = new JPanel(); // dateInputPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); // monthsBox = new JComboBox(months); // dateInputPanel.add(monthsBox); // JLabel slash = new JLabel("/"); // dateInputPanel.add(slash); // daysBox = new JComboBox(days); // dateInputPanel.add(daysBox); // dateInputPanel.setBounds(200, 75, 180, 25); // add(dateInputPanel); // // // time = new JLabel("Time:"); // time.setBounds(100, 100, 80, 25); // add(time); // // timeInput = new JTextField(50); // timeInput.setBounds(200, 100, 80, 25); // add(timeInput); // // foodGroup = new JLabel("Food Group:"); // foodGroup.setBounds(100, 125, 80, 25); // add(foodGroup); // // String[] foodGroupOptions = {sourceFood.getFoodCategories().get(0), "Dairy", "Fruits", "Grains", "Protein", "Vegetables"}; // foodGroupInput = new JComboBox(foodGroupOptions); // foodGroupInput.setBounds(200, 125, 100, 25); // add(foodGroupInput); // // foodName = new JLabel("Food:"); // // foodName.setBounds(100, 150, 80, 25); // add(foodName); // // foodInput = new JTextField(50); // foodInput.setText(sourceFood.getName()); // foodInput.setBounds(200, 150, 100, 50); // add(foodInput); // // // submitBtn = new JButton("Update"); // submitBtn.setBounds(150, 250, 80, 25); // add(submitBtn); // // foodListBtn = new JButton("Food List"); // foodListBtn.setBounds(300, 250, 180, 25); // add(foodListBtn); // // deleteButton = new JButton("Delete"); // deleteButton.setBounds(50, 250, 80, 25); // add(deleteButton); // // setVisible(true); // //// dateInput.addActionListener((ActionEvent ae) -> { //// System.out.println("DateInput event triggered."); //// }); // timeInput.addActionListener((ActionEvent ae) -> { // System.out.println("TimeInput event triggered."); // }); // foodGroupInput.addActionListener((ActionEvent ae) -> { // System.out.println("foodGroupInput event triggered."); // }); // foodInput.addActionListener((ActionEvent ae) -> { // System.out.println("foodInput event triggered."); // }); // submitBtn.addActionListener((ActionEvent ae) -> { // String name = foodInput.getText(); // String category = foodGroupInput.getSelectedItem().toString(); // int month = Integer.parseInt(monthsBox.getSelectedItem().toString()); // int day = Integer.parseInt(daysBox.getSelectedItem().toString()); // GregorianCalendar time = new GregorianCalendar(2017, month, day); // sourceFood.setFoodCategory(category); // sourceFood.setName(name); // sourceFood.setTime(time); // parentCntl.updateFood(sourceFood); // }); // // deleteButton.addActionListener((ActionEvent ae) -> { // this.setVisible(false); // parentCntl.deleteFood(sourceFood); // parentCntl.goListView(); // }); } }
32.466495
132
0.571009
ed8dc9cceb822821bf34f22e5db3091c0a3dd93b
213
package com.adjust.sdk.test; /** * Created by pfms on 28/01/15. */ public enum ResponseType { NULL, CLIENT_PROTOCOL_EXCEPTION, INTERNAL_SERVER_ERROR, WRONG_JSON, EMPTY_JSON, MESSAGE, ATTRIBUTION, ASK_IN; }
23.666667
113
0.751174
b9babeb78505f80144afb370d34ef383ece1f90a
3,013
package mall.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import mall.dao.OrderDAO; import mall.pojo.Order; import mall.pojo.OrderItem; import mall.pojo.User; import mall.util.OrderType; import mall.util.Page4Navigator; @Service @CacheConfig(cacheNames="orders") public class OrderService { @Autowired OrderDAO orderDAO; @Autowired OrderItemService orderItemService; @Cacheable(key="'orders-page-'+#start+ '-' + #size") public Page4Navigator<Order> list(int start, int size) { Sort sort = new Sort(Sort.Direction.DESC, "id"); Pageable pageable = new PageRequest(start, size,sort); Page<Order> pageFromJPA =orderDAO.findAll(pageable); return new Page4Navigator<>(pageFromJPA,size); } // 创建订单,业务方法 @Transactional(propagation = Propagation.REQUIRED, rollbackForClassName = "Exception") public float createOrder(Order order, List<OrderItem> ois) { float total = 0; add(order); if (false) throw new RuntimeException(); for (OrderItem oi : ois) { oi.setOrder(order); orderItemService.update(oi); total += oi.getProduct().getPromotePrice() * oi.getNumber(); } return total; } @Cacheable(key="orders-all") public List<Order> list() { Sort sort = new Sort(Sort.Direction.ASC, "id"); return orderDAO.findAll(sort); } @CacheEvict(allEntries=true) public void add(Order bean) { orderDAO.save(bean); } @CacheEvict(allEntries=true) public void delete(int id) { orderDAO.delete(id); } @Cacheable(key="'orders-one-'+ #id") public Order get(int id) { Order order = orderDAO.findOne(id); return order; } @CacheEvict(allEntries=true) public void update(Order order) { orderDAO.save(order); } public List<Order> listByUserWithoutDelete(User user) { List<Order> orders = listByUserAndNotDeleted(user); // 填充订单项 orderItemService.fillItems(orders); return orders; } /** * 找到状态不是删除的订单 * * @param user * @return */ @Cacheable(key="'orders-listByUserAndNotDeleted-'+user.id") private List<Order> listByUserAndNotDeleted(User user) { return orderDAO.findByUserAndStatusNotOrderByIdDesc(user, OrderType.DELETE.toString()); } /** * 为订单计算总价 * @param order */ public void setTotalPrice(Order order) { List<OrderItem> orderItems = order.getOrderItems(); float total = 0; for (OrderItem orderItem : orderItems) { total += orderItem.getProduct().getPromotePrice() * orderItem.getNumber(); } order.setTotalPrice(total); } }
25.752137
89
0.745105
ac67382643d94564ba3fd56043eefe5d6ad046a4
5,305
// Generated from Logic.g4 by ANTLR 4.8 package grammar.logic; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class LogicLexer extends Lexer { static { RuntimeMetaData.checkVersion("4.8", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int ALPHA=1, DIGIT=2, NOT=3, AND=4, OR=5, IMPLY=6, PARENTHESES_OPEN=7, PARENTHESES_CLOSE=8, STATEMENT_DELIMIT=9, STATEMENTS_OPEN=10, STATEMENTS_CLOSE=11, WS=12; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; private static String[] makeRuleNames() { return new String[] { "ALPHA", "DIGIT", "NOT", "AND", "OR", "IMPLY", "PARENTHESES_OPEN", "PARENTHESES_CLOSE", "STATEMENT_DELIMIT", "STATEMENTS_OPEN", "STATEMENTS_CLOSE", "WS" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, null, null, null, null, null, null, "'('", "')'", null, "'{'", "'}'" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, "ALPHA", "DIGIT", "NOT", "AND", "OR", "IMPLY", "PARENTHESES_OPEN", "PARENTHESES_CLOSE", "STATEMENT_DELIMIT", "STATEMENTS_OPEN", "STATEMENTS_CLOSE", "WS" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public LogicLexer(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "Logic.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\16V\b\1\4\2\t\2\4"+ "\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+ "\13\4\f\t\f\4\r\t\r\3\2\3\2\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\5\4\'"+ "\n\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5\5\5\60\n\5\3\6\3\6\3\6\3\6\3\6\5\6\67"+ "\n\6\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\5\7D\n\7\3\b\3\b\3\t"+ "\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\r\6\rQ\n\r\r\r\16\rR\3\r\3\r\2\2\16\3"+ "\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\3\2\6\4\2C\\c"+ "|\3\2\62;\4\2..==\5\2\13\f\17\17\"\"\2^\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3"+ "\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2"+ "\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\3\33\3\2\2\2\5\35"+ "\3\2\2\2\7&\3\2\2\2\t/\3\2\2\2\13\66\3\2\2\2\rC\3\2\2\2\17E\3\2\2\2\21"+ "G\3\2\2\2\23I\3\2\2\2\25K\3\2\2\2\27M\3\2\2\2\31P\3\2\2\2\33\34\t\2\2"+ "\2\34\4\3\2\2\2\35\36\t\3\2\2\36\6\3\2\2\2\37 \7P\2\2 !\7Q\2\2!\'\7V\2"+ "\2\"#\7p\2\2#$\7q\2\2$\'\7v\2\2%\'\7\u00ae\2\2&\37\3\2\2\2&\"\3\2\2\2"+ "&%\3\2\2\2\'\b\3\2\2\2()\7C\2\2)*\7P\2\2*\60\7F\2\2+,\7c\2\2,-\7p\2\2"+ "-\60\7f\2\2.\60\7\u2229\2\2/(\3\2\2\2/+\3\2\2\2/.\3\2\2\2\60\n\3\2\2\2"+ "\61\62\7Q\2\2\62\67\7T\2\2\63\64\7q\2\2\64\67\7t\2\2\65\67\7\u222a\2\2"+ "\66\61\3\2\2\2\66\63\3\2\2\2\66\65\3\2\2\2\67\f\3\2\2\289\7K\2\29:\7O"+ "\2\2:;\7R\2\2;<\7N\2\2<D\7[\2\2=>\7k\2\2>?\7o\2\2?@\7r\2\2@A\7n\2\2AD"+ "\7{\2\2BD\7\u2194\2\2C8\3\2\2\2C=\3\2\2\2CB\3\2\2\2D\16\3\2\2\2EF\7*\2"+ "\2F\20\3\2\2\2GH\7+\2\2H\22\3\2\2\2IJ\t\4\2\2J\24\3\2\2\2KL\7}\2\2L\26"+ "\3\2\2\2MN\7\177\2\2N\30\3\2\2\2OQ\t\5\2\2PO\3\2\2\2QR\3\2\2\2RP\3\2\2"+ "\2RS\3\2\2\2ST\3\2\2\2TU\b\r\2\2U\32\3\2\2\2\b\2&/\66CR\3\b\2\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
36.840278
98
0.620358
ce68b872331bf5a548890b852bf9f8ef8c5f6084
1,895
/* * @Copyright (c) 2018 缪聪([email protected]) * * 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.mcg.plugin.execute.strategy; import java.util.ArrayList; import com.alibaba.fastjson.JSON; import com.mcg.entity.flow.end.FlowEnd; import com.mcg.entity.generate.ExecuteStruct; import com.mcg.entity.generate.RunResult; import com.mcg.plugin.build.McgProduct; import com.mcg.plugin.execute.ProcessStrategy; import com.mcg.util.DataConverter; public class FlowEndStrategy implements ProcessStrategy { @Override public void prepare(ArrayList<String> sequence, McgProduct mcgProduct, ExecuteStruct executeStruct) throws Exception { FlowEnd flowEnd = (FlowEnd)mcgProduct; executeStruct.getRunStatus().setExecuteId(flowEnd.getEndId()); } @Override public RunResult run(McgProduct mcgProduct, ExecuteStruct executeStruct) throws Exception { FlowEnd flowEnd = (FlowEnd)mcgProduct; JSON parentParam = DataConverter.getParentRunResult(flowEnd.getEndId(), executeStruct); flowEnd = DataConverter.flowOjbectRepalceGlobal(DataConverter.addFlowStartRunResult(parentParam, executeStruct), flowEnd); RunResult result = new RunResult(); result.setElementId(flowEnd.getEndId()); result.setJsonVar(flowEnd.getEndProperty().getComment()); executeStruct.getRunStatus().setCode("success"); return result; } }
38.673469
124
0.759894
50e3c2c6527173369f8d5a91863a24b4633edcb0
448
/** * * @author Carlos Contreras */ public class Monomio { public int coeficiente; public String base; public int exponente; public Monomio(int coeficiente, String variable, int exponente) { this.coeficiente = coeficiente; this.base = variable; this.exponente = exponente; } public String toString() { return Rutinas.PonBlancos(base, 1) + Rutinas.PonCeros(exponente, 5); } }
22.4
76
0.631696
fad5ee30e222d0b53d21357afac251aabb2fb3c4
597
package es.urjc.etsii.grafo.solution; import es.urjc.etsii.grafo.io.Instance; import java.util.Optional; /** * Neighborhood that is able to generate random movements under demand * * @param <S> Solution class * @param <I> Instance class */ public interface RandomizableNeighborhood<M extends Move<S,I>, S extends Solution<S,I>, I extends Instance> { /** * Pick a random move within the neighborhood * * @param s Solution used to generate the neighborhood * @return a random move, if there is at least one valid move */ Optional<M> getRandomMove(S s); }
24.875
109
0.696817
919b45f46062b3d9963ba5b36ad0a38803471aa8
2,151
package codeforces; import java.io.*; import java.util.*; public class K_BachgoldProblem { final static FastReader fr = new FastReader(); final static long mod = 1000000007 ; static void solve() { int n = fr.nextInt(); // we have to find maximum possible primes // so we try to take smallest prime number // we can keep subtracting 2 from that number till it is // greater than 2 // when it becomes 3 or 0 stop // if number is even it can be represented as sum // of 2's n/2 times if (n%2 == 0) { int count = n/2 ; System.out.println(count); for (int i = 0 ; i < count ; i++) { System.out.print(2 + " "); } System.out.println(); return ; } // if number is odd it can represented as sum of a 3 // and (n/2 - 1) 2's else { int count = n/2 - 1 ; System.out.println(count+1); for (int i =0 ;i < count ; i++) { System.out.print(2 + " "); } System.out.println(3); } } public static void main(String[] args) { int t = 1; while (t-- > 0) { solve(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
18.228814
59
0.48768
80e1ced517e6d24c271fa0bdc34f34c55d972d93
619
package org.enast.hummer.dynamodel.attribute; import org.enast.hummer.dynamodel.conmon.DataType; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author zhujinming6 * @create 2020-04-11 16:33 * @update 2020-04-11 16:33 **/ @Data @AllArgsConstructor @NoArgsConstructor public class BaseAttribute { private String identify; private String name; private DataType dataType; private Boolean required; private Boolean unique; private String accessMode; private Integer dataLength; private Boolean notNull; private String defaultValue; }
22.107143
50
0.757674
145b409a14c074897022fb6b58dc4f7c3c92f713
1,414
package com.mediamonks.googleflip.pages.game.physics.levels; import android.util.Log; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.mediamonks.googleflip.GoogleFlipGameApplication; import com.mediamonks.googleflip.pages.game.FlipGameActivity; import org.andengine.extension.physics.box2d.PhysicsWorld; /** * First tutorial level */ public class TutorialLevel1 extends AbstractGameLevel implements GameLevel { public TutorialLevel1() { _originalWidth = 1080; _originalHeight = 1920; } @Override public void createLevel(PhysicsWorld world, FixtureDef fixtureDef) { createBox(world, fixtureDef, _originalWidth / 2, 14, _originalWidth, 28); createBox(world, fixtureDef, _originalWidth / 2, _originalHeight - (20 + (90 * (_density / (_height / _originalHeight)))), _originalWidth, 40); createBox(world, fixtureDef, 14, _originalHeight / 2, 28, _originalHeight); createBox(world, fixtureDef, _originalWidth - 14, _originalHeight / 2, 28, _originalHeight); } @Override public Vector2 getBallSpawnLocation() { return getScaledVector(178, 273); } @Override public Vector2 getSinkholeLocation() { return getScaledVector(887, 1405 - (int) (100 * Math.max(0, _scaledDensity - 3))); } @Override public String getBackgroundUrl() { return "background_tutorial_1.png"; } @Override public float getLevelDuration() { return 0; } }
28.857143
145
0.763083
0bba761e1394e2ac231bc3690d09201bd85030d2
948
package net.vexelon.appicons.wireframe; import net.vexelon.appicons.wireframe.entities.IconFile; import net.vexelon.appicons.wireframe.entities.IconURL; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.Set; /** * Blocking API */ public interface BioDownloader { /** * Fetches icon urls for a single {@code appId} in a blocking way. */ List<IconURL> getUrls(String appId); /** * Fetches icon files for a single {@code appId} in a blocking way. */ List<IconFile> getFiles(String appId, Path destination); /** * Fetches icon urls for multiple app identifiers {@code appIds} in a blocking way. */ Map<String, List<IconURL>> getMultiUrls(Set<String> appIds); /** * Fetches icon files for multiple app identifiers {@code appIds} in a blocking way. */ Map<String, List<IconFile>> getMultiFiles(Set<String> appIds, Path destination); }
27.085714
88
0.690928
ccbf8363284d5fad5d6c81c3b080746d7aad4073
3,196
package com.kumaduma.epicseveninfo.Model.Tier; import java.util.List; public class PVPTier { private String nameId; private double arenaOffense; private double arenaDefense; private double gwOffense; private double gwDefense; private double average; private List<String> recommendedSetList; private List<String> recommendedNeckList; private List<String> suggestedRoleList; private String recommendedArtifactImageId; private List<String> alternateArtifactImageIdList; private String note; public String getNameId() { return nameId; } public void setNameId(String nameId) { this.nameId = nameId; } public double getAverage() { return average; } public void setAverage(double average) { this.average = average; } public void setAverage(){ double sum = arenaDefense + arenaOffense + gwDefense + gwOffense; average = round((sum/4), 1); } public List<String> getRecommendedSetList() { return recommendedSetList; } public void setRecommendedSetList(List<String> recommendedSetList) { this.recommendedSetList = recommendedSetList; } public List<String> getRecommendedNeckList() { return recommendedNeckList; } public void setRecommendedNeckList(List<String> recommendedNeckList) { this.recommendedNeckList = recommendedNeckList; } public List<String> getSuggestedRoleList() { return suggestedRoleList; } public void setSuggestedRoleList(List<String> suggestedRoleList) { this.suggestedRoleList = suggestedRoleList; } public double getArenaOffense() { return arenaOffense; } public void setArenaOffense(double arenaOffense) { this.arenaOffense = arenaOffense; } public double getArenaDefense() { return arenaDefense; } public void setArenaDefense(double arenaDefense) { this.arenaDefense = arenaDefense; } public double getGwOffense() { return gwOffense; } public void setGwOffense(double gwOffense) { this.gwOffense = gwOffense; } public double getGwDefense() { return gwDefense; } public void setGwDefense(double gwDefense) { this.gwDefense = gwDefense; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getRecommendedArtifactImageId() { return recommendedArtifactImageId; } public void setRecommendedArtifactImageId(String recommendedArtifactImageId) { this.recommendedArtifactImageId = recommendedArtifactImageId; } public List<String> getAlternateArtifactImageIdList() { return alternateArtifactImageIdList; } public void setAlternateArtifactImageIdList(List<String> alternateArtifactImageIdList) { this.alternateArtifactImageIdList = alternateArtifactImageIdList; } private static double round (double value, int precision) { int scale = (int) Math.pow(10, precision); return (double) Math.round(value * scale) / scale; } }
25.365079
92
0.681164
edd9c42235e9eb0ccbc9be4f3b4e9d3d4135eee3
242
package org.baifei.modules.entity.response.dhl; import lombok.Data; import java.util.List; @Data public class DhlResponseStatus { private String code; private String message; private List<DhlMessageDetails> messageDetails; }
16.133333
51
0.764463
825623a6fc8e9ec886f47ea7dda5792d629f8b70
638
package com.chilitech.base.manager.database; import android.content.Context; import java.util.List; public interface DBHandler { void init(Context context); <T> long save(T t); <T> long saveOrUpdate(T t); <T> void delete(T t); <T> void clear(Class<T> clazz); <T> T getById(Class<T> clazz, Long id); <T> List<T> getAll(Class<T> clazz); void clearCache(); /** * @param clazz * @param where ex: where begin_date_time >= ? AND end_date_time <= ? * @param params * @param <T> * @return */ <T> List<T> query(Class<T> clazz, String where, String... params); }
17.722222
74
0.598746
d3f9981dc5ad280cbd9b78823878bfe2337037e4
1,889
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package be.ugent.maf.cellmissy.gui.view.renderer.list; import be.ugent.maf.cellmissy.entity.PlateCondition; import be.ugent.maf.cellmissy.entity.result.area.AreaAnalysisGroup; import java.awt.Component; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultListCellRenderer; import javax.swing.JList; import org.apache.commons.lang.StringUtils; /** * * @author Paola Masuzzo <[email protected]> */ public class AnalysisGroupListRenderer extends DefaultListCellRenderer { private final List<PlateCondition> plateConditionList; public AnalysisGroupListRenderer(List<PlateCondition> plateConditionList) { this.plateConditionList = plateConditionList; setOpaque(true); } /** * Override Component Method * * @param list * @param value * @param index * @param isSelected * @param cellHasFocus * @return this class */ @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); AreaAnalysisGroup analysisGroup = (AreaAnalysisGroup) value; List<PlateCondition> plateConditions = analysisGroup.getPlateConditions(); List<String> conditionsName = new ArrayList<>(); for (PlateCondition plateCondition : plateConditions) { int conditionIndex = plateConditionList.indexOf(plateCondition); conditionsName.add("" + (conditionIndex + 1)); } String join = StringUtils.join(conditionsName, ", "); setText(analysisGroup.getGroupName() + " (" + join + ")"); return this; } }
34.981481
131
0.689254
53935354c3e98ceec7586230a3eaac6887ab6bab
4,204
package zielu.gittoolbox.ui.blame; import com.intellij.openapi.util.text.StringUtil; import jodd.util.StringBand; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import zielu.gittoolbox.ResBundle; import zielu.gittoolbox.UtfSeq; import zielu.gittoolbox.config.AuthorNameType; import zielu.gittoolbox.config.DateType; import zielu.gittoolbox.revision.RevisionInfo; import zielu.gittoolbox.ui.AuthorPresenter; import zielu.gittoolbox.util.Html; class BlamePresenterImpl implements BlamePresenter { private static final String SUBJECT_SEPARATOR = " " + UtfSeq.BULLET + " "; private static final String COMMIT_PREFIX = ResBundle.message("blame.commit") + " "; private static final String AUTHOR_PREFIX = ResBundle.message("blame.author") + " "; private static final String DATE_PREFIX = ResBundle.message("blame.date") + " "; private final BlamePresenterLocalGateway gateway; BlamePresenterImpl() { this.gateway = new BlamePresenterLocalGateway(); } @NotNull @Override public String getEditorInline(@NotNull RevisionInfo revisionInfo) { String author = formatInlineAuthor(revisionInfo); String date = gateway.formatInlineDateTime(revisionInfo.getDate()); boolean notBlankAuthor = StringUtils.isNotBlank(author); boolean notBlankDate = StringUtils.isNotBlank(date); StringBand info = new StringBand(5); if (notBlankAuthor && notBlankDate) { info.append(author).append(", ").append(date); } else if (notBlankAuthor) { info.append(author); } else if (notBlankDate) { info.append(date); } boolean showSubject = gateway.getShowInlineSubject(); if (showSubject && revisionInfo.getSubject() != null) { info.append(SUBJECT_SEPARATOR).append(revisionInfo.getSubject()); } return info.toString(); } @NotNull @Override public String getStatusBar(@NotNull RevisionInfo revisionInfo) { StringBand value = new StringBand(5).append(ResBundle.message("blame.prefix")); String author = formatStatusAuthor(revisionInfo); if (StringUtils.isNotBlank(author)) { value.append(" ").append(author); } value.append(" ").append(gateway.formatDateTime(DateType.ABSOLUTE, revisionInfo.getDate())); return value.toString(); } @NotNull @Override public String getPopup(@NotNull RevisionInfo revisionInfo, @Nullable String details) { StringBand text = new StringBand(11) .append(COMMIT_PREFIX) .append(revisionInfo.getRevisionNumber().asString()); String author = formatPopupAuthor(revisionInfo); if (StringUtils.isNotBlank(author)) { text.append(Html.BR).append(AUTHOR_PREFIX).append(author); } text.append(Html.BR) .append(DATE_PREFIX) .append(gateway.formatDateTime(DateType.ABSOLUTE, revisionInfo.getDate())) .append(Html.BR); if (StringUtil.isNotEmpty(details)) { text.append(Html.BR).append(details); } return text.toString(); } private String formatInlineAuthor(@NotNull RevisionInfo revisionInfo) { return formatAuthor(gateway.getInlineAuthorNameType(), revisionInfo); } private String formatStatusAuthor(@NotNull RevisionInfo revisionInfo) { return formatAuthor(gateway.getStatusAuthorNameTYpe(), revisionInfo); } private String formatPopupAuthor(@NotNull RevisionInfo revisionInfo) { StringBand formatted = new StringBand(5); formatted.append(formatAuthor(AuthorNameType.FULL, revisionInfo)); if (revisionInfo.getAuthorEmail() != null) { formatted.append(" "); formatted.append(Html.LT); formatted.append(revisionInfo.getAuthorEmail()); formatted.append(Html.GT); } return formatted.toString(); } private String formatAuthor(@NotNull AuthorNameType type, @NotNull RevisionInfo revisionInfo) { if (type == AuthorNameType.EMAIL || type == AuthorNameType.EMAIL_USER) { if (revisionInfo.getAuthorEmail() == null) { return AuthorPresenter.format(type, revisionInfo.getAuthor(), revisionInfo.getAuthor()); } } return AuthorPresenter.format(type, revisionInfo.getAuthor(), revisionInfo.getAuthorEmail()); } }
37.20354
97
0.731446
d58b8ef1b2d0edd9104a4e9665015cce38d41477
438
private static int[][][] dwgraph(int N, int[][] E) { int[] D = new int[N]; for (int[] e : E) ++D[e[0]]; int[][][] res = new int[2][N][]; for (int i = 0; i < 2; ++i) for (int j = 0; j < N; ++j) res[i][j] = new int[D[j]]; D = new int[N]; for (int[] e : E) { int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1; res[0][x][D[x]] = y; res[1][x][D[x]] = z; ++D[x]; } return res; }
31.285714
86
0.378995
1a06d99fd0752ae69665b972f403afdfc5e6b161
15,571
/* * * This file is part of the iText (R) project. Copyright (c) 1998-2017 iText Group NV * Authors: Balder Van Camp, Emiel Ackermann, et al. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 * as published by the Free Software Foundation with the addition of the * following permission added to Section 15 as permitted in Section 7(a): * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY * ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT * OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. You should have received a copy of the GNU Affero General Public * License along with this program; if not, see http://www.gnu.org/licenses or * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA, 02110-1301 USA, or download the license from the following URL: * http://itextpdf.com/terms-of-use/ * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License. * * In accordance with Section 7(b) of the GNU Affero General Public License, a * covered work must retain the producer line in every PDF that is created or * manipulated using iText. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving the iText software without disclosing the * source code of your own applications. These activities include: offering paid * services to customers as an ASP, serving PDFs on the fly in a web * application, shipping iText with a closed source product. * * For more information, please contact iText Software Corp. at this address: * [email protected] */ package com.itextpdf.tool.xml.parser; import com.itextpdf.text.xml.XMLUtil; import com.itextpdf.text.xml.simpleparser.IanaEncodings; import com.itextpdf.tool.xml.parser.io.EncodingUtil; import com.itextpdf.tool.xml.parser.io.MonitorInputReader; import com.itextpdf.tool.xml.parser.io.ParserMonitor; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; /** * Reads an XML file. Attach a {@link XMLParserListener} for receiving events. * * @author redlab_b */ public class XMLParser { private State state; private final StateController controller; private final List<XMLParserListener> listeners; private final XMLParserMemory memory; private ParserMonitor monitor; private String text = null; private TagState tagState; private Charset charset; private boolean decodeSpecialChars = true; /** * Constructs a default XMLParser ready for HTML/XHTML processing. */ public XMLParser() { this(true, Charset.defaultCharset()); } /** * Constructs a XMLParser. * * @param isHtml false if this parser is not going to parse HTML and * whitespace should be submitted as text too. * @param charset charset */ public XMLParser(final boolean isHtml, final Charset charset) { this.charset = charset; this.controller = new StateController(this, isHtml); controller.unknown(); memory = new XMLParserMemory(isHtml); listeners = new CopyOnWriteArrayList<XMLParserListener>(); } /** * Construct an XMLParser with the given XMLParserConfig ready for * HTML/XHTML processing.. * * @param listener the listener * @param charset the Charset */ public XMLParser(final XMLParserListener listener, final Charset charset) { this(true, charset); listeners.add(listener); } /** * Construct a XMLParser with the given XMLParserConfig. * * @param isHtml false if this parser is not going to parse HTML and * whitespace should be submitted as text too. * @param listener the listener * @param charset the Charset to use */ public XMLParser(final boolean isHtml, final XMLParserListener listener, final Charset charset) { this(isHtml, charset); listeners.add(listener); } /** * Constructs a new Parser with the default jvm charset. * * @param b true if HTML is being parsed * @param listener the XMLParserListener */ public XMLParser(final boolean b, final XMLParserListener listener) { this(b, Charset.defaultCharset()); listeners.add(listener); } /** * Constructs a new Parser with HTML parsing set to true and the default jvm charset. * * @param listener the XMLParserListener */ public XMLParser(final XMLParserListener listener) { this(true, Charset.defaultCharset()); listeners.add(listener); } /** * If no <code>ParserListener</code> is added, parsing with the parser seems * useless no? * * @param pl the {@link XMLParserListener} * @return the parser */ public XMLParser addListener(final XMLParserListener pl) { listeners.add(pl); return this; } /** * Removes a Listener from the list of listeners. * * @param pl the {@link XMLParserListener} to remove * @return the parser */ public XMLParser removeListener(final XMLParserListener pl) { listeners.remove(pl); return this; } /** * Parse an InputStream with default encoding set * * @param in the InputStream to parse * @throws IOException if IO went wrong */ public void parse(final InputStream in) throws IOException { parse(new InputStreamReader(in)); } /** * Parse an InputStream that optionally detects encoding from the stream * * @param in the InputStream to parse * @param detectEncoding true if encoding should be detected from the stream * @throws IOException if IO went wrong */ public void parse(final InputStream in, final boolean detectEncoding) throws IOException { if (detectEncoding) { parse(detectEncoding(new BufferedInputStream(in))); } else { parse(in); } } /** * Parses an InputStream using the given encoding * * @param in the stream to read * @param charSet to use for the constructed reader. * @throws IOException if reading fails */ public void parse(final InputStream in, final Charset charSet) throws IOException { this.charset = charSet; InputStreamReader reader = new InputStreamReader(in, charSet); parse(reader); } /** * Parse an Reader * * @param reader the reader * @throws IOException if IO went wrong */ public void parse(final Reader reader) throws IOException { parseWithReader(reader); } /** * The actual parse method * * @param reader * @throws IOException */ private void parseWithReader(final Reader reader) throws IOException { for (XMLParserListener l : listeners) { l.init(); } Reader r; if (monitor != null) { r = new MonitorInputReader(reader, monitor); } else { r = reader; } char read[] = new char[1]; try { while (-1 != (r.read(read))) { state.process(read[0]); } } finally { for (XMLParserListener l : listeners) { l.close(); } r.close(); } } /** * Detects encoding from a stream. * * @param in the stream * @return a Reader with the deduced encoding. * @throws IOException if IO went wrong * @throws UnsupportedEncodingException if unsupported encoding was detected */ public InputStreamReader detectEncoding(final InputStream in) throws IOException, UnsupportedEncodingException { // we expect a '>' in the first 100 characters in.mark(1028); byte b4[] = new byte[4]; int count = in.read(b4); if (count != 4) throw new IOException("Insufficient length"); String encoding = XMLUtil.getEncodingName(b4); String decl = null; if (encoding.equals("UTF-8")) { StringBuffer sb = new StringBuffer(); int c; while ((c = in.read()) != -1) { if (c == '>') break; sb.append((char) c); } decl = sb.toString(); } else if (encoding.equals("CP037")) { ByteArrayOutputStream bi = new ByteArrayOutputStream(); int c; while ((c = in.read()) != -1) { if (c == 0x6e) // that's '>' in ebcdic break; bi.write(c); } decl = new String(bi.toByteArray(), "CP037"); } if (decl != null) { decl = EncodingUtil.getDeclaredEncoding(decl); if (decl != null) encoding = decl; } in.reset(); return new InputStreamReader(in, IanaEncodings.getJavaEncoding(encoding)); } /** * Set the current state. * * @param state the current state */ protected void setState(final State state) { this.state = state; } /** * @param character the character to append * @return the parser */ public XMLParser append(final char character) { this.memory.current().append(character); return this; } // /** // * @param str the String to append // * @return the parser // */ // public XMLParser append(final String str) { // this.memory.current().write(str.getBytes()); // return this; // // } /** * The state controller of the parser * * @return {@link StateController} */ public StateController selectState() { return this.controller; } /** * Triggered when the UnknownState encountered anything before encountering * a tag. */ public void unknownData() { for (XMLParserListener l : listeners) { l.unknownText(this.memory.current().toString()); } } /** * Flushes the currently stored data in the buffer. */ public void flush() { this.memory.resetBuffer(); } /** * Returns the current content of the text buffer. * * @return current buffer content */ public String current() { return this.memory.current().toString(); } /** * Returns the XMLParserMemory. * * @return the memory */ public XMLParserMemory memory() { return memory; } /** * Triggered when an opening tag has been encountered. */ public void startElement() { currentTagState(TagState.OPEN); String tagName = this.memory.getCurrentTag(); Map<String, String> attributes = this.memory.getAttributes(); if (tagName.startsWith("?")) { memory().processingInstruction().setLength(0); } callText(); for (XMLParserListener l : listeners) { l.startElement(tagName, attributes, this.memory.getNameSpace()); } this.memory().flushNameSpace(); } /** * Call this method to submit the text to listeners. */ private void callText() { if (null != text && text.length() > 0) { // LOGGER .log(text); for (XMLParserListener l : listeners) { l.text(text); } text = null; } } /** * Triggered when a closing tag has been encountered. */ public void endElement() { currentTagState(TagState.CLOSE); callText(); for (XMLParserListener l : listeners) { l.endElement(this.memory.getCurrentTag(), this.memory.getNameSpace()); } } /** * Triggered when content has been encountered. * * @param bs the content */ public void text(final String bs) { text = bs; } /** * Triggered for comments. */ public void comment() { callText(); for (XMLParserListener l : listeners) { l.comment(this.memory.current().toString()); } } /** * @return the current last character of the buffer or ' ' if none. */ public char currentLastChar() { StringBuilder current2 = this.memory.current(); int length = current2.length(); CharSequence current = current2.subSequence(length - 2, length - 1); if (current.length() > 0) { return (char) (current.length() - 1); } return ' '; } /** * Get the current tag * * @return the current tag. */ public String currentTag() { return this.memory.getCurrentTag(); } /** * Get the state of the current tag * * @return the state of the current tag */ public TagState currentTagState() { return this.tagState; } /** * Set the state of the current tag * * @param state the state of the current tag */ private void currentTagState(final TagState state) { this.tagState = state; } /** * @param monitor the monitor to set */ public void setMonitor(final ParserMonitor monitor) { this.monitor = monitor; } /** * Determines whether special chars like &gt; will be decoded * @param decodeSpecialChars true to decode, false to not decode */ public void setDecodeSpecialChars(boolean decodeSpecialChars) { this.decodeSpecialChars = decodeSpecialChars; } public boolean isDecodeSpecialChars() { return decodeSpecialChars; } /** * @return the current buffer as a String */ public String bufferToString() { return this.memory.current().toString(); } /** * @param bytes the byte array to append * @return this instance of the XMLParser */ public XMLParser append(final char[] bytes) { this.memory.current().append(bytes); return this; } /** * @return the size of the buffer */ public int bufferSize() { return (null != this.memory.current()) ? this.memory.current().length() : 0; } /** * Appends the given string to the buffer. * * @param string the String to append * @return this instance of the XMLParser */ public XMLParser append(final String string) { this.memory.current().append(string); return this; } /** * Returns the current used character set. * * @return the charset */ public Charset getCharset() { return charset; } }
29.379245
116
0.612099
2cea96f40ce111fd77d4ca670fa70cf24eabeb09
9,936
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (c) 2009 Google, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.endless; import java.util.concurrent.atomic.AtomicBoolean; import android.annotation.TargetApi; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import com.commonsware.cwac.adapter.ExpandableAdapterWrapper; /** * Adapter that assists another adapter in appearing endless. For example, this * could be used for an adapter being filled by a set of Web service calls, * where each call returns a "page" of data. * * Subclasses need to be able to return, via getPendingView() a row that can * serve as both a placeholder while more data is being appended. * * The actual logic for loading new data should be done in appendInBackground(). * This method, as the name suggests, is run in a background thread. It should * return true if there might be more data, false otherwise. * * If your situation is such that you will not know if there is more data until * you do some work (e.g., make another Web service call), it is up to you to do * something useful with that row returned by getPendingView() to let the user * know you are out of data, plus return false from that final call to * appendInBackground(). */ abstract public class ExpandableEndlessAdapter extends ExpandableAdapterWrapper { abstract protected boolean cacheInBackground() throws Exception; abstract protected void appendCachedData(); private View pendingView = null; private AtomicBoolean keepOnAppending = new AtomicBoolean(true); private Context context; private int pendingResource = -1; private boolean isSerialized = false; private boolean runInBackground = true; /** * Constructor wrapping a supplied ListAdapter */ public ExpandableEndlessAdapter(BaseExpandableListAdapter wrapped) { super(wrapped); } /** * Constructor wrapping a supplied ListAdapter and explicitly set if there * is more data that needs to be fetched or not. * * @param wrapped * @param keepOnAppending */ public ExpandableEndlessAdapter(BaseExpandableListAdapter wrapped, boolean keepOnAppending) { super(wrapped); this.setKeepOnAppending(keepOnAppending); } /** * Constructor wrapping a supplied ListAdapter and providing a id for a * pending view. * * @param context * @param wrapped * @param pendingResource */ public ExpandableEndlessAdapter(Context context, BaseExpandableListAdapter wrapped, int pendingResource) { super(wrapped); this.context = context; this.pendingResource = pendingResource; } /** * Constructor wrapping a supplied ListAdapter, providing a id for a pending * view and explicitly set if there is more data that needs to be fetched or * not. * * @param context * @param wrapped * @param pendingResource * @param keepOnAppending */ public ExpandableEndlessAdapter(Context context, BaseExpandableListAdapter wrapped, int pendingResource, boolean keepOnAppending) { super(wrapped); this.context = context; this.pendingResource = pendingResource; this.setKeepOnAppending(keepOnAppending); } public boolean isSerialized() { return (isSerialized); } public void setSerialized(boolean isSerialized) { this.isSerialized = isSerialized; } public void stopAppending() { setKeepOnAppending(false); } public void restartAppending() { setKeepOnAppending(true); } /** * When set to false, cacheInBackground is called directly, rather than from * an AsyncTask. * * This is useful if for example you have code to populate the adapter that * already runs in a background thread, and simply don't need the built in * background functionality. * * When using this you must remember to call onDataReady() once you've * appended your data. * * Default value is true. * * @param runInBackground * * :see #cacheInBackground() :see #onDataReady() */ public void setRunInBackground(boolean runInBackground) { this.runInBackground = runInBackground; } /** * Use to manually notify the adapter that it's dataset has changed. Will * remove the pendingView and update the display. */ public void onDataReady() { pendingView = null; notifyDataSetChanged(); } /** * How many items are in the data set represented by this Adapter. */ @Override public int getGroupCount() { if (keepOnAppending.get()) { return (super.getGroupCount() + 1); // one more for // "pending" } return (super.getGroupCount()); } /** * Masks ViewType so the AdapterView replaces the "Pending" row when new * data is loaded. */ @Override public int getGroupType(int groupPosition) { if (groupPosition == getWrappedAdapter().getGroupCount()) { return (-1); } return super.getGroupType(groupPosition); } /** * Masks ViewType so the AdapterView replaces the "Pending" row when new * data is loaded. * * @see #getItemViewType(int) */ public int getViewTypeCount() { return (super.getGroupTypeCount() + 1); } @Override public Object getGroup(int position) { if (position >= super.getGroupCount()) { return (null); } return (super.getGroup(position)); } @Override public boolean areAllItemsEnabled() { return (false); } /** * Get a View that displays the data at the specified position in the data * set. In this case, if we are at the end of the list and we are still in * append mode, we ask for a pending view and return it, plus kick off the * background task to append more data to the wrapped adapter. * * @param position * Position of the item whose data we want * @param convertView * View to recycle, if not null * @param parent * ViewGroup containing the returned View */ @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (groupPosition == super.getGroupCount() && keepOnAppending.get()) { if (pendingView == null) { pendingView = getPendingView(parent); if (runInBackground) { executeAsyncTask(buildTask()); } else { try { setKeepOnAppending(cacheInBackground()); } catch (Exception e) { setKeepOnAppending(onException(pendingView, e)); } } } return (pendingView); } return (super.getGroupView(groupPosition, isExpanded, convertView, parent)); } /** * Called if cacheInBackground() raises a runtime exception, to allow the UI * to deal with the exception on the main application thread. * * @param pendingView * View representing the pending row * @param e * Exception that was raised by cacheInBackground() * @return true if should allow retrying appending new data, false otherwise */ protected boolean onException(View pendingView, Exception e) { Log.e("EndlessAdapter", "Exception in cacheInBackground()", e); return (false); } protected AppendTask buildTask() { return (new AppendTask(this)); } @TargetApi(11) private <T> void executeAsyncTask(AsyncTask<T, ?, ?> task, T... params) { if (!isSerialized && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)) { task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); } else { task.execute(params); } } private void setKeepOnAppending(boolean newValue) { boolean same = (newValue == keepOnAppending.get()); keepOnAppending.set(newValue); if (!same) { notifyDataSetChanged(); } } /** * A background task that will be run when there is a need to append more * data. Mostly, this code delegates to the subclass, to append the data in * the background thread and rebind the pending view once that is done. */ protected static class AppendTask extends AsyncTask<Void, Void, Exception> { ExpandableEndlessAdapter adapter = null; boolean tempKeep; protected AppendTask(ExpandableEndlessAdapter adapter) { this.adapter = adapter; } @Override protected Exception doInBackground(Void... params) { Exception result = null; try { tempKeep = adapter.cacheInBackground(); } catch (Exception e) { result = e; } return (result); } @Override protected void onPostExecute(Exception e) { adapter.setKeepOnAppending(tempKeep); if (e == null) { adapter.appendCachedData(); } else { adapter.setKeepOnAppending(adapter.onException(adapter.pendingView, e)); } adapter.onDataReady(); } } /** * Inflates pending view using the pendingResource ID passed into the * constructor * * @param parent * @return inflated pending view, or null if the context passed into the * pending view constructor was null. */ protected View getPendingView(ViewGroup parent) { if (context != null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return inflater.inflate(pendingResource, parent, false); } throw new RuntimeException("You must either override getPendingView() or supply a pending View resource via the constructor"); } /** * Getter method for the Context being held by the adapter * * @return Context */ protected Context getContext() { return (context); } }
28.388571
132
0.718398
74c45997eb3dc53f6ca6af4cac06c4d3e99bfab4
2,782
package es.pcv.game.gui; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.jogamp.opengl.GL2; import com.jogamp.opengl.glu.GLU; import com.jogamp.opengl.glu.GLUquadric; import es.pcv.core.render.figure.Drawable; import es.pcv.game.configuration.Config; import es.pcv.game.elements.player.Player; import es.pcv.game.elements.weapons.Weapon; public class Stats implements Drawable { private Player pl; private Font font=new Font(Font.SANS_SERIF, Font.PLAIN, 18); private Color color=new Color(255,0,0); private Color black=new Color(0,0,0); private BufferedImage[] weapon; public Stats(Player pl) { this.pl = pl; weapon=new BufferedImage[3]; File f = new File(Config.RESOURCES_PATH+"/icons/pistola.jpg"); try { weapon[0] = ImageIO.read(f); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } f = new File(Config.RESOURCES_PATH+"/icons/espada.jpg"); try { weapon[1] = ImageIO.read(f); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } f = new File(Config.RESOURCES_PATH+"/icons/escopeta.png"); try { weapon[2] = ImageIO.read(f); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public boolean isDead() { return false; } public boolean kill() { return false; } public void draw(Graphics g) { g.setColor(color); g.setFont(font); g.fillRect(5, 5, (int) (2.5*pl.getLive()) , 20); g.setColor(black); g.drawRect(5, 5, 500, 20); g.drawRect(4, 4, 502, 22); String s=""; Weapon wp=pl.getWeapon(); if (wp!=null){ if( wp.getMaxDurability()!=0) { s=wp.getDurability()+"/"+wp.getMaxDurability(); g.drawChars(s.toCharArray(), 0, s.length(), 20, 65); }else{ g.setFont(new Font(font.getFontName(), font.getStyle(), 44)); s='\u221e'+""; g.drawChars(s.toCharArray(), 0, s.length(), 30, 70); g.setFont(font); } } for (int i=0;i<pl.getWeaponCapacity();i++){ wp=pl.getWeapon(i); g.setColor(black); if (wp!=null) { g.drawImage(Weapon.ICONS.getImage(wp.getId()), 120 + (i*40), 40 , 30 ,30,null); }else{ g.drawRect(120 + (i*40), 40 , 30 ,30); } if(i==pl.getCurrentWeapon()){ g.setColor(color); g.drawRect(120 + (i*40), 40 , 30 ,30); } Integer num=i+1; char[] number=num.toString().toCharArray(); g.drawChars(number, 0, 1, 130 + (i*40), 85); } //String s="Live:" + pl.getLive() + "/" + pl.getMaxLive(); //g.drawString(s, 0,20); } public void draw3d(GL2 gl, GLU glu, GLUquadric quadric) { // TODO Auto-generated method stub } }
23.183333
83
0.6445
d07c59da34c528e0a150abf145ce5a7ba2dfd12f
5,072
package org.batfish.client; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.batfish.common.BatfishLogger; import org.batfish.common.CoordConsts; public class Settings { private static final String ARG_COMMAND_FILE = "cmdfile"; private static final String ARG_HELP = "help"; private static final String ARG_LOG_FILE = "logfile"; private static final String ARG_LOG_LEVEL = "loglevel"; private static final String ARG_PERIOD_CHECK_WORK = "periodcheckwork"; private static final String ARG_SERVICE_HOST = "coordhost"; private static final String ARG_SERVICE_POOL_PORT = "poolmgrport"; private static final String ARG_SERVICE_WORK_PORT = "workmgrport"; private static final String DEFAULT_LOG_LEVEL = BatfishLogger .getLogLevelStr(BatfishLogger.LEVEL_WARN); private static final String DEFAULT_PERIOD_CHECK_WORK = "5000"; // 5 seconds private static final String DEFAULT_SERVICE_HOST = "localhost"; private static final String DEFAULT_SERVICE_POOL_PORT = CoordConsts.SVC_POOL_PORT .toString(); private static final String DEFAULT_SERVICE_WORK_PORT = CoordConsts.SVC_WORK_PORT .toString(); private static final String EXECUTABLE_NAME = "batfish_client"; private String _commandFile; private String _logFile; private String _logLevel; private Options _options; private long _periodCheckWorkMs; private String _serviceHost; private int _servicePoolPort; private int _serviceWorkPort; public Settings() throws ParseException { this(new String[] {}); } public Settings(String[] args) throws ParseException { initOptions(); parseCommandLine(args); } public String getCommandFile() { return _commandFile; } public String getLogFile() { return _logFile; } public String getLogLevel() { return _logLevel; } public long getPeriodCheckWorkMs() { return _periodCheckWorkMs; } public String getServiceHost() { return _serviceHost; } public int getServicePoolPort() { return _servicePoolPort; } public int getServiceWorkPort() { return _serviceWorkPort; } private void initOptions() { _options = new Options(); _options.addOption(Option.builder().argName("port_number_pool_service") .hasArg().desc("port for pool management service") .longOpt(ARG_SERVICE_POOL_PORT).build()); _options.addOption(Option.builder().argName("port_number_work_service") .hasArg().desc("port for work management service") .longOpt(ARG_SERVICE_WORK_PORT).build()); _options.addOption(Option.builder().argName("hostname for the service") .hasArg().desc("base url for coordinator service") .longOpt(ARG_SERVICE_HOST).build()); _options.addOption(Option.builder().argName("period_check_work_ms") .hasArg().desc("period with which to check work (ms)") .longOpt(ARG_PERIOD_CHECK_WORK).build()); _options.addOption(Option.builder().argName("logfile").hasArg() .desc("send output to specified log file").longOpt(ARG_LOG_FILE) .build()); _options.addOption(Option.builder().argName("loglevel").hasArg() .desc("log level").longOpt(ARG_LOG_LEVEL).build()); _options.addOption(Option.builder().argName("cmdfile").hasArg() .desc("read commands from the specified command file") .longOpt(ARG_COMMAND_FILE).build()); _options.addOption(Option.builder().desc("print this message") .longOpt(ARG_HELP).build()); } private void parseCommandLine(String[] args) throws ParseException { CommandLine line = null; CommandLineParser parser = new DefaultParser(); // parse the command line arguments line = parser.parse(_options, args); if (line.hasOption(ARG_HELP)) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.setLongOptPrefix("-"); formatter.printHelp(EXECUTABLE_NAME, _options); System.exit(0); } _servicePoolPort = Integer.parseInt(line.getOptionValue( ARG_SERVICE_POOL_PORT, DEFAULT_SERVICE_POOL_PORT)); _serviceWorkPort = Integer.parseInt(line.getOptionValue( ARG_SERVICE_WORK_PORT, DEFAULT_SERVICE_WORK_PORT)); _serviceHost = line .getOptionValue(ARG_SERVICE_HOST, DEFAULT_SERVICE_HOST); _periodCheckWorkMs = Long.parseLong(line.getOptionValue( ARG_PERIOD_CHECK_WORK, DEFAULT_PERIOD_CHECK_WORK)); _logFile = line.getOptionValue(ARG_LOG_FILE); _logLevel = line.getOptionValue(ARG_LOG_LEVEL, DEFAULT_LOG_LEVEL); _commandFile = line.getOptionValue(ARG_COMMAND_FILE); } }
36.489209
84
0.707413
d0e4732881d1e18c44c4b1b2c12404038671e7ae
1,727
package com.liulishuo.filedownloader.model; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class FileDownloadHeader implements Parcelable { public static final Creator<FileDownloadHeader> CREATOR = new C10911a(); /* renamed from: a */ private HashMap<String, List<String>> f33336a; /* renamed from: a */ public void mo35713a(String name, String value) { if (name == null) { throw new NullPointerException("name == null"); } else if (name.isEmpty()) { throw new IllegalArgumentException("name is empty"); } else if (value != null) { if (this.f33336a == null) { this.f33336a = new HashMap<>(); } List list = (List) this.f33336a.get(name); if (list == null) { list = new ArrayList(); this.f33336a.put(name, list); } if (!list.contains(value)) { list.add(value); } } else { throw new NullPointerException("value == null"); } } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeMap(this.f33336a); } /* renamed from: a */ public HashMap<String, List<String>> mo35712a() { return this.f33336a; } public FileDownloadHeader() { } protected FileDownloadHeader(Parcel in) { this.f33336a = in.readHashMap(String.class.getClassLoader()); } public String toString() { return this.f33336a.toString(); } }
27.412698
76
0.584829
c90dc7d6051174544d6cfc27b770cb4a05f0a079
3,224
package fi.trustnet.example.issuer; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import org.abstractj.kalium.NaCl.Sodium; import org.apache.commons.codec.binary.Hex; import org.hyperledger.indy.sdk.did.DidResults.CreateAndStoreMyDidResult; import com.github.jsonldjava.utils.JsonUtils; import fi.trustnet.verifiablecredentials.VerifiableCredential; import info.weboftrust.ldsignatures.LdSignature; import info.weboftrust.ldsignatures.crypto.EC25519Provider; import info.weboftrust.ldsignatures.signer.Ed25519Signature2018LdSigner; public class ExampleIssuer { public static void main(String[] args) throws Exception { // open Sovrin Sovrin.open(); // create issuer DID String issuerSeed = "0000000000000000000000000Issuer1"; byte[] issuerPrivateKey = new byte[Sodium.CRYPTO_SIGN_ED25519_SECRETKEYBYTES]; byte[] issuerPublicKey = new byte[Sodium.CRYPTO_SIGN_ED25519_PUBLICKEYBYTES]; EC25519Provider.get().generateEC25519KeyPairFromSeed(issuerPublicKey, issuerPrivateKey, issuerSeed.getBytes(StandardCharsets.UTF_8)); CreateAndStoreMyDidResult issuer = Sovrin.createDid(issuerSeed); String issuerDid = issuer.getDid(); String issuerVerkey = issuer.getVerkey(); System.out.println("Issuer DID: " + issuerDid); System.out.println("Issuer DID Verkey: " + issuerVerkey); System.out.println("Issuer Private Key: " + Hex.encodeHexString(issuerPrivateKey)); System.out.println("Issuer Public Key: " + Hex.encodeHexString(issuerPublicKey)); // get subject DID String subjectSeed = "000000000000000000000000Subject1"; CreateAndStoreMyDidResult subject = Sovrin.createDid(subjectSeed); String subjectDid = subject.getDid(); String subjectVerkey = subject.getVerkey(); System.out.println("Subject DID: " + subjectDid); System.out.println("Subject DID Verkey: " + subjectVerkey); // issue Verifiable Credential VerifiableCredential verifiableCredential = new VerifiableCredential(); verifiableCredential.getContext().add("https://trafi.fi/credentials/v1"); verifiableCredential.getType().add("DriversLicenseCredential"); verifiableCredential.setIssuer(URI.create("did:sov:" + issuerDid)); verifiableCredential.setIssued("2018-01-01"); verifiableCredential.setSubject("did:sov:" + subjectDid); LinkedHashMap<String, Object> jsonLdClaimsObject = verifiableCredential.getJsonLdClaimsObject(); LinkedHashMap<String, Object> jsonLdDriversLicenseObject = new LinkedHashMap<String, Object> (); jsonLdDriversLicenseObject.put("licenseClass", "trucks"); jsonLdClaimsObject.put("driversLicense", jsonLdDriversLicenseObject); URI creator = URI.create("did:sov:" + issuerDid + "#key1"); String created = "2018-01-01T21:19:10Z"; String domain = null; String nonce = "c0ae1c8e-c7e7-469f-b252-86e6a0e7387e"; // sign Ed25519Signature2018LdSigner signer = new Ed25519Signature2018LdSigner(creator, created, domain, nonce, issuerPrivateKey); LdSignature ldSignature = signer.sign(verifiableCredential.getJsonLdObject()); // output System.out.println("Signature Value: " + ldSignature.getSignatureValue()); System.out.println(JsonUtils.toPrettyString(verifiableCredential.getJsonLdObject())); } }
38.843373
135
0.788151
e0f37c41455888338c532f4c43ac7d09f9a344dd
98
package com.nanda.testlab.selenium.guru99.test; public class LinksTest extends BaseTest { }
12.25
47
0.765306
e80570ba1a2e8006088cde49950bc3e51b411c70
4,505
package com.soundbread.history.data.db.model; import java.util.ArrayList; import java.util.List; /** * Created by fruitbites on 2017-09-17. */ public class Incident { String id; int time; String tp; String dynasty; String name; String chinese; String photo; String thumbOn; String thumbOff; String desc; String birth; String alias; String period; String event; String materials; String remains; String person; String organization; String antecedents; List<Content> contents; public Incident() { this("",0,"","","","","","","","","","","","","","","","","",new ArrayList<Content>()); } public Incident(String id, int time, String tp, String dynasty, String name, String chinese, String photo, String thumbOn, String thumbOff, String desc, String birth, String alias, String period, String event, String materials, String remains, String person, String oranization, String antecedents, List<Content> contents) { this.id = id; this.time = time; this.tp = tp; this.dynasty = dynasty; this.name = name; this.chinese = chinese; this.photo = photo; this.thumbOn = thumbOn; this.thumbOff = thumbOff; this.desc = desc; this.birth = birth; this.alias = alias; this.period = period; this.event = event; this.materials = materials; this.remains = remains; this.person = person; this.organization = oranization; this.antecedents = antecedents; this.contents = contents; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public String getTp() { return tp; } public void setTp(String tp) { this.tp = tp; } public String getDynasty() { return dynasty; } public void setDynasty(String dynasty) { this.dynasty = dynasty; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getChinese() { return chinese; } public void setChinese(String chinese) { this.chinese = chinese; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public String getThumbOn() { return thumbOn; } public void setThumbOn(String thumbOn) { this.thumbOn = thumbOn; } public String getThumbOff() { return thumbOff; } public void setThumbOff(String thumbOff) { this.thumbOff = thumbOff; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getBirth() { return birth; } public void setBirth(String birth) { this.birth = birth; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getPeriod() { return period; } public void setPeriod(String period) { this.period = period; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } public String getMaterials() { return materials; } public void setMaterials(String materials) { this.materials = materials; } public String getRemains() { return remains; } public void setRemains(String remains) { this.remains = remains; } public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getAntecedents() { return antecedents; } public void setAntecedents(String antecedents) { this.antecedents = antecedents; } public List<Content> getContents() { return contents; } public void setContents(List<Content> contents) { this.contents = contents; } }
20.477273
328
0.582686
8e65f3dbb55f01aec8aeb55751b054c78a29b438
20
public class aa { }
6.666667
17
0.65
c7fb2f1593e75732474a6a4665bd5684644b413c
732
package com.liugh.bean.chain; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; @Service public class ApplicationService { @Autowired private ApplicationContext context; public void mockedClient() { // request一般是通过外部调用获取 Request request = new Request(); Pipeline pipeline = newPipeline(request); try { pipeline.fireTaskReceived(); pipeline.fireTaskFiltered(); pipeline.fireTaskExecuted(); } finally { pipeline.fireAfterCompletion(); } } private Pipeline newPipeline(Request request) { return context.getBean(DefaultPipeline.class, request); } }
25.241379
62
0.737705
725362aad9b91c8d030c1d5c5cd8e2e0c7ab6ac8
5,031
/* * (c) Copyright 2018 Palantir Technologies 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 com.palantir.lock.client; import java.io.IOException; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableSet; import com.palantir.common.concurrent.PTExecutors; import com.palantir.lock.ForwardingRemoteLockService; import com.palantir.lock.HeldLocksToken; import com.palantir.lock.LockRefreshToken; import com.palantir.lock.LockRequest; import com.palantir.lock.RemoteLockService; @SuppressWarnings("checkstyle:FinalClass") // Avoid breaking API in case someone extended this public class LockRefreshingRemoteLockService extends ForwardingRemoteLockService { private static final Logger log = LoggerFactory.getLogger(LockRefreshingRemoteLockService.class); final RemoteLockService delegate; final Set<LockRefreshToken> toRefresh; final ScheduledExecutorService exec; final long refreshFrequencyMillis = 5000; volatile boolean isClosed = false; public static LockRefreshingRemoteLockService create(RemoteLockService delegate) { final LockRefreshingRemoteLockService ret = new LockRefreshingRemoteLockService(delegate); ret.exec.scheduleWithFixedDelay(() -> { long startTime = System.currentTimeMillis(); try { ret.refreshLocks(); } catch (Throwable t) { log.warn("Failed to refresh locks", t); } finally { long elapsed = System.currentTimeMillis() - startTime; if (elapsed > LockRequest.getDefaultLockTimeout().toMillis() / 2) { log.warn("Refreshing locks took {} milliseconds" + " for tokens: {}", elapsed, ret.toRefresh); } else if (elapsed > ret.refreshFrequencyMillis) { log.info("Refreshing locks took {} milliseconds" + " for tokens: {}", elapsed, ret.toRefresh); } } }, 0, ret.refreshFrequencyMillis, TimeUnit.MILLISECONDS); return ret; } private LockRefreshingRemoteLockService(RemoteLockService delegate) { this.delegate = delegate; toRefresh = ConcurrentHashMap.newKeySet(); exec = PTExecutors.newScheduledThreadPool(1, PTExecutors.newNamedThreadFactory(true)); } @Override protected RemoteLockService delegate() { return delegate; } @Override public LockRefreshToken lock(String client, LockRequest request) throws InterruptedException { LockRefreshToken ret = super.lock(client, request); if (ret != null) { toRefresh.add(ret); } return ret; } @Override public HeldLocksToken lockAndGetHeldLocks(String client, LockRequest request) throws InterruptedException { HeldLocksToken ret = super.lockAndGetHeldLocks(client, request); if (ret != null) { toRefresh.add(ret.getLockRefreshToken()); } return ret; } @Override public boolean unlock(LockRefreshToken token) { toRefresh.remove(token); return super.unlock(token); } private void refreshLocks() { ImmutableSet<LockRefreshToken> refreshCopy = ImmutableSet.copyOf(toRefresh); if (refreshCopy.isEmpty()) { return; } Set<LockRefreshToken> refreshedTokens = delegate().refreshLockRefreshTokens(refreshCopy); for (LockRefreshToken token : refreshCopy) { if (!refreshedTokens.contains(token) && toRefresh.contains(token)) { log.warn("failed to refresh lock: {}", token); toRefresh.remove(token); } } } @Override @SuppressWarnings("checkstyle:NoFinalizer") // TODO (jkong): Can we safely remove this without breaking things? protected void finalize() throws Throwable { super.finalize(); if (!isClosed) { log.warn("Closing in the finalize method. This should be closed explicitly."); dispose(); } } public void dispose() { exec.shutdown(); isClosed = true; } @Override public void close() throws IOException { super.close(); dispose(); } }
36.194245
115
0.664878
c22094b8def189e4b156b68961d2f87bf18c4ab2
1,130
package com.kioea.www.jsqlparsertest; import java.io.StringReader; import junit.framework.TestCase; import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.statement.truncate.Truncate; import org.junit.Test; public class TruncateTest extends TestCase { private CCJSqlParserManager parserManager = new CCJSqlParserManager(); public TruncateTest(String arg0) { super(arg0); } @Test public void testTruncate() throws Exception { String statement = "TRUncATE TABLE myschema.mytab"; Truncate truncate = (Truncate) parserManager.parse(new StringReader(statement)); assertEquals("myschema", truncate.getTable().getSchemaName()); assertEquals("myschema.mytab", truncate.getTable().getWholeTableName()); assertEquals(statement.toUpperCase(), truncate.toString().toUpperCase()); statement = "TRUncATE TABLE mytab"; String toStringStatement = "TRUncATE TABLE mytab"; truncate = (Truncate) parserManager.parse(new StringReader(statement)); assertEquals("mytab", truncate.getTable().getName()); assertEquals(toStringStatement.toUpperCase(), truncate.toString().toUpperCase()); } }
34.242424
83
0.776106
52cf1e807c6940c6440bad68d6a79833bdd38b71
5,163
/* * MIT License * * Copyright (c) 2019 Syswin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.syswin.temail.notification.main.domains; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.google.gson.Gson; import com.syswin.temail.notification.main.util.NotificationUtil; import com.syswin.temail.notification.main.util.TopicEventUtil; import java.util.List; /** * @author [email protected] */ @JsonInclude(Include.NON_NULL) public class TopicEvent { /** * 事件参数 */ @JsonIgnore private Long id; private String xPacketId; private Long eventSeqId; private Integer eventType; /** * 话题参数 */ private String topicId; private String msgId; private Long seqId; private String message; private String from; private String to; private Long timestamp; // 以下参数均存入扩展参数字段 /** * 批量msgId */ private List<String> msgIds; /** * 删除会话是否同时删除消息 */ private Boolean deleteAllMsg; @JsonIgnore private String extendParam; /** * 自动解析扩展字段 */ public TopicEvent autoReadExtendParam(Gson gson) { if (this.extendParam != null && !this.extendParam.isEmpty()) { NotificationUtil.copyField(gson.fromJson(this.extendParam, TopicEvent.class), this); } return this; } /** * 自动配置扩展字段 */ public TopicEvent autoWriteExtendParam(String params) { this.extendParam = TopicEventUtil.initExtendParam(params, this); return this; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getxPacketId() { return xPacketId; } public void setxPacketId(String xPacketId) { this.xPacketId = xPacketId; } public Long getEventSeqId() { return eventSeqId; } public void setEventSeqId(Long eventSeqId) { this.eventSeqId = eventSeqId; } public Integer getEventType() { return eventType; } public void setEventType(Integer eventType) { this.eventType = eventType; } public String getTopicId() { return topicId; } public void setTopicId(String topicId) { this.topicId = topicId; } public String getMsgId() { return msgId; } public void setMsgId(String msgId) { this.msgId = msgId; } public Long getSeqId() { return seqId; } public void setSeqId(Long seqId) { this.seqId = seqId; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Long getTimestamp() { if (this.timestamp == null) { this.timestamp = System.currentTimeMillis(); } return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public List<String> getMsgIds() { return msgIds; } public void setMsgIds(List<String> msgIds) { this.msgIds = msgIds; } public Boolean getDeleteAllMsg() { return deleteAllMsg; } public void setDeleteAllMsg(Boolean deleteAllMsg) { this.deleteAllMsg = deleteAllMsg; } public String getExtendParam() { return extendParam; } public void setExtendParam(String extendParam) { this.extendParam = extendParam; } @Override public String toString() { return "TopicEvent{" + "id=" + id + ", xPacketId='" + xPacketId + '\'' + ", eventSeqId=" + eventSeqId + ", eventType=" + eventType + ", topicId='" + topicId + '\'' + ", msgId='" + msgId + '\'' + ", seqId=" + seqId + ", message length='" + (message == null ? 0 : message.length()) + '\'' + ", from='" + from + '\'' + ", to='" + to + '\'' + ", timestamp=" + timestamp + ", msgIds=" + msgIds + ", deleteAllMsg=" + deleteAllMsg + ", extendParam='" + extendParam + '\'' + '}'; } }
22.845133
90
0.662018
3182e264d08fc708354a2ae56d3aa99b7c8f9c46
17,671
/** * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.localsearch; import static org.junit.Assert.assertTrue; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.evosuite.Properties; import org.evosuite.Properties.Criterion; import org.evosuite.Properties.SolverType; import org.evosuite.Properties.StoppingCondition; import org.evosuite.TestGenerationContext; import org.evosuite.classpath.ClassPathHandler; import org.evosuite.coverage.FitnessFunctions; import org.evosuite.ga.localsearch.DefaultLocalSearchObjective; import org.evosuite.setup.DependencyAnalysis; import org.evosuite.symbolic.TestCaseBuilder; import org.evosuite.testcase.DefaultTestCase; import org.evosuite.testcase.execution.ExecutionTracer; import org.evosuite.testcase.execution.reset.ClassReInitializer; import org.evosuite.testcase.variable.VariableReference; import org.evosuite.testsuite.TestSuiteChromosome; import org.evosuite.testsuite.TestSuiteFitnessFunction; import org.evosuite.utils.Randomness; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.examples.with.different.packagename.concolic.MIMEType; public class TestLocalSearchMIMEType { private final static boolean DEFAULT_IS_TRACE_ENABLED = ExecutionTracer.isTraceCallsEnabled(); private java.util.Properties currentProperties; @Before public void setUp() { ClassPathHandler.getInstance().changeTargetCPtoTheSameAsEvoSuite(); Properties.getInstance().resetToDefaults(); Randomness.setSeed(42); Properties.TARGET_CLASS = ""; TestGenerationContext.getInstance().resetContext(); ClassReInitializer.resetSingleton(); Randomness.setSeed(42); currentProperties = (java.util.Properties) System.getProperties().clone(); Properties.CRITERION = new Criterion[] { Criterion.LINE, Criterion.BRANCH, Criterion.EXCEPTION, Criterion.WEAKMUTATION, Criterion.OUTPUT, Criterion.METHOD, Criterion.METHODNOEXCEPTION, Criterion.CBRANCH }; ExecutionTracer.enableTraceCalls(); } @After public void tearDown() { if (DEFAULT_IS_TRACE_ENABLED) { ExecutionTracer.enableTraceCalls(); } else { ExecutionTracer.disableTraceCalls(); } TestGenerationContext.getInstance().resetContext(); ClassReInitializer.resetSingleton(); System.setProperties(currentProperties); Properties.getInstance().resetToDefaults(); } private DefaultTestCase createTestCase0() throws NoSuchFieldException, SecurityException, NoSuchMethodException, ClassNotFoundException { TestCaseBuilder builder = new TestCaseBuilder(); final Class<?> mimeTypeClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(MIMEType.class.getName()); final Field memField = mimeTypeClass.getField("MEM"); final Method toString = mimeTypeClass.getMethod("toString"); VariableReference mIMEType0 = builder.appendStaticFieldStmt(memField); builder.appendMethod(mIMEType0, toString); System.out.println("Test Case #0=" + builder.toCode()); return builder.getDefaultTestCase(); } private DefaultTestCase createTestCase2() throws NoSuchFieldException, SecurityException, NoSuchMethodException, ClassNotFoundException { final Class<?> mimeTypeClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(MIMEType.class.getName()); final Field rdfField = mimeTypeClass.getDeclaredField("RDF"); final Method hashCode = mimeTypeClass.getMethod("hashCode"); final Field slashField = mimeTypeClass.getDeclaredField("slash"); final Method getTypeMethod = mimeTypeClass.getMethod("getType"); final Method getSubTypeMethod = mimeTypeClass.getMethod("getSubType"); final Method equalsMethod = mimeTypeClass.getMethod("equals", Object.class); final Field mimeTypeField = mimeTypeClass.getDeclaredField("mimeType"); final Constructor<?> constructorStringBoolean = mimeTypeClass.getConstructor(String.class, boolean.class); final TestCaseBuilder builder = new TestCaseBuilder(); VariableReference mIMEType0 = builder.appendStaticFieldStmt(rdfField); VariableReference string0 = builder.appendStringPrimitive(""); VariableReference int0 = builder.appendMethod(mIMEType0, hashCode); VariableReference string1 = builder.appendStringPrimitive(""); VariableReference int1 = builder.appendIntPrimitive(0); VariableReference string2 = builder .appendStringPrimitive("com.examples.with.different.packagename.concolic.MalformedMIMETypeException"); builder.appendAssignment(mIMEType0, slashField, int1); VariableReference int2 = builder.appendFieldStmt(mIMEType0, slashField); VariableReference string3 = builder.appendMethod(mIMEType0, getTypeMethod); VariableReference string4 = builder.appendMethod(mIMEType0, getSubTypeMethod); VariableReference boolean0 = builder.appendMethod(mIMEType0, equalsMethod, string3); VariableReference string5 = builder.appendFieldStmt(mIMEType0, mimeTypeField); VariableReference string6 = builder.appendMethod(mIMEType0, getSubTypeMethod); VariableReference int3 = builder.appendFieldStmt(mIMEType0, slashField); VariableReference string7 = builder.appendStringPrimitive("xT7vo\"<|[E{4"); builder.appendConstructor(constructorStringBoolean, string7, boolean0); builder.addException(new Error()); System.out.println("Test Case #2=" + builder.toCode()); return builder.getDefaultTestCase(); } private DefaultTestCase createTestCase1() throws NoSuchFieldException, SecurityException, NoSuchMethodException, ClassNotFoundException { final TestCaseBuilder builder = new TestCaseBuilder(); final Class<?> mimeTypeClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(MIMEType.class.getName()); final Class<?> objectClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(Object.class.getName()); final Constructor<?> constructorStringBoolean = mimeTypeClass.getConstructor(String.class, boolean.class); final Constructor<?> constructorString = mimeTypeClass.getConstructor(String.class); final Field mimeTypeField = mimeTypeClass.getDeclaredField("mimeType"); final Field slashField = mimeTypeClass.getDeclaredField("slash"); final Method getSubTypeMethod = mimeTypeClass.getMethod("getSubType"); final Method equalsMethod = mimeTypeClass.getMethod("equals", Object.class); final Method getTypeMethod = mimeTypeClass.getMethod("getType"); VariableReference string0 = builder.appendStringPrimitive("Y.8p>:/]WybaL"); VariableReference boolean0 = builder.appendBooleanPrimitive(false); VariableReference mIMEType0 = builder.appendConstructor(constructorStringBoolean, string0, boolean0); VariableReference int0 = builder.appendIntPrimitive(-1); VariableReference int1 = builder.appendIntPrimitive(-1); VariableReference int2 = builder.appendIntPrimitive(1); builder.appendAssignment(mIMEType0, slashField, int2); builder.appendAssignment(mIMEType0, slashField, int0); builder.appendAssignment(mIMEType0, slashField, int1); VariableReference int3 = builder.appendIntPrimitive(0); VariableReference string1 = builder.appendStringPrimitive("Jm"); builder.appendAssignment(mIMEType0, mimeTypeField, string1); VariableReference int4 = builder.appendIntPrimitive(2556); VariableReference int5 = builder.appendIntPrimitive(2556); builder.appendAssignment(mIMEType0, slashField, int4); builder.appendAssignment(mIMEType0, slashField, int3); VariableReference string2 = builder.appendMethod(mIMEType0, getSubTypeMethod); VariableReference object0 = builder.appendNull(objectClass); VariableReference boolean1 = builder.appendMethod(mIMEType0, equalsMethod, object0); VariableReference object1 = builder.appendNull(objectClass); VariableReference boolean2 = builder.appendMethod(mIMEType0, equalsMethod, object1); VariableReference string3 = builder.appendStringPrimitive(""); VariableReference mIMEType1 = builder.appendConstructor(constructorString, string3); builder.addException(new Exception()); builder.appendAssignment(mIMEType1, slashField, int5); VariableReference string4 = builder.appendStringPrimitive("DI'XL>AQzq1"); builder.appendAssignment(mIMEType1, mimeTypeField, string4); VariableReference string5 = builder.appendFieldStmt(mIMEType1, mimeTypeField); VariableReference string6 = builder.appendStringPrimitive("bjvXpt%"); VariableReference boolean3 = builder.appendBooleanPrimitive(true); VariableReference mIMEType2 = builder.appendConstructor(constructorStringBoolean, string6, boolean3); builder.appendAssignment(mIMEType2, slashField, mIMEType0, slashField); VariableReference string7 = builder.appendMethod(mIMEType0, getTypeMethod); VariableReference mIMEType3 = builder.appendConstructor(constructorStringBoolean, string5, boolean1); builder.appendAssignment(mIMEType1, mimeTypeField, string7); VariableReference string8 = builder.appendStringPrimitive("g"); VariableReference mIMEType4 = builder.appendConstructor(constructorString, string8); VariableReference string9 = builder.appendMethod(mIMEType1, getTypeMethod); System.out.println("Test Case #1=" + builder.toCode()); return builder.getDefaultTestCase(); } @Test public void testFitness() throws NoSuchFieldException, SecurityException, NoSuchMethodException, ClassNotFoundException { Properties.RESET_STATIC_FINAL_FIELDS = false; Properties.TEST_ARCHIVE = false; Properties.LOCAL_SEARCH_PROBABILITY = 1.0; Properties.LOCAL_SEARCH_RATE = 1; Properties.LOCAL_SEARCH_BUDGET_TYPE = Properties.LocalSearchBudgetType.TESTS; Properties.LOCAL_SEARCH_BUDGET = 100; Properties.DSE_SOLVER = SolverType.EVOSUITE_SOLVER; Properties.STOPPING_CONDITION = StoppingCondition.MAXTIME; Properties.SEARCH_BUDGET = 120; Properties.TARGET_CLASS = MIMEType.class.getName(); String classPath = ClassPathHandler.getInstance().getTargetProjectClasspath(); DependencyAnalysis.analyzeClass(MIMEType.class.getName(), Arrays.asList(classPath)); TestSuiteChromosome suite = new TestSuiteChromosome(); DefaultTestCase test0 = createTestCase0(); DefaultTestCase test1 = createTestCase1(); DefaultTestCase test2 = createTestCase2(); DefaultTestCase test3 = createTestCase3(); DefaultTestCase test4 = createTestCase4(); DefaultTestCase test5 = createTestCase5(); suite.addTest(test0); suite.addTest(test1); suite.addTest(test2); suite.addTest(test3); suite.addTest(test4); suite.addTest(test5); TestSuiteFitnessFunction lineCoverage = FitnessFunctions.getFitnessFunction(Criterion.LINE); TestSuiteFitnessFunction branchCoverage = FitnessFunctions.getFitnessFunction(Criterion.BRANCH); TestSuiteFitnessFunction exceptionCoverage = FitnessFunctions.getFitnessFunction(Criterion.EXCEPTION); TestSuiteFitnessFunction weakMutationCoverage = FitnessFunctions.getFitnessFunction(Criterion.WEAKMUTATION); TestSuiteFitnessFunction outputCoverage = FitnessFunctions.getFitnessFunction(Criterion.OUTPUT); TestSuiteFitnessFunction methodCoverage = FitnessFunctions.getFitnessFunction(Criterion.METHOD); TestSuiteFitnessFunction methodNoExceptionCoverage = FitnessFunctions .getFitnessFunction(Criterion.METHODNOEXCEPTION); TestSuiteFitnessFunction cbranchCoverage = FitnessFunctions.getFitnessFunction(Criterion.CBRANCH); List<TestSuiteFitnessFunction> fitnessFunctions = new ArrayList<TestSuiteFitnessFunction>(); fitnessFunctions.add(lineCoverage); fitnessFunctions.add(branchCoverage); fitnessFunctions.add(exceptionCoverage); fitnessFunctions.add(weakMutationCoverage); fitnessFunctions.add(outputCoverage); fitnessFunctions.add(methodCoverage); fitnessFunctions.add(methodNoExceptionCoverage); fitnessFunctions.add(cbranchCoverage); for (TestSuiteFitnessFunction ff : fitnessFunctions) { suite.addFitness(ff); } for (TestSuiteFitnessFunction ff : fitnessFunctions) { double oldFitness = ff.getFitness(suite); System.out.println(ff.toString() + "->" + oldFitness); } double oldFitness = suite.getFitness(); System.out.println("oldFitness->" + oldFitness); System.out.println("oldSize->" + suite.getTests().size()); DefaultLocalSearchObjective objective = new DefaultLocalSearchObjective<>(); for (TestSuiteFitnessFunction ff : fitnessFunctions) { objective.addFitnessFunction(ff); } boolean hasImproved = suite.localSearch(objective); System.out.println("hasImproved=" + hasImproved); for (TestSuiteFitnessFunction ff : fitnessFunctions) { double newFitness = ff.getFitness(suite); System.out.println(ff.toString() + "->" + newFitness); } double newFitness = suite.getFitness(); System.out.println("newFitness->" + newFitness); System.out.println("newSize->" + suite.getTests().size()); assertTrue(newFitness<=oldFitness); } private DefaultTestCase createTestCase3() throws NoSuchFieldException, SecurityException, NoSuchMethodException, ClassNotFoundException { final Class<?> mimeTypeClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(MIMEType.class.getName()); final Field xmlField = mimeTypeClass.getDeclaredField("XML"); final Method toString = mimeTypeClass.getMethod("toString"); final TestCaseBuilder builder = new TestCaseBuilder(); VariableReference mIMEType0 = builder.appendStaticFieldStmt(xmlField); VariableReference string0 = builder.appendMethod(mIMEType0, toString); System.out.println("Test Case #3=" + builder.toCode()); return builder.getDefaultTestCase(); } private DefaultTestCase createTestCase4() throws NoSuchFieldException, SecurityException, NoSuchMethodException, ClassNotFoundException { final Class<?> mimeTypeClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(MIMEType.class.getName()); final Field rdfField = mimeTypeClass.getDeclaredField("RDF"); final Field slashField = mimeTypeClass.getDeclaredField("slash"); final Method equalsMethod = mimeTypeClass.getMethod("equals", Object.class); final Constructor<?> constructorString = mimeTypeClass.getConstructor(String.class); final Field mimeTypeField = mimeTypeClass.getDeclaredField("mimeType"); final Method getTypeMethod = mimeTypeClass.getMethod("getType"); final Method toString = mimeTypeClass.getMethod("toString"); final TestCaseBuilder builder = new TestCaseBuilder(); VariableReference mIMEType0 = builder.appendStaticFieldStmt(rdfField); VariableReference int0 = builder.appendIntPrimitive(2415); VariableReference int1 = builder.appendIntPrimitive(2415); VariableReference int2 = builder.appendIntPrimitive(-196); builder.appendAssignment(mIMEType0, slashField, int2); builder.appendAssignment(mIMEType0, slashField, int0); VariableReference int3 = builder.appendIntPrimitive(0); builder.appendAssignment(mIMEType0, slashField, int1); builder.appendAssignment(mIMEType0, slashField, int3); VariableReference boolean0 = builder.appendMethod(mIMEType0, equalsMethod, mIMEType0); VariableReference string0 = builder.appendStringPrimitive("/"); VariableReference string1 = builder.appendStringPrimitive("\"cC3$]nc.<p) u:"); VariableReference mIMEType1 = builder.appendConstructor(constructorString, string0); builder.appendAssignment(mIMEType1, slashField, mIMEType0, slashField); VariableReference string2 = builder.appendNull(String.class); builder.appendAssignment(mIMEType1, mimeTypeField, string2); VariableReference int4 = builder.appendFieldStmt(mIMEType0, slashField); builder.appendMethod(mIMEType1, getTypeMethod); builder.addException(new NullPointerException()); VariableReference string3 = builder.appendMethod(mIMEType1, toString); System.out.println("Test Case #4=" + builder.toCode()); return builder.getDefaultTestCase(); } private DefaultTestCase createTestCase5() throws NoSuchFieldException, SecurityException, NoSuchMethodException, ClassNotFoundException { final Class<?> mimeTypeClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(MIMEType.class.getName()); final Field memField = mimeTypeClass.getDeclaredField("MEM"); final Method toString = mimeTypeClass.getMethod("toString"); final TestCaseBuilder builder = new TestCaseBuilder(); VariableReference mIMEType0 = builder.appendStaticFieldStmt(memField); VariableReference string0 = builder.appendMethod(mIMEType0, toString); System.out.println("Test Case #5=" + builder.toCode()); return builder.getDefaultTestCase(); } }
48.149864
111
0.785128
2a23d261066241d914746c7901a436c17be200c5
11,625
/* * Copyright (C) 2017-present, Chenai Nakam([email protected]) * * 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 hobby.wei.c.remote.api; import java.util.HashMap; import java.util.Map; import hobby.wei.c.data.abs.IParser; import hobby.wei.c.remote.INetAces.Method; /** * 网络接口数据缓存配置。 * 与网络接口有关的任务,缓存全部存入一个接口专用的通用数据库表。 * 是否访问网络跟缓存配置有关。除正常情况`先读缓存后读网络`以外,访问网络【之前】是否访问【缓存】数据库跟具体的任务类型有关。分为两种情况: * 1、虽然有缓存,但仍强制访问网络:如登录。应该直接访问网络而不应先访问缓存数据库(登录需要的参数应该在之前的任务中读取); * 2、即使有网络连接,即使缓存为空,也只读缓存而不访问网络:如获取上次登录的用户信息。由于登录之后获取的用户信息是存入接口专用表的, * 因此需要访问接口专用表,但是接口专用表是不允许其他非网络接口任务使用的,因此需要配置为接口任务,但是不访问网络。 * * @author Wei Chou([email protected]) * @version 1.0, xx/xx/2013 */ public abstract class Api { public final static long DAY_TIME_MS = 24 * 60 * 60 * 1000; protected abstract String key4Uid(); protected abstract String key4Passport(); protected abstract String key4PageNum(); protected abstract String key4PageSize(); protected abstract int maxPageSize(); /** * 全局唯一的名字,所有Api配置中不可重复。 * 这里把一个特定接口“controller、参数个数、参数类型”三者的组合看作一个 Category,因此对于同一个 controller 有不同参数的组合的情况, * 仅通过 controller 无法标识一个特定类型的请求(Category),因此通过 name 标识。 */ public final String name; public final String baseUrl; public final String controller; public final int method; /** * passport放到header里面。 */ public final boolean passport; /** * 是否分页。 */ public final boolean pagination; public final Map<String, String> headers; public final String[] params; public final String[] defValues; /** * 作为缓存key生成条件的参数,必须包含于 params。要求这些值对于一条记录是不变的且足够标识一条记录。 * 注意:pageSize 是不应该有的;对于与用户有关的数据,userId 会自动设置为一个参数,这里不需要添加。 */ public final String[] cacheParams; /** * 缓存时间,小于 0 表示没有缓存,0表示无限缓存,不用写入缓存时间。大于 0 则需要写入缓存时间。单位:毫秒。 */ public final long cacheTimeMS; /** * 数据解析器。 */ public final IParser parser; public Api(String url, String controller, int method, String[] params, long cacheTimeMS, IParser parser) { this(null, url, controller, method, false, params, null, params, cacheTimeMS, parser); } public Api(String url, String controller, int method, String[] params, String[] cacheParams, long cacheTimeMS, IParser parser) { this(null, url, controller, method, false, params, null, cacheParams, cacheTimeMS, parser); } public Api(String name, String url, String controller, int method, boolean passport, String[] params, String[] defValues, String[] cacheParams, long cacheTimeMS, IParser parser) { this(name, url, controller, method, passport, null, params, defValues, cacheParams, cacheTimeMS, parser); } public Api(String name, String baseUrl, String controller, int method, boolean passport, Map<String, String> headers, String[] params, String[] defValues, String[] cacheParams, long cacheTimeMS, IParser parser) { if (name == null || name.length() == 0) name = null; if (controller == null || controller.length() == 0) controller = null; baseUrl = baseUrl.trim().toLowerCase(); if (!baseUrl.startsWith("http")) throw new IllegalArgumentException("baseUrl必须以`http`开头"); if (controller != null) { controller = controller.trim(); if (!controller.matches(REGEX)) throw new IllegalArgumentException("controller含有非法字符`" + controller + "`,参见正则`" + REGEX + "`。"); if (!baseUrl.endsWith("/")) throw new IllegalArgumentException("当controller不为空时,baseUrl必须以`/`结尾。"); } else { if (baseUrl.endsWith("/")) throw new IllegalArgumentException("当controller为空时,baseUrl不能以`/`结尾。"); } if (name != null) { name = name.trim(); if (!name.matches(REGEX)) throw new IllegalArgumentException("name含有非法字符`" + name + "`,参见正则`" + REGEX + "`。"); } else { name = controller; if (name == null) throw new IllegalArgumentException("当controller为空时,name不能为空。"); } if (method < Method.DEPRECATED_GET_OR_POST || method > Method.DELETE) { throw new IllegalArgumentException("method值不正确,详见" + Method.class.getName()); } if (defValues == null || defValues.length == 0) defValues = null; if (defValues != null && defValues.length > params.length) throw new IllegalArgumentException("defValues长度不能大于params。可以为null。"); if (params == null || params.length == 0) params = null; if (cacheParams == null || cacheParams.length == 0) cacheParams = null; if (cacheTimeMS >= 0) { int len = params == null ? 0 : params.length; int clen = cacheParams == null ? 0 : cacheParams.length; if (len > 0 && clen == 0) throw new IllegalArgumentException("启用了缓存,cacheParams不能为空。"); if (passport && clen == 0) throw new IllegalArgumentException("启用了缓存,且数据与用户相关(passport),cacheParams必须含有`" + key4Uid() + "`字段。"); if (passport) { if (clen > len + 1) throw new IllegalArgumentException("启用了缓存,cacheParams长度不能超过params.length + 1。"); } else { if (clen > len) throw new IllegalArgumentException("启用了缓存,cacheParams长度不能超过params。"); } } //////////////////// 避免之后其他部分代码的频繁 toLowerCase() 以及由此引发的错误 /////////////////////////// boolean pagination = false, pageNo = false, pageSize = false; if (params != null) { for (int i = 0; i < params.length; i++) { params[i] = params[i].toLowerCase(); if (!pageNo && params[i].equals(key4PageNum())) { pagination = pageNo = true; continue; } if (!pageSize && params[i].equals(key4PageSize())) { pagination = pageSize = true; if (defValues != null && defValues.length > i) { int size = Integer.parseInt(defValues[i]); if (size > maxPageSize()) throw new IllegalArgumentException("pageSize不能超过`" + maxPageSize() + "`。"); } } } for (int i = 0; i < params.length; i++) { for (int j = i + 1; j < params.length; j++) { if (params[i].equals(params[j])) throw new IllegalArgumentException("params不能有重复:" + params[i] + ", [" + i + "], [" + j + "]。"); } } } if (pagination && !pageNo) throw new IllegalArgumentException("由于有分页,params必须含有`" + key4PageNum() + "`字段。"); if (pagination && !pageSize) throw new IllegalArgumentException("由于有分页,params必须含有`" + key4PageSize() + "`字段。"); boolean userId = pageNo = false; if (cacheParams != null && cacheTimeMS >= 0) { for (int i = 0; i < cacheParams.length; i++) { cacheParams[i] = cacheParams[i].toLowerCase(); if (passport && !userId && cacheParams[i].equals(key4Uid())) { userId = true; continue; } if (pagination && !pageNo && cacheParams[i].equals(key4PageNum())) { pageNo = true; continue; } if (cacheParams[i].equals(key4PageSize())) { throw new IllegalArgumentException("cacheParams不应该含有`" + key4PageSize() + "`字段。"); } } for (int i = 0; i < cacheParams.length; i++) { for (int j = i + 1; j < cacheParams.length; j++) { if (cacheParams[i].equals(cacheParams[j])) throw new IllegalArgumentException("cacheParams不能有重复:" + cacheParams[i] + ", [" + i + "], [" + j + "]。"); } } } if (cacheTimeMS >= 0 && passport && !userId) throw new IllegalArgumentException("启用了缓存,数据与用户相关(passport),cacheParams必须含有`" + key4Uid() + "`字段。"); if (cacheTimeMS >= 0 && pagination && !pageNo) throw new IllegalArgumentException("启用了缓存,有分页,cacheParams必须含有`" + key4PageNum() + "`字段。"); if (cacheTimeMS >= 0) { //////////////////// 仅检查 cacheParams 是否包含于 params ///////////////////////////////// if (cacheParams != null) { boolean contain = false, checked = false; for (String c : cacheParams) { contain = false; if (params != null) { for (String p : params) { if (c.equals(p)) { contain = true; break; } } } if (!contain) { if (!checked && c.equals(key4Uid())) { checked = true; if (passport) continue; } throw new IllegalArgumentException("cacheParams必须包含于params。passport为true时,`" + key4Uid() + "`字段除外。"); } } } } this.name = name; this.baseUrl = baseUrl; this.controller = controller; this.method = method; this.passport = passport; this.pagination = pagination; this.headers = headers; this.params = params; this.defValues = defValues; this.cacheParams = cacheParams; this.cacheTimeMS = cacheTimeMS; this.parser = parser; } public final Map<String, String> getMappedParams(Map<String, String> paramsMap) { Map<String, String> taskParams = new HashMap<String, String>(); if (defValues != null) { for (int i = 0; i < defValues.length; i++) { taskParams.put(params[i], defValues[i]); } } if (params != null) { String value; for (String key : params) { value = paramsMap.get(key); if (value != null && value.length() > 0) { if (key.equals(key4PageSize()) && Integer.parseInt(value) > maxPageSize()) { throw new IllegalArgumentException("pageSize不能超过`" + maxPageSize() + "`。"); } if (key.equals(key4PageNum()) && Integer.parseInt(value) < 1) { throw new IllegalArgumentException("pageNo不能小于1。"); } taskParams.put(key, value); } else if (!taskParams.containsKey(key)) { taskParams.put(key, value); } } } if (cacheParams != null) { for (String p : cacheParams) { if (!taskParams.containsKey(p)) taskParams.put(p, paramsMap.get(p)); } } if (passport) taskParams.put(key4Passport(), paramsMap.get(key4Passport())); return taskParams; } private static final String REGEX = "[A-Za-z_$]+\\d*[A-Za-z_$]*"; }
43.703008
145
0.557075
f03325f272a1f6cf28ce68e0c25c7d893575dd98
568
/* * This Java source file was generated by the Gradle 'init' task. */ package it.unicam.cs.ids.c3; import it.unicam.cs.ids.c3.javafx.JavaFXC3; import it.unicam.cs.ids.c3.database.DBManager; import javafx.application.Application; import java.io.IOException; import java.sql.SQLException; public class App { public static void main(String[] args) throws IOException, SQLException { DBManager.getInstance().setDBManager("root", "toor"); launchGui(); } private static void launchGui() { Application.launch(JavaFXC3.class); } }
27.047619
77
0.711268
70f3566259dc1e6f7d89300de75d0ee603597296
1,151
package br.com.projeto.casa.codigo.pais.modelo; import br.com.projeto.casa.codigo.pais.modelo.excessao.PaisNaoEncontradoException; import br.com.projeto.casa.codigo.pais.repositorio.PaisRepositorio; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotBlank; @Entity public class Pais { public static Pais buscarPorId( final Long id, final PaisRepositorio paisRepositorio ){ return paisRepositorio .findById( id ) .orElseThrow(() -> new PaisNaoEncontradoException( String.format("Pais com id { %d } nao encontrado.", id) )); } @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) private Long id; @NotBlank private String nome; protected Pais(){} public Pais(final String nome){ this.nome = nome; } public String getNome() { return nome; } public Pais cadastrar( final PaisRepositorio paisRepositorio ) { return paisRepositorio.save( this ); } }
25.577778
91
0.67854
00bd2e89c56b3d53f8480d31a8615c7ef92e1dbe
5,978
package com.iceberg.dao; import com.iceberg.entity.Role; import com.iceberg.entity.UserInfo; import com.iceberg.utils.PageModel; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest public class UserInfoMapperTest { private Logger logger = LoggerFactory.getLogger(UserInfoMapper.class); @Autowired private UserInfoMapper userInfoMapper; /** * Get user's information by their partial information */ @Test public void getUserInfoTest() { logger.info("getUserInfoTest"); UserInfo userInfo = new UserInfo(); userInfo.setId(1); // userInfo.setUsername("zsh"); UserInfo userInfo1 = userInfoMapper.getUserInfo(userInfo); int id = userInfo1.getId(); assertEquals(1, id); logger.info("getUserInfoTest success"); } /** * Given user information, add a user. */ @Test public void addUserTest() { logger.info("addUserTest"); UserInfo userInfo = new UserInfo(8888, "czy", "[email protected]"); userInfoMapper.delete("8888"); int add = userInfoMapper.add(userInfo); assertEquals(1, add); logger.info("addUserTest success"); } /** * Given user information, find if the user exists. */ @Test public void userIsExistedTest() { logger.info("userIsExistedTest"); UserInfo userInfo = new UserInfo(); userInfo.setUsername("hwj"); int num = userInfoMapper.userIsExisted(userInfo); assertEquals(1, num); logger.info("userIsExistedTest success"); } @Test public void getUsersByWhereTest() { logger.info("getUsersByWhereTest"); UserInfo userInfo = new UserInfo(); userInfo.setRoleid(1); userInfo.setUsername("hwj"); PageModel<UserInfo> userInfoPageModel = new PageModel<UserInfo>(2,userInfo); List<UserInfo> usersByWhere = userInfoMapper.getUsersByWhere(userInfoPageModel); assertEquals(0, usersByWhere.size()); logger.info("getUsersByWhereTest success"); } @Test public void getToatlByWhereTest() { logger.info("getToatlByWhereTest"); UserInfo userInfo = new UserInfo(); userInfo.setRoleid(1); userInfo.setUsername("hwj"); PageModel<UserInfo> userInfoPageModel = new PageModel<>(2, userInfo); int toatlByWhere = userInfoMapper.getToatlByWhere(userInfoPageModel); assertEquals(1, toatlByWhere); logger.info("getToatlByWhereTest success"); } /** * Find a user by id and update the user's information. */ @Test public void updateTest() { logger.info("updateTest"); UserInfo userInfo = new UserInfo(); userInfo.setId(8888); userInfo.setUsername("testtest"); userInfo.setRealname("testuser"); int update = userInfoMapper.update(userInfo); assertEquals(1, update); logger.info("updateTest success"); } /** * Delete a user by id. */ @Test public void deleteTest() { logger.info("deleteTest"); UserInfo userInfo = new UserInfo(); userInfo.setId(9999); userInfo.setRoleid(3); userInfo.setUsername("deltest"); userInfo.setRealname("truedeltest"); userInfoMapper.add(userInfo); int delete = userInfoMapper.delete("9999"); assertEquals(1, delete); logger.info("deleteTest success"); } /** * Find all existing roles. */ @Test public void getAllRolesTest() { logger.info("getAllRolesTest"); List<Role> allRoles = userInfoMapper.getAllRoles(); for (Role r : allRoles) { System.out.println(r.getRolename()); } String rolename = allRoles.get(0).getRolename(); assertEquals("Administrator", rolename); logger.info("getAllRolesTest success"); } /** * Add a role. Role id is auto generated. */ @Test public void addRoleTest() { logger.info("addRoleTest"); Role role = new Role(); role.setRolename("testRole"); int i = userInfoMapper.addRole(role); assertEquals(1, i); logger.info("addRoleTest success"); } /** * Find role by id and update role name. */ @Test public void updateRoleTest() { logger.info("updateRoleTest"); Role role = new Role(); role.setRoleid(6); role.setRolename("test"); userInfoMapper.deleteRole("6"); userInfoMapper.addRole(role); role.setRoleid(6); role.setRolename("testtestRole"); int i = userInfoMapper.updateRole(role); assertEquals(1, i); logger.info("updateRoleTest success"); } // /** // * Given group's information, add the group. // */ // @Test // public void addGroupIdTest() { // logger.info("addGroupIdTest"); // Group group = new Group(); // group.setManagerid(12); // group.setGroupname("testGroup"); // userInfoMapper.addGroupId(group); // logger.info("addGroupIdTest success"); // } /** * Delete a role by id. */ @Test public void deleteRoleTest() { logger.info("deleteRoleTest"); int i = userInfoMapper.deleteRole("6"); assertEquals(1, i); logger.info("deleteRoleTest success"); } /** * Find role name by id. */ @Test public void getRoleByIdTest() { logger.info("getRoleByIdTest"); Role roleById = userInfoMapper.getRoleById("1"); assertEquals("Administrator", roleById.getRolename()); logger.info("getRoleByIdTest success"); } }
28.740385
88
0.617431
888264d6b908aed0e13422ac4e1ae8ab2323bab1
8,321
package com.femto.post.activity; import java.util.HashMap; import org.apache.http.Header; import org.json.JSONObject; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.PlatformActionListener; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.sina.weibo.SinaWeibo; import cn.sharesdk.wechat.friends.Wechat; import com.android.futures.util.LogUtils; import com.femto.post.R; import com.femto.post.appfinal.AppUrl; import com.femto.post.application.MyApplication; import com.hyphenate.chat.EMClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.mob.tools.utils.UIHandler; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Handler.Callback; import android.os.Message; import android.text.ClipboardManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; public class Activity_Login extends BaseActivity implements Callback,PlatformActionListener { private static final int MSG_USERID_FOUND = 1; private static final int MSG_LOGIN = 2; private static final int MSG_AUTH_CANCEL = 3; private static final int MSG_AUTH_ERROR= 4; private static final int MSG_AUTH_COMPLETE = 5; private RelativeLayout rl_left; private TextView tv_title, tv_regist_login, tv_login, tv_forgetpd; private EditText ed_phone, ed_password; private RelativeLayout weChat_login; @Override public void onClick(View v) { switch (v.getId()) { case R.id.rl_left: finish(); break; case R.id.tv_regist_login: openActivity(Activity_Regist.class, null); break; case R.id.tv_login: Login(); break; case R.id.tv_forgetpd: openActivity(Activity_FindPassWord.class, null); break; case R.id.weChat_login: weChatLogin(); break; default: break; } } @Override public void initView() { rl_left = (RelativeLayout) findViewById(R.id.rl_left); tv_title = (TextView) findViewById(R.id.tv_title); tv_regist_login = (TextView) findViewById(R.id.tv_regist_login); tv_login = (TextView) findViewById(R.id.tv_login); tv_forgetpd = (TextView) findViewById(R.id.tv_forgetpd); ed_password = (EditText) findViewById(R.id.ed_password); ed_phone = (EditText) findViewById(R.id.ed_phone); weChat_login = (RelativeLayout)findViewById(R.id.weChat_login); weChat_login.setOnClickListener(this); } @Override public void initUtils() { } @Override public void Control() { // TODO Auto-generated method stub rl_left.setOnClickListener(this); tv_login.setOnClickListener(this); tv_forgetpd.setOnClickListener(this); tv_regist_login.setOnClickListener(this); tv_title.setText("登录"); } @Override public void setContentView() { ShareSDK.initSDK(this); setContentView(R.layout.activity_login); MyApplication.addActivity(this); } private void Login() { RequestParams params = new RequestParams(); String name = ed_phone.getText().toString().trim(); final String password = ed_password.getText().toString().trim(); if(TextUtils.isEmpty(name)||TextUtils.isEmpty(password)) { Toast.makeText(Activity_Login.this, "用户名或密码不能为空", 0).show(); return; } params.put("name", name); params.put("password", password); params.put("token", MyApplication.token); params.put("ios", 0); showProgressDialog("登录中"); MyApplication.ahc.post(AppUrl.useruserlogin, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); dismissProgressDialog(); LogUtils.i("response==="+response.toString()); String message = response.optString("message"); LogUtils.i("message==="+message); String result = response.optString("result"); if (result.equals("0")) { /****************************/ //int userId = response.optInt("userId"); String userId = response.optString("userId"); String userName = response.optString("userName"); String phone = response.optString("phone"); String url = response.optString("url"); String name = response.optString("name"); SharedPreferences sp = getSharedPreferences( "login", Context.MODE_PRIVATE); Editor edit = sp.edit(); //edit.putInt("userId", userId); edit.putString("userId", userId); edit.putString("userName", userName); edit.putString("phone", phone); edit.putString("name", name); edit.putString("url", url); edit.putBoolean("islogin", true); edit.putString("password",password); edit.commit(); MyApplication.getBasicInformation(); openActivity(MainActivity.class, null); finish(); } showToast("" + message, 0); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); dismissProgressDialog(); Toast.makeText(Activity_Login.this, "登录失败", Toast.LENGTH_SHORT).show(); } }); } //微信登录 private void weChatLogin() { Platform weChat = ShareSDK.getPlatform(this,Wechat.NAME); LogUtils.i("weChat==="+weChat.getName()); authorize(weChat); } @Override protected void onDestroy() { ShareSDK.stopSDK(this); super.onDestroy(); } /** * 微信登录相关 * @param plat */ private void authorize(Platform plat) { LogUtils.i("isValid==="+plat.isAuthValid()); if(plat.isAuthValid()) { LogUtils.i("palt==="+plat.getName()); String userId = plat.getDb().getUserId(); Log.i("test2", "userId"+userId); if (!TextUtils.isEmpty(userId)) { UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this); login(plat.getName(), userId, null); return; } } plat.setPlatformActionListener(this); plat.SSOSetting(true); plat.showUser(null); } private void login(String plat, String userId, HashMap<String, Object> userInfo) { LogUtils.i("login======="); Message msg = new Message(); msg.what = MSG_LOGIN; msg.obj = plat; UIHandler.sendMessage(msg, this); } public void onComplete(Platform platform, int action, HashMap<String, Object> res) { if (action == Platform.ACTION_USER_INFOR) { UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, this); login(platform.getName(), platform.getDb().getUserId(), res); } System.out.println(res); System.out.println("------User Name ---------" + platform.getDb().getUserName()); System.out.println("------User ID ---------" + platform.getDb().getUserId()); } public void onError(Platform platform, int action, Throwable t) { if (action == Platform.ACTION_USER_INFOR) { UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, this); } t.printStackTrace(); } public void onCancel(Platform platform, int action) { if (action == Platform.ACTION_USER_INFOR) { UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this); } } public boolean handleMessage(Message msg) { switch(msg.what) { case MSG_USERID_FOUND: { Toast.makeText(this, "用户信息已存在,正在执行跳转操作...", Toast.LENGTH_SHORT).show(); } break; case MSG_LOGIN: { // String text = getString("使用%s帐号登录中…", msg.obj); String text = "第三方账号登录中"; Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); System.out.println("---------------"); // Builder builder = new Builder(this); // builder.setTitle(R.string.if_register_needed); // builder.setMessage(R.string.after_auth); // builder.setPositiveButton(R.string.ok, null); // builder.create().show(); } break; case MSG_AUTH_CANCEL: { Toast.makeText(this, "授权取消", Toast.LENGTH_SHORT).show(); System.out.println("-------MSG_AUTH_CANCEL--------"); } break; case MSG_AUTH_ERROR: { Toast.makeText(this, "授权错误", Toast.LENGTH_SHORT).show(); System.out.println("-------MSG_AUTH_ERROR--------"); } break; case MSG_AUTH_COMPLETE: { Toast.makeText(this, "授权成功,正在跳转登录操作…", Toast.LENGTH_SHORT).show(); System.out.println("--------MSG_AUTH_COMPLETE-------"); } break; } return false; } }
30.818519
93
0.696431
e82363023f94f80a8e119a6e9e1706593e1cfa5a
831
package com.stylefeng.guns.modular.api.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(value ="省市区") public class ProvCityDistModel { private Integer id; @ApiModelProperty("地名") private String name; // @ApiModelProperty("0 省 1市区 2县") // private String type; // @ApiModelProperty("市") // private String city; // @ApiModelProperty("省id") // private Integer provinceId; // @ApiModelProperty("省") // private String district; // @ApiModelProperty("市id") // private Integer cityId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
20.775
47
0.636582
7db07709b73f12407941621fdd5da16971ed5110
3,602
package com.wjx.android.wanandroidmvp.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.blankj.utilcode.util.SPUtils; import com.wjx.android.wanandroidmvp.R; import com.wjx.android.wanandroidmvp.base.utils.Constant; import com.wjx.android.wanandroidmvp.base.utils.Utils; import com.wjx.android.wanandroidmvp.bean.base.Event; import com.wjx.android.wanandroidmvp.ui.activity.SearchResultActivity; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created with Android Studio. * Description: * * @author: Wangjianxian * @date: 2020/01/29 * Time: 12:06 */ public class SearchHistoryAdapter extends RecyclerView.Adapter<SearchHistoryAdapter.SearchHistoryHolder> { private Context mContext; private List<String> mSearchHistoryList = new ArrayList<>(); private boolean isNightMode; public SearchHistoryAdapter(Context context, List<String> searchHistoryList) { mContext = context; mSearchHistoryList.addAll(searchHistoryList); isNightMode = SPUtils.getInstance(Constant.CONFIG_SETTINGS). getBoolean(Constant.KEY_NIGHT_MODE, false); } public void setSearchHistoryList(List<String> searchHistoryList) { mSearchHistoryList.clear(); mSearchHistoryList.addAll(searchHistoryList); notifyDataSetChanged(); } @NonNull @Override public SearchHistoryHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.search_history_item, parent, false); return new SearchHistoryHolder(view); } @Override public void onBindViewHolder(@NonNull SearchHistoryHolder holder, int position) { holder.mHistoryText.setText(mSearchHistoryList.get(position)); holder.mHistoryDelete.setOnClickListener(v -> { Utils.deleteSearchHistory(mSearchHistoryList.get(position), mContext); Event event = new Event(); event.target = Event.TARGET_SEARCH; event.type = Event.TYPE_DELETE_SEARCH; event.data = position + ""; EventBus.getDefault().post(event); }); holder.itemView.setOnClickListener(v -> { Intent intent = new Intent(mContext, SearchResultActivity.class); intent.putExtra(Constant.KEY_KEYWORD, mSearchHistoryList.get(position)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); }); holder.mHistoryText.setTextColor(mContext.getColor(isNightMode ? R.color.card_bg : R.color.colorGray666)); holder.mHistoryDelete.setImageDrawable(mContext.getDrawable(isNightMode ? R.drawable.ic_delete_night : R.drawable.ic_delete)); } @Override public int getItemCount() { return mSearchHistoryList != null ? mSearchHistoryList.size() : 0; } class SearchHistoryHolder extends RecyclerView.ViewHolder { @BindView(R.id.item_history_text) TextView mHistoryText; @BindView(R.id.item_history_delete) ImageView mHistoryDelete; public SearchHistoryHolder(@NonNull View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
34.634615
134
0.722376
cfe19c2a578b234d78d22491aff8cb161643974a
567
package ExerciciosAula14e15; import java.util.Scanner; public class Exercicio2 { public static void main (String[] args){ Scanner scan = new Scanner (System.in); System.out.println("Digite um número: "); double num1 = scan.nextDouble(); if(num1 > 0){ System.out.println("O número digitado é positivo!"); } else if (num1 < 0){ System.out.println("O número digitado é negativo!"); }else{ System.out.println("O número digitado não é positivo e não é negativo!"); } } }
33.352941
85
0.597884
7195484069b0346437e114aae12a270ee62a5bd5
1,106
package com.shiva.jenkvExamples; import java.io.FileNotFoundException; import java.io.FileOutputStream; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfWriter; public class ChunkExample { public static void main(String[] args) { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream("Chunk.pdf")); document.open(); document.add(new Chunk("This is sentence 1. ")); document.add(new Chunk("This is sentence 2. ")); document.add(new Chunk("This is sentence 3. ")); document.add(new Chunk("This is sentence 4. ")); document.add(new Chunk("This is sentence 5. ")); document.add(new Chunk("This is sentence 6. ")); document.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
28.358974
61
0.600362
dbbfc5744ceba1372f43c55c12bd4baa1d4ee53c
4,359
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.area; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.xmlgraphics.util.QName; import org.apache.fop.fo.extensions.ExtensionAttachment; /** * Abstract base class for all area tree objects. */ public abstract class AreaTreeObject { /** Foreign attributes */ protected Map<QName, String> foreignAttributes = null; /** Extension attachments */ protected List<ExtensionAttachment> extensionAttachments = null; /** * Sets a foreign attribute. * @param name the qualified name of the attribute * @param value the attribute value */ public void setForeignAttribute(QName name, String value) { if (this.foreignAttributes == null) { this.foreignAttributes = new java.util.HashMap<QName, String>(); } this.foreignAttributes.put(name, value); } /** * Add foreign attributes from a Map. * * @param atts a Map with attributes (keys: QName, values: String) */ public void setForeignAttributes(Map<QName, String> atts) { if (atts == null || atts.size() == 0) { return; } for (Map.Entry<QName, String> e : atts.entrySet()) { setForeignAttribute(e.getKey(), e.getValue()); } } /** * Returns the value of a foreign attribute on the area. * @param name the qualified name of the attribute * @return the attribute value or null if it isn't set */ public String getForeignAttributeValue(QName name) { if (this.foreignAttributes != null) { return this.foreignAttributes.get(name); } else { return null; } } /** @return the foreign attributes associated with this area */ public Map<QName, String> getForeignAttributes() { if (this.foreignAttributes != null) { return Collections.unmodifiableMap(this.foreignAttributes); } else { return Collections.emptyMap(); } } private void prepareExtensionAttachmentContainer() { if (this.extensionAttachments == null) { this.extensionAttachments = new java.util.ArrayList<ExtensionAttachment>(); } } /** * Adds a new ExtensionAttachment instance to this page. * @param attachment the ExtensionAttachment */ public void addExtensionAttachment(ExtensionAttachment attachment) { prepareExtensionAttachmentContainer(); extensionAttachments.add(attachment); } /** * Set extension attachments from a List * @param extensionAttachments a List with extension attachments */ public void setExtensionAttachments(List<ExtensionAttachment> extensionAttachments) { prepareExtensionAttachmentContainer(); this.extensionAttachments.addAll(extensionAttachments); } /** @return the extension attachments associated with this area */ public List<ExtensionAttachment> getExtensionAttachments() { if (this.extensionAttachments != null) { return Collections.unmodifiableList(this.extensionAttachments); } else { return Collections.emptyList(); } } /** * Indicates whether this area tree object has any extension attachments. * @return true if there are extension attachments */ public boolean hasExtensionAttachments() { return this.extensionAttachments != null && !this.extensionAttachments.isEmpty(); } }
33.022727
89
0.671714
5ad9231bc391677a2299c66c9df7aad061deaea0
14,260
package net.earthcomputer.easyeditors.gui.command; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import net.earthcomputer.easyeditors.gui.GuiSelectEntity; import net.earthcomputer.easyeditors.gui.GuiSelectFromList; import net.earthcomputer.easyeditors.gui.ICallback; import net.earthcomputer.easyeditors.gui.IEntitySelectorCallback; import net.earthcomputer.easyeditors.util.Translate; import net.earthcomputer.easyeditors.util.TranslateKeys; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityList.EntityEggInfo; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.stats.AchievementList; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextComponentTranslation; import net.minecraftforge.fml.common.registry.ForgeRegistries; public class GuiSelectStat extends GuiSelectFromList<StatBase> { private static List<StatBase> createStatsList(boolean includeAchievements) { List<StatBase> stats = Lists.newArrayListWithExpectedSize( StatList.BASIC_STATS.size() + (includeAchievements ? AchievementList.ACHIEVEMENTS.size() : 0)); stats.addAll(StatList.BASIC_STATS); stats.add(new StatBase("stat.craftItem", new TextComponentTranslation(TranslateKeys.GUI_COMMANDEDITOR_SELECTSTAT_CRAFTITEM))); stats.add(new StatBase("stat.mineBlock", new TextComponentTranslation(TranslateKeys.GUI_COMMANDEDITOR_SELECTSTAT_MINEBLOCK))); stats.add(new StatBase("stat.useItem", new TextComponentTranslation(TranslateKeys.GUI_COMMANDEDITOR_SELECTSTAT_USEITEM))); stats.add(new StatBase("stat.breakItem", new TextComponentTranslation(TranslateKeys.GUI_COMMANDEDITOR_SELECTSTAT_BREAKITEM))); stats.add(new StatBase("stat.pickup", new TextComponentTranslation(TranslateKeys.GUI_COMMANDEDITOR_SELECTSTAT_PICKUP))); stats.add(new StatBase("stat.drop", new TextComponentTranslation(TranslateKeys.GUI_COMMANDEDITOR_SELECTSTAT_DROP))); stats.add(new StatBase("stat.killEntity", new TextComponentTranslation(TranslateKeys.GUI_COMMANDEDITOR_SELECTSTAT_KILLENTITY))); stats.add(new StatBase("stat.entityKilledBy", new TextComponentTranslation(TranslateKeys.GUI_COMMANDEDITOR_SELECTSTAT_ENTITYKILLEDBY))); if (includeAchievements) { stats.addAll(AchievementList.ACHIEVEMENTS); } return stats; } private Block parameterBlock; private Item parameterItem; private ResourceLocation parameterEntity; private GuiButton selectParameterButton; public GuiSelectStat(GuiScreen prevScreen, ICallback<StatBase> callback, boolean includeAchievements) { super(prevScreen, callback, createStatsList(includeAchievements), Translate.GUI_COMMANDEDITOR_SELECTSTAT_TITLE); setFooterHeight(55); if (requiresParameterBlock()) { StatBase lookingFor = callback.getCallbackValue(); for (Block block : ForgeRegistries.BLOCKS) { if (lookingFor.equals(StatList.getBlockStats(block))) { parameterBlock = block; break; } } } else if (requiresParameterItem()) { StatBase lookingFor = callback.getCallbackValue(); String lookingForId = lookingFor.statId; if (lookingForId.startsWith("stat.craftItem.")) { for (Item item : ForgeRegistries.ITEMS) { if (lookingFor.equals(StatList.getCraftStats(item))) { parameterItem = item; break; } } } else if (lookingForId.startsWith("stat.useItem.")) { for (Item item : ForgeRegistries.ITEMS) { if (lookingFor.equals(StatList.getObjectUseStats(item))) { parameterItem = item; break; } } } else if (lookingForId.startsWith("stat.breakItem.")) { for (Item item : ForgeRegistries.ITEMS) { if (lookingFor.equals(StatList.getObjectBreakStats(item))) { parameterItem = item; break; } } } else if (lookingForId.startsWith("stat.pickup.")) { for (Item item : ForgeRegistries.ITEMS) { if (lookingFor.equals(StatList.getObjectsPickedUpStats(item))) { parameterItem = item; break; } } } else if (lookingForId.startsWith("stat.drop.")) { for (Item item : ForgeRegistries.ITEMS) { if (lookingFor.equals(StatList.getDroppedObjectStats(item))) { parameterItem = item; break; } } } else { throw new AssertionError(); } } else if (requiresParameterEntity()) { String statId = callback.getCallbackValue().statId; String entityName; if (statId.startsWith("stat.killEntity.")) { entityName = statId.substring(16); } else { entityName = statId.substring(20); } ResourceLocation entityLocation = null; EntityEggInfo eggInfo = null; for (Map.Entry<ResourceLocation, EntityEggInfo> candidate : EntityList.ENTITY_EGGS.entrySet()) { if (entityName.equals(EntityList.getTranslationName(candidate.getKey()))) { entityLocation = candidate.getKey(); eggInfo = candidate.getValue(); break; } } if (entityLocation != null) { if (statId.startsWith("stat.killEntity.")) { if (eggInfo.killEntityStat != null) { parameterEntity = entityLocation; } } else { if (eggInfo.entityKilledByStat != null) { parameterEntity = entityLocation; } } } } } @Override protected List<String> getTooltip(StatBase value) { return Collections.emptyList(); } @Override protected void drawSlot(int y, StatBase value) { String str = value.getStatName().getFormattedText(); fontRendererObj.drawString(str, width / 2 - fontRendererObj.getStringWidth(str) / 2, y + 2, 0xffffff); str = value.statId; fontRendererObj.drawString(str, width / 2 - fontRendererObj.getStringWidth(str) / 2, y + 4 + fontRendererObj.FONT_HEIGHT, 0xc0c0c0); } @Override protected boolean doesSearchTextMatch(String searchText, StatBase value) { if (value.getStatName().getUnformattedText().toLowerCase().contains(searchText)) { return true; } if (value.statId.toLowerCase().contains(searchText)) { return true; } return false; } private boolean requiresParameterBlock() { return getSelectedValue().statId.equals("stat.mineBlock"); } private static final Set<String> REQUIRE_PARAM_ITEM = ImmutableSet.of("stat.craftItem", "stat.useItem", "stat.breakItem", "stat.pickup", "stat.drop"); private boolean requiresParameterItem() { return REQUIRE_PARAM_ITEM.contains(getSelectedValue().statId); } private boolean requiresParameterEntity() { String statId = getSelectedValue().statId; return "stat.killEntity".equals(statId) || "stat.entityKilledBy".equals(statId); } private boolean requiresParameter() { return requiresParameterBlock() || requiresParameterItem() || requiresParameterEntity(); } @Override public void initGui() { super.initGui(); selectParameterButton = addButton(new GuiButton(2, width - 30, height - 47, 20, 20, "...")); selectParameterButton.visible = requiresParameter(); } @Override public void drawForeground(int mouseX, int mouseY, float partialTicks) { super.drawForeground(mouseX, mouseY, partialTicks); if (requiresParameter()) { selectParameterButton.visible = true; String str; if (requiresParameterBlock()) { if (parameterBlock == null) { getDoneButton().enabled = false; str = Translate.GUI_COMMANDEDITOR_NOBLOCK; } else { getDoneButton().enabled = true; str = GuiSelectBlock.getDisplayName(parameterBlock.getDefaultState()); } } else if (requiresParameterItem()) { if (parameterItem == null) { getDoneButton().enabled = false; str = Translate.GUI_COMMANDEDITOR_NOITEM; } else { getDoneButton().enabled = true; str = I18n.format(parameterItem.getUnlocalizedName() + ".name"); } } else { if (parameterEntity == null) { getDoneButton().enabled = false; str = Translate.GUI_COMMANDEDITOR_NOENTITY; } else { getDoneButton().enabled = true; str = GuiSelectEntity.getEntityName(parameterEntity); } } fontRendererObj.drawString(str, width / 2 - fontRendererObj.getStringWidth(str) / 2, height - 44, 0xffffff); } else { selectParameterButton.visible = false; } } @Override public void actionPerformed(GuiButton button) throws IOException { if (button.id == 2) { if (requiresParameterBlock()) { mc.displayGuiScreen(new GuiSelectBlock(this, new ICallback<IBlockState>() { @Override public IBlockState getCallbackValue() { return parameterBlock == null ? null : parameterBlock.getDefaultState(); } @Override public void setCallbackValue(IBlockState value) { parameterBlock = value.getBlock(); } }, false, new Predicate<IBlockState>() { @Override public boolean apply(IBlockState state) { Block block = state.getBlock(); StatBase mineBlockStat = StatList.getBlockStats(block); if (mineBlockStat == null) { return false; } String expectedStatId = "stat.mineBlock." + Item.getItemFromBlock(block).delegate.name().toString().replace(':', '.'); String actualStatId = mineBlockStat.statId; return expectedStatId.equals(actualStatId); } })); } else if (requiresParameterItem()) { Predicate<ItemStack> predicate; String statId = getSelectedValue().statId; if ("stat.pickup".equals(statId) || "stat.drop".equals(statId)) { predicate = Predicates.alwaysTrue(); } else if ("stat.useItem".equals(statId)) { predicate = new Predicate<ItemStack>() { @Override public boolean apply(ItemStack stack) { Item item = stack.getItem(); StatBase useItemStat = StatList.getObjectUseStats(item); if (useItemStat == null) { return false; } String expectedStatId = "stat.useItem." + item.delegate.name().toString().replace(':', '.'); String actualStatId = useItemStat.statId; return expectedStatId.equals(actualStatId); } }; } else if ("stat.breakItem".equals(statId)) { predicate = new Predicate<ItemStack>() { @Override public boolean apply(ItemStack stack) { Item item = stack.getItem(); StatBase breakItemStat = StatList.getObjectBreakStats(item); if (breakItemStat == null) { return false; } String expectedStatId = "stat.breakItem." + item.delegate.name().toString().replace(':', '.'); String actualStatId = breakItemStat.statId; return expectedStatId.equals(actualStatId); } }; } else if ("stat.craftItem".equals(statId)) { predicate = new Predicate<ItemStack>() { @Override public boolean apply(ItemStack stack) { Item item = stack.getItem(); StatBase craftStat = StatList.getCraftStats(item); if (craftStat == null) { return false; } String expectedStatId = "stat.craftItem." + item.delegate.name().toString().replace(':', '.'); String actualStatId = craftStat.statId; return expectedStatId.equals(actualStatId); } }; } else { throw new AssertionError(); } mc.displayGuiScreen(new GuiSelectItem(this, new ICallback<ItemStack>() { @Override public ItemStack getCallbackValue() { return parameterItem == null ? ItemStack.EMPTY : new ItemStack(parameterItem); } @Override public void setCallbackValue(ItemStack value) { parameterItem = value.getItem(); } }, false, predicate)); } else if (requiresParameterEntity()) { mc.displayGuiScreen(new GuiSelectEntity(this, new IEntitySelectorCallback() { @Override public ResourceLocation getEntity() { return parameterEntity; } @Override public void setEntity(ResourceLocation entityName) { parameterEntity = entityName; } }, false, false, Predicates.and(Predicates.in(EntityList.ENTITY_EGGS.keySet()), new Predicate<ResourceLocation>() { @Override public boolean apply(ResourceLocation input) { return EntityList.ENTITY_EGGS.get(input).killEntityStat != null; } }))); } } else { super.actionPerformed(button); } } @Override protected StatBase getOverrideCallbackValue(StatBase originalValue) { if (requiresParameterBlock()) { return StatList.getBlockStats(parameterBlock); } else if (requiresParameterItem()) { String statId = originalValue.statId; if ("stat.pickup".equals(statId)) { return StatList.getObjectsPickedUpStats(parameterItem); } else if ("stat.drop".equals(statId)) { return StatList.getDroppedObjectStats(parameterItem); } else if ("stat.useItem".equals(statId)) { return StatList.getObjectUseStats(parameterItem); } else if ("stat.breakItem".equals(statId)) { return StatList.getObjectBreakStats(parameterItem); } else if ("stat.craftItem".equals(statId)) { return StatList.getCraftStats(parameterItem); } else { throw new AssertionError(); } } else if (requiresParameterEntity()) { EntityEggInfo eggInfo = EntityList.ENTITY_EGGS.get(parameterEntity); if ("stat.killEntity".equals(originalValue.statId)) { return eggInfo.killEntityStat; } else { return eggInfo.entityKilledByStat; } } else { return originalValue; } } private static final Set<String> WILDCARDS = ImmutableSet.of("stat.mineBlock", "stat.craftItem", "stat.useItem", "stat.breakItem", "stat.pickup", "stat.drop", "stat.killEntity", "stat.entityKilledBy"); @Override protected boolean areEqual(StatBase a, StatBase b) { String aid = a.statId, bid = b.statId; if (aid.equals(bid)) { return true; } if (WILDCARDS.contains(aid)) { if (bid.startsWith(aid + ".")) { return true; } } if (WILDCARDS.contains(bid)) { if (aid.startsWith(bid + ".")) { return true; } } return false; } }
34.695864
114
0.706241
63ba9daedf7ce5a5a4e862e2cb0af4e4ff5b1f27
749
package org.opendatakit.submit.ui.common; import android.app.Application; import androidx.lifecycle.AndroidViewModel; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.opendatakit.application.CommonApplication; import org.opendatakit.database.service.UserDbInterface; public class AppAwareViewModel extends AndroidViewModel { private String appName; public String getAppName() { return appName; } public void setAppName(@NonNull String appName) { this.appName = appName; } @Nullable public UserDbInterface getDatabase() { return this.<CommonApplication>getApplication().getDatabase(); } public AppAwareViewModel(@NonNull Application application) { super(application); } }
24.16129
66
0.782377
461778b5a98f22f67968c720bd2aa7bfcfd6d508
1,627
package org.robobinding.widget.imageview; import org.robobinding.util.PrimitiveTypeUtils; import org.robobinding.viewattribute.property.MultiTypePropertyViewAttribute; import org.robobinding.viewattribute.property.PropertyViewAttribute; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.ImageView; /** * * @since 1.0 * @version $Revision: 1.0 $ * @author Robert Taylor */ public class ImageSourceAttribute implements MultiTypePropertyViewAttribute<ImageView> { @Override public PropertyViewAttribute<ImageView, ?> create(ImageView view, Class<?> propertyType) { if (PrimitiveTypeUtils.integerIsAssignableFrom(propertyType)) { return new IntegerImageSourceAttribute(); } else if (Drawable.class.isAssignableFrom(propertyType)) { return new DrawableImageSourceAttribute(); } else if (Bitmap.class.isAssignableFrom(propertyType)) { return new BitmapImageSourceAttribute(); } return null; } static class IntegerImageSourceAttribute implements PropertyViewAttribute<ImageView, Integer> { @Override public void updateView(ImageView view, Integer newResourceId) { view.setImageResource(newResourceId); } } static class DrawableImageSourceAttribute implements PropertyViewAttribute<ImageView, Drawable> { @Override public void updateView(ImageView view, Drawable newDrawable) { view.setImageDrawable(newDrawable); } } static class BitmapImageSourceAttribute implements PropertyViewAttribute<ImageView, Bitmap> { @Override public void updateView(ImageView view, Bitmap newBitmap) { view.setImageBitmap(newBitmap); } } }
30.698113
98
0.794714
d5b31a78b572f845675524bb546a330cb11542ec
28,765
/******************************************************************************* * Copyright 2011 Antti Havanko * * This file is part of Motiver.fi. * Motiver.fi is licensed under one open source license and one commercial license. * * Commercial license: This is the appropriate option if you want to use Motiver.fi in * commercial purposes. Contact [email protected] for licensing options. * * Open source license: This is the appropriate option if you are creating an open source * application with a license compatible with the GNU GPL license v3. Although the GPLv3 has * many terms, the most important is that you must provide the source code of your application * to your users so they can be free to modify your application for their own needs. ******************************************************************************/ package com.delect.motiver.client.presenter; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.SimpleEventBus; import com.google.gwt.http.client.Request; import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.RootPanel; import com.delect.motiver.client.AppController; import com.delect.motiver.client.Motiver; import com.delect.motiver.client.MyAsyncCallback; import com.delect.motiver.client.event.BlogShowEvent; import com.delect.motiver.client.event.CardioShowEvent; import com.delect.motiver.client.event.CoachModeEvent; import com.delect.motiver.client.event.CommentNewEvent; import com.delect.motiver.client.event.InfoMessageEvent; import com.delect.motiver.client.event.LoadingEvent; import com.delect.motiver.client.event.MeasurementShowEvent; import com.delect.motiver.client.event.NutritionDayShowEvent; import com.delect.motiver.client.event.OfflineModeEvent; import com.delect.motiver.client.event.RunShowEvent; import com.delect.motiver.client.event.ShortcutKeyEvent; import com.delect.motiver.client.event.TabEvent; import com.delect.motiver.client.event.WorkoutShowEvent; import com.delect.motiver.client.event.handler.BlogShowEventHandler; import com.delect.motiver.client.event.handler.CardioShowEventHandler; import com.delect.motiver.client.event.handler.CoachModeEventHandler; import com.delect.motiver.client.event.handler.InfoMessageEventHandler; import com.delect.motiver.client.event.handler.LoadingEventHandler; import com.delect.motiver.client.event.handler.MeasurementShowEventHandler; import com.delect.motiver.client.event.handler.NutritionDayShowEventHandler; import com.delect.motiver.client.event.handler.OfflineModeEventHandler; import com.delect.motiver.client.event.handler.RunShowEventHandler; import com.delect.motiver.client.event.handler.ShortcutKeyEventHandler; import com.delect.motiver.client.event.handler.TabEventHandler; import com.delect.motiver.client.event.handler.WorkoutShowEventHandler; import com.delect.motiver.client.presenter.ConfirmDialogPresenter.ConfirmDialogDisplay; import com.delect.motiver.client.presenter.HeaderPresenter.HeaderDisplay; import com.delect.motiver.client.presenter.HeaderPresenter.HeaderTarget; import com.delect.motiver.client.presenter.InfoMessagePresenter.InfoMessageDisplay; import com.delect.motiver.client.presenter.InfoMessagePresenter.MessageColor; import com.delect.motiver.client.presenter.LoadingPresenter.LoadingDisplay; import com.delect.motiver.client.presenter.MainPagePresenter.MainPageDisplay; import com.delect.motiver.client.presenter.ShortcutKeysPresenter.ShortcutKeysDisplay; import com.delect.motiver.client.presenter.admin.AdminPagePresenter; import com.delect.motiver.client.presenter.admin.AdminPagePresenter.AdminPageDisplay; import com.delect.motiver.client.presenter.cardio.CardioPagePresenter; import com.delect.motiver.client.presenter.cardio.CardioPagePresenter.CardioPageDisplay; import com.delect.motiver.client.presenter.coach.CoachModeIndicatorPresenter; import com.delect.motiver.client.presenter.coach.CoachModeIndicatorPresenter.CoachModeIndicatorDisplay; import com.delect.motiver.client.presenter.coach.CoachPagePresenter; import com.delect.motiver.client.presenter.coach.CoachPagePresenter.CoachPageDisplay; import com.delect.motiver.client.presenter.guide.BeginnersGuidePresenter; import com.delect.motiver.client.presenter.guide.BeginnersGuidePresenter.BeginnersGuideDisplay; import com.delect.motiver.client.presenter.nutrition.NutritionPagePresenter; import com.delect.motiver.client.presenter.nutrition.NutritionPagePresenter.NutritionPageDisplay; import com.delect.motiver.client.presenter.profile.ProfilePagePresenter; import com.delect.motiver.client.presenter.profile.ProfilePagePresenter.ProfilePageDisplay; import com.delect.motiver.client.presenter.statistics.StatisticsPagePresenter; import com.delect.motiver.client.presenter.statistics.StatisticsPagePresenter.StatisticsPageDisplay; import com.delect.motiver.client.presenter.training.TrainingPagePresenter; import com.delect.motiver.client.presenter.training.TrainingPagePresenter.TrainingPageDisplay; import com.delect.motiver.client.service.MyServiceAsync; import com.delect.motiver.client.view.ConfirmDialogView; import com.delect.motiver.client.view.Display; import com.delect.motiver.client.view.HeaderView; import com.delect.motiver.client.view.InfoMessageView; import com.delect.motiver.client.view.LoadingView; import com.delect.motiver.client.view.MainPageView; import com.delect.motiver.client.view.ShortcutKeysView; import com.delect.motiver.client.view.admin.AdminPageView; import com.delect.motiver.client.view.cardio.CardioPageView; import com.delect.motiver.client.view.coach.CoachModeIndicatorView; import com.delect.motiver.client.view.coach.CoachPageView; import com.delect.motiver.client.view.guide.BeginnersGuideView; import com.delect.motiver.client.view.nutrition.NutritionPageView; import com.delect.motiver.client.view.profile.ProfilePageView; import com.delect.motiver.client.view.statistics.StatisticsPageView; import com.delect.motiver.client.view.training.TrainingPageView; import com.delect.motiver.shared.CommentModel; import com.delect.motiver.shared.Constants; import com.delect.motiver.shared.TicketModel; import com.delect.motiver.shared.util.CommonUtils; import com.extjs.gxt.ui.client.widget.LayoutContainer; /** User index view. Is shown when user is logged in. */ public class UserIndexPresenter extends Presenter implements ValueChangeHandler<String> { /** * Abstract class for view to extend */ public abstract static class UserIndexDisplay extends Display { /** * Returns container for body. * @return LayoutContainer */ public abstract LayoutContainer getBodyContainer(); /** * Returns container for footer. * @return LayoutContainer */ public abstract LayoutContainer getFooterContainer(); /** * Returns container for header. * @return LayoutContainer */ public abstract LayoutContainer getHeaderContainer(); /** * Returns container for messages. * @return LayoutContainer */ public abstract LayoutContainer getMessageContainer(); /** * Sets handler for view to call. * @param handler UserIndexHandler */ public abstract void setHandler(UserIndexHandler handler); /** * Shows/hides 'print view' link. * @param visible boolean */ public abstract void setPrintLinkVisibility(boolean visible); /** * Shows/hides loading text. * @param enabled boolean */ public abstract void showLoading(boolean enabled); } /** Handler for this presenter. */ public interface UserIndexHandler { /** * Called when new ticked is written. * @param ticket TicketModel */ void newTicket(TicketModel ticket); /** * Called when print view link is clicked. */ void printPage(); } private CoachModeIndicatorPresenter coachModeIndicatorPresenter; private int connection_count = 0; private UserIndexDisplay display; private HeaderPresenter headerUserPresenter; private InfoMessagePresenter infoMessageOfflineMode; private List<InfoMessagePresenter> infoMessagePresenters = new ArrayList<InfoMessagePresenter>(); private LoadingPresenter loadingPresenter; private Presenter pagePresenter; private ShortcutKeysPresenter shortcutKeysPresenter; private BeginnersGuidePresenter beginnersGuidePresenter; private Timer timer; private Timer timerReload; protected ConfirmDialogPresenter dialog; /** * Constructor for UserIndexPresenter. * @param rpcService MyServiceAsync * @param eventBus SimpleEventBus * @param display UserIndexDisplay */ public UserIndexPresenter(MyServiceAsync rpcService, SimpleEventBus eventBus, UserIndexDisplay display) { super(rpcService, eventBus); this.display = display; //containers headerUserPresenter = new HeaderPresenter(rpcService, eventBus, (HeaderDisplay)GWT.create(HeaderView.class), HeaderTarget.USER, 0); shortcutKeysPresenter = new ShortcutKeysPresenter(rpcService, eventBus, (ShortcutKeysDisplay)GWT.create(ShortcutKeysView.class)); } @Override public Display getView() { return display; } @Override public void onBind() { History.addValueChangeHandler(this); display.setHandler(new UserIndexHandler() { @SuppressWarnings("unchecked") @Override public void newTicket(TicketModel ticket) { rpcService.addTicket(ticket, MyAsyncCallback.EmptyCallback); //show "thank you" dialog if(dialog != null) dialog.stop(); dialog = new ConfirmDialogPresenter(rpcService, eventBus, (ConfirmDialogDisplay)GWT.create(ConfirmDialogView.class), AppController.Lang.ThankYou(), AppController.Lang.ThankYouForReporting()); dialog.run(display.getBaseContainer()); } @Override public void printPage() { Window.open(Constants.URL_APP + "print/#" + History.getToken(), "_blank", "status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1"); } }); //tab change handler addEventHandler(TabEvent.TYPE, new TabEventHandler() { @Override public void onTabChanged(TabEvent event) { //set new history token switch(event.getIndex()) { case 0: History.newItem("user"); break; case 1: History.newItem("user/training"); break; case 2: History.newItem("user/nutrition"); break; case 3: History.newItem("user/cardio"); break; case 4: History.newItem("user/statistics"); break; case 5: History.newItem("user/profile"); break; case 6: History.newItem("user/coach"); break; case 7: History.newItem("user/admin"); break; default: History.newItem("user"); break; } //reset reload timer setPageReloadTimer(); } }); //EVENT: connection error addEventHandler(InfoMessageEvent.TYPE, new InfoMessageEventHandler() { @Override public void onInfoMessage(InfoMessageEvent event) { final InfoMessagePresenter infoMessagePresenter = new InfoMessagePresenter(rpcService, eventBus, (InfoMessageDisplay)GWT.create(InfoMessageView.class), event.getMessageColor(), event.getMessage(), event.getClickListener()); infoMessagePresenter.run(display.getMessageContainer()); infoMessagePresenters.add(infoMessagePresenter); } }); //EVENT: offline mode addEventHandler(OfflineModeEvent.TYPE, new OfflineModeEventHandler() { @Override public void onModeChange(OfflineModeEvent event) { if(infoMessageOfflineMode != null) { infoMessageOfflineMode.stop(); } //if mode is on if(event.isOn()) { infoMessageOfflineMode = new InfoMessagePresenter(rpcService, eventBus, (InfoMessageDisplay)GWT.create(InfoMessageView.class), MessageColor.COLOR_BLUE, AppController.Lang.OfflineModeIsOn(), null); infoMessageOfflineMode.run(display.getMessageContainer()); } } }); //EVENT: blog show addEventHandler(BlogShowEvent.TYPE, new BlogShowEventHandler() { @Override public void onBlogShow(BlogShowEvent event) { //open blog in new window Window.open(event.getUser().getBlogUrl(), "_blank", "status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1,scrollbars=1"); } }); //EVENT: show workout addEventHandler(WorkoutShowEvent.TYPE, new WorkoutShowEventHandler() { @Override public void selectWorkout(WorkoutShowEvent event) { if(event.getWorkout().getDate() != null) { Date d = event.getWorkout().getDate(); d = CommonUtils.getDateGmt(d); //open correct day History.newItem("user/training/" + (d.getTime() / 1000)); } } }); //EVENT: show day (nutrition) addEventHandler(NutritionDayShowEvent.TYPE, new NutritionDayShowEventHandler() { @Override public void selectNutritionDay(NutritionDayShowEvent event) { if(event.getNutritionDay().getDate() != null) { final Date d = event.getNutritionDay().getDate(); //open correct day History.newItem("user/nutrition/" + (d.getTime() / 1000)); } } }); //EVENT: show cardio addEventHandler(CardioShowEvent.TYPE, new CardioShowEventHandler() { @Override public void onCardioShow(CardioShowEvent event) { //open correct day History.newItem("user/cardio/c" + event.getCardio().getId()); } }); //EVENT: show run addEventHandler(RunShowEvent.TYPE, new RunShowEventHandler() { @Override public void onRunShow(RunShowEvent event) { //open correct day History.newItem("user/cardio/r" + event.getRun().getId()); } }); //EVENT: show measurement addEventHandler(MeasurementShowEvent.TYPE, new MeasurementShowEventHandler() { @Override public void onMeasurementShow(MeasurementShowEvent event) { //open correct day History.newItem("user/profile/m" + event.getMeasurement().getId()); } }); //EVENT: loading text addEventHandler(LoadingEvent.TYPE, new LoadingEventHandler() { @Override public void onLoading(LoadingEvent event) { if(event.getMessage() != null) { //if first connection -> fire event if(connection_count == 0) { if(loadingPresenter != null) { loadingPresenter.stop(); } //show loading text loadingPresenter = new LoadingPresenter(rpcService, eventBus, (LoadingDisplay)GWT.create(LoadingView.class), event.getMessage()); loadingPresenter.run(display.getBaseContainer()); } connection_count++; } //cancelled loading event else { //reduce connection count if(connection_count > 0) { connection_count--; } //if no connections left -> stop if(connection_count == 0 && loadingPresenter != null) { loadingPresenter.stop(); } } } }); //EVENT: coach mode on addEventHandler(CoachModeEvent.TYPE, new CoachModeEventHandler() { @Override public void onCoachModeOn(CoachModeEvent event) { //coach mode started if(event.getUser() != null) { //set variables AppController.UserLast = AppController.User; AppController.User = event.getUser(); AppController.COACH_MODE_UID = event.getUser().getUid(); AppController.COACH_MODE_ON = true; //show indicator if(coachModeIndicatorPresenter != null) { coachModeIndicatorPresenter.stop(); } coachModeIndicatorPresenter = new CoachModeIndicatorPresenter(rpcService, eventBus, (CoachModeIndicatorDisplay)GWT.create(CoachModeIndicatorView.class), event.getUser()); coachModeIndicatorPresenter.run(display.getBaseContainer()); } //coach mode ended else { //set variables AppController.User = AppController.UserLast; AppController.COACH_MODE_UID = null; AppController.COACH_MODE_ON = false; } //restart header and menu headerUserPresenter.stop(); pagePresenter.stop(); pagePresenter = null; headerUserPresenter = new HeaderPresenter(rpcService, eventBus, (HeaderDisplay)GWT.create(HeaderView.class), HeaderTarget.USER, 0); headerUserPresenter.run(display.getHeaderContainer()); //fire main view if(event.getUser() != null) { History.newItem("user", true); } else { History.fireCurrentHistoryState(); } } }); //EVENT: shortcut key addEventHandler(ShortcutKeyEvent.TYPE, new ShortcutKeyEventHandler() { @Override public void onShortcutKey(ShortcutKeyEvent event) { if(event.getKey() == 83) { showBeginnerTutorial(); } } }); if(History.getToken().length() == 0) { History.newItem("user", false); } } protected void showBeginnerTutorial() { if(beginnersGuidePresenter != null) beginnersGuidePresenter.stop(); beginnersGuidePresenter = new BeginnersGuidePresenter(rpcService, eventBus, (BeginnersGuideDisplay)GWT.create(BeginnersGuideView.class)); beginnersGuidePresenter.run(display.getMessageContainer()); } @Override public void onRun() { display.showLoading(true); //header headerUserPresenter.run(display.getHeaderContainer()); shortcutKeysPresenter.run(display.getMessageContainer()); History.fireCurrentHistoryState(); //reload page each xx hours setPageReloadTimer(); //show tutorial if not already shown if(!AppController.User.isTutorialShowed()) { showBeginnerTutorial(); //save user AppController.User.setTutorialShowed(true); rpcService.saveUserData(AppController.User, MyAsyncCallback.EmptyCallback); } } @Override public void onStop() { if(timer != null) { timer.cancel(); } if(timerReload != null) { timerReload.cancel(); } if(loadingPresenter != null) { loadingPresenter.stop(); } if(infoMessageOfflineMode != null) { infoMessageOfflineMode.stop(); } if(coachModeIndicatorPresenter != null) { coachModeIndicatorPresenter.stop(); } if(shortcutKeysPresenter != null) { shortcutKeysPresenter.stop(); } if(headerUserPresenter != null) { headerUserPresenter.stop(); } if(pagePresenter != null) { pagePresenter.stop(); } if(dialog != null) dialog.stop(); if(infoMessagePresenters != null) { for(InfoMessagePresenter p : infoMessagePresenters) { if(p != null) { p.stop(); } } infoMessagePresenters.clear(); } } /** * Called when url token changes. * @param event ValueChangeEvent<String> * @see com.google.gwt.event.logical.shared.ValueChangeHandler#onValueChange(ValueChangeEvent<String>) */ @Override public void onValueChange(ValueChangeEvent<String> event) { final String token = event.getValue(); //remove page styles RootPanel.get().removeStyleName("page-training"); RootPanel.get().removeStyleName("page-nutrition"); RootPanel.get().removeStyleName("page-cardio"); RootPanel.get().removeStyleName("page-profile"); //hide print page link display.setPrintLinkVisibility(false); if (token != null) { try { //training if (token.contains("user/training")) { //page style RootPanel.get().addStyleName("page-training"); //page title Window.setTitle("Motiver - " + AppController.Lang.Training()); //analytics trackHit("training"); Date d = null; try { //check date if(token.matches("user/training/[0-9]*(/.*)?")) { final long dSec = Integer.parseInt(token.replace("user/training/", "")); if(dSec < 1000000000) { d = new Date(); } else { d = new Date(dSec * 1000); } } } catch (NumberFormatException e) { Motiver.showException(e); } //update tab headerUserPresenter.setTab(1); //if different page if(pagePresenter != null && !(pagePresenter instanceof TrainingPagePresenter)) { pagePresenter.stop(); pagePresenter = null; } if(pagePresenter == null) { pagePresenter = new TrainingPagePresenter(rpcService, eventBus, (TrainingPageDisplay)GWT.create(TrainingPageView.class), d); } pagePresenter.run(display.getBodyContainer()); } //nutrition else if (token.contains("user/nutrition")) { //page style RootPanel.get().addStyleName("page-nutrition"); //page title Window.setTitle("Motiver - " + AppController.Lang.Nutrition()); //analytics trackHit("nutrition"); //hide print page link // display.setPrintLinkVisibility(true); Date d = null; try { //check date if(token.matches("user/nutrition/[0-9]*(/.*)?")) { final long dSec = Integer.parseInt(token.replace("user/nutrition/", "")); if(dSec < 1000000000) { d = new Date(); } else { d = new Date(dSec * 1000); } } } catch (NumberFormatException e) { Motiver.showException(e); } //update tab headerUserPresenter.setTab(2); //if different page if(pagePresenter != null && !(pagePresenter instanceof NutritionPagePresenter)) { pagePresenter.stop(); pagePresenter = null; } if(pagePresenter == null) { pagePresenter = new NutritionPagePresenter(rpcService, eventBus, (NutritionPageDisplay)GWT.create(NutritionPageView.class), d); } pagePresenter.run(display.getBodyContainer()); } //cardio else if (token.contains("user/cardio")) { //page style RootPanel.get().addStyleName("page-cardio"); //page title Window.setTitle("Motiver - " + AppController.Lang.Cardio()); //analytics trackHit("cardio"); //update tab headerUserPresenter.setTab(3); //if different page if(pagePresenter != null && !(pagePresenter instanceof CardioPagePresenter)) { pagePresenter.stop(); pagePresenter = null; } if(pagePresenter == null) { pagePresenter = new CardioPagePresenter(rpcService, eventBus, (CardioPageDisplay)GWT.create(CardioPageView.class)); } pagePresenter.run(display.getBodyContainer()); } //statistics else if (token.contains("user/statistics")) { //page title Window.setTitle("Motiver - " + AppController.Lang.Statistics()); String target = ""; try { //check date if(token.matches("user/statistics/.*")) { target = token.replace("user/statistics/", ""); } } catch (Exception e) { Motiver.showException(e); } //analytics trackHit("stats"); //update tab headerUserPresenter.setTab(4); //if different page if(pagePresenter != null && !(pagePresenter instanceof StatisticsPagePresenter)) { pagePresenter.stop(); pagePresenter = null; } if(pagePresenter == null) { pagePresenter = new StatisticsPagePresenter(rpcService, eventBus, (StatisticsPageDisplay)GWT.create(StatisticsPageView.class), target); } pagePresenter.run(display.getBodyContainer()); } //profile else if (token.contains("user/profile")) { //page style RootPanel.get().addStyleName("page-profile"); //page title Window.setTitle("Motiver - " + AppController.Lang.Profile()); //analytics trackHit("profile"); //update tab headerUserPresenter.setTab(5); //if different page if(pagePresenter != null && !(pagePresenter instanceof ProfilePagePresenter)) { pagePresenter.stop(); pagePresenter = null; } if(pagePresenter == null) { pagePresenter = new ProfilePagePresenter(rpcService, eventBus, (ProfilePageDisplay)GWT.create(ProfilePageView.class)); } pagePresenter.run(display.getBodyContainer()); } //coach else if (token.contains("user/coach")) { //page title Window.setTitle("Motiver - " + AppController.Lang.Coach()); //analytics trackHit("coach"); //update tab headerUserPresenter.setTab(6); //if different page if(pagePresenter != null && !(pagePresenter instanceof CoachPagePresenter)) { pagePresenter.stop(); pagePresenter = null; } if(pagePresenter == null) { pagePresenter = new CoachPagePresenter(rpcService, eventBus, (CoachPageDisplay)GWT.create(CoachPageView.class)); } pagePresenter.run(display.getBodyContainer()); } //admin else if (token.contains("user/admin")) { //page title Window.setTitle("Motiver - " + AppController.Lang.Admin()); //analytics trackHit("admin"); //update tab headerUserPresenter.setTab(7); //if different page if(pagePresenter != null && !(pagePresenter instanceof AdminPagePresenter)) { pagePresenter.stop(); pagePresenter = null; } if(pagePresenter == null) { pagePresenter = new AdminPagePresenter(rpcService, eventBus, (AdminPageDisplay)GWT.create(AdminPageView.class)); } pagePresenter.run(display.getBodyContainer()); } //main else { //page title Window.setTitle("Motiver - " + AppController.Lang.Main()); //analytics trackHit("main"); //update tab headerUserPresenter.setTab(0); //if different page if(pagePresenter != null && !(pagePresenter instanceof MainPagePresenter)) { pagePresenter.stop(); pagePresenter = null; } if(pagePresenter == null) { pagePresenter = new MainPagePresenter(rpcService, eventBus, (MainPageDisplay)GWT.create(MainPageView.class)); } pagePresenter.run(display.getBodyContainer()); } } catch (Exception e) { Motiver.showException(e); } display.showLoading(false); } } /** * Launches timer which reloads page */ private void setPageReloadTimer() { if(timerReload != null) { timerReload.cancel(); } timerReload = new Timer() { @Override public void run() { pagePresenter.stop(); pagePresenter = null; History.fireCurrentHistoryState(); } }; timerReload.scheduleRepeating(Constants.DELAY_PAGE_RELOAD); } /** * Changes Analytics settings. * @param pageName String */ private native void trackHit(String pageName) /*-{ try { // setup tracking object with account var pageTracker = $wnd._gat._getTracker("UA-23160347-1"); pageTracker._setRemoteServerMode(); // turn on anchor observing pageTracker._setAllowAnchor(true) // send event to google server pageTracker._trackPageview(pageName); } catch(err) { } }-*/; /** * Loads comments and shows comments presenter if necessary */ protected void loadComments() { //not in coach mode if(AppController.COACH_MODE_ON) { return; } //fetch comments final Request req = rpcService.getComments(0, 20, null, AppController.User.getUid(), false, new MyAsyncCallback<List<CommentModel>>() { @Override public void onSuccess(List<CommentModel> list) { //check if new comments int newCommentsCount = 0; for(CommentModel m : list) { if(m != null && m.isUnread()) { newCommentsCount++; } } fireEvent(new CommentNewEvent(newCommentsCount)); } }); addRequest(req); } }
32.799316
228
0.671962
30af52181da2c24d1975bdf7ea9eb5d5c0ece300
10,652
package io.swagger.codegen; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.samskivert.mustache.Mustache; import io.swagger.codegen.*; import io.swagger.codegen.languages.AbstractCSharpCodegen; import io.swagger.models.*; import io.swagger.models.properties.*; import io.swagger.util.Json; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; import java.util.Map.Entry; import static java.util.UUID.randomUUID; public class AspAdvancedGenerator extends AbstractCSharpCodegen { private String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}"; @SuppressWarnings("hiding") protected Logger LOGGER = LoggerFactory.getLogger(AspAdvancedGenerator.class); public AspAdvancedGenerator() { super(); setSourceFolder("src"); outputFolder = "generated-code" + File.separator + this.getName(); modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("controller.mustache", ".cs"); // contextually reserved words // NOTE: C# uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons. reservedWords.addAll( Arrays.asList("var", "async", "await", "dynamic", "yield") ); cliOptions.clear(); // CLI options addOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Title.Case).", this.packageName); addOption(CodegenConstants.PACKAGE_VERSION, "C# package version.", this.packageVersion); addOption(CodegenConstants.OPTIONAL_PROJECT_GUID, CodegenConstants.OPTIONAL_PROJECT_GUID_DESC, null); addOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC, sourceFolder); addOption(CodegenConstants.PRESERVE_COMMENT_NEWLINES, "Preserve newlines in comments", String.valueOf(this.preserveNewLines)); // CLI Switches addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, this.sortParamsByRequiredFlag); addSwitch(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC, this.useDateTimeOffsetFlag); addSwitch(CodegenConstants.USE_COLLECTION, CodegenConstants.USE_COLLECTION_DESC, this.useCollection); addSwitch(CodegenConstants.RETURN_ICOLLECTION, CodegenConstants.RETURN_ICOLLECTION_DESC, this.returnICollection); } @Override public CodegenType getTag() { return CodegenType.SERVER; } @Override public String getName() { return "AspAdvanced"; } @Override public String getHelp() { return "Generates an ASP.NET Core Web API server."; } @Override public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_GUID)) { setPackageGuid((String) additionalProperties.get(CodegenConstants.OPTIONAL_PROJECT_GUID)); } additionalProperties.put("packageGuid", packageGuid); additionalProperties.put("dockerTag", this.packageName.toLowerCase()); apiPackage = packageName + ".Controllers"; modelPackage = packageName + ".Model"; String packageFolder = sourceFolder + File.separator + packageName; supportingFiles.add(new SupportingFile("NuGet.Config", "", "NuGet.Config")); supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("Solution.mustache", "", this.packageName + ".sln")); supportingFiles.add(new SupportingFile("Dockerfile.mustache", packageFolder, "Dockerfile")); supportingFiles.add(new SupportingFile("gitignore", packageFolder, ".gitignore")); supportingFiles.add(new SupportingFile("appsettings.json", packageFolder, "appsettings.json")); supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs")); supportingFiles.add(new SupportingFile("Program.mustache", packageFolder, "Program.cs")); supportingFiles.add(new SupportingFile("validateModel.mustache", packageFolder + File.separator + "Attributes", "ValidateModelStateAttribute.cs")); supportingFiles.add(new SupportingFile("web.config", packageFolder, "web.config")); supportingFiles.add(new SupportingFile("Project.csproj.mustache", packageFolder, this.packageName + ".csproj")); supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", packageFolder + File.separator + "Properties", "launchSettings.json")); supportingFiles.add(new SupportingFile("Filters" + File.separator + "BasePathFilter.mustache", packageFolder + File.separator + "Filters", "BasePathFilter.cs")); supportingFiles.add(new SupportingFile("Filters" + File.separator + "GeneratePathParamsValidationFilter.mustache", packageFolder + File.separator + "Filters", "GeneratePathParamsValidationFilter.cs")); supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", packageFolder + File.separator + "wwwroot", "README.md")); supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", packageFolder + File.separator + "wwwroot", "index.html")); supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", packageFolder + File.separator + "wwwroot", "web.config")); supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "swagger-original.mustache", packageFolder + File.separator + "wwwroot", "swagger-original.json")); } @Override public void setSourceFolder(final String sourceFolder) { if(sourceFolder == null) { LOGGER.warn("No sourceFolder specified, using default"); this.sourceFolder = "src" + File.separator + this.packageName; } else if(!sourceFolder.equals("src") && !sourceFolder.startsWith("src")) { LOGGER.warn("ASP.NET Core requires source code exists under src. Adjusting."); this.sourceFolder = "src" + File.separator + sourceFolder; } else { this.sourceFolder = sourceFolder; } } public void setPackageGuid(String packageGuid) { this.packageGuid = packageGuid; } @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Controllers"; } @Override public String modelFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Model"; } @Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { try { objs.put("swagger-json", Json.pretty().writeValueAsString(swagger).replace("\r\n", "\n")); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage(), e); } } return super.postProcessSupportingFileData(objs); } @Override protected void processOperation(CodegenOperation operation) { super.processOperation(operation); // HACK: Unlikely in the wild, but we need to clean operation paths for MVC Routing if (operation.path != null) { String original = operation.path; operation.path = operation.path.replace("?", "/"); if (!original.equals(operation.path)) { LOGGER.warn("Normalized " + original + " to " + operation.path + ". Please verify generated source."); } } // Converts, for example, PUT to HttpPut for controller attributes operation.httpMethod = "Http" + operation.httpMethod.substring(0, 1) + operation.httpMethod.substring(1).toLowerCase(); } @Override public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { // To avoid unexpected behaviors when options are passed programmatically such as { "useCollection": "" } return super.processCompiler(compiler).emptyStringIsFalse(true); } @Override public String toEnumVarName(String name, String datatype) { if (name.length() == 0) { return "Empty"; } // for symbol, e.g. $, # if (getSymbolName(name) != null) { return camelize(getSymbolName(name)); } String enumName = name.toLowerCase(); enumName = sanitizeName(camelize(enumName)); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); if (enumName.matches("\\d.*")) { // starts with number return "_" + enumName; } else { return enumName; } } @Override public String getTypeDeclaration(Property p) { String swaggerType = getSwaggerType(p); if (p instanceof ArrayProperty) { return getArrayTypeDeclaration((ArrayProperty) p); } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); return swaggerType + "<string, " + getTypeDeclaration(inner) + ">"; } if (p.getRequired()) { swaggerType = swaggerType.replaceAll("\\?", ""); return swaggerType; } return super.getTypeDeclaration(p); } private String getArrayTypeDeclaration(ArrayProperty arr) { String arrayType = typeMapping.get("array"); StringBuilder instantiationType = new StringBuilder(arrayType); Property items = arr.getItems(); String nestedType = getTypeDeclaration(items); instantiationType.append("<").append(nestedType).append(">"); return instantiationType.toString(); } @Override public String toEnumName(CodegenProperty property) { return sanitizeName(camelize(property.name)); } }
40.501901
209
0.656684
d6f5cde7ace188d39f57d591cd34cec101d70131
4,758
package net.minecraft.world.chunk.storage; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.chunk.BlockStateContainer; import net.minecraft.world.chunk.NibbleArray; public class ExtendedBlockStorage { private final int field_76684_a; private int field_76682_b; private int field_76683_c; public final BlockStateContainer field_177488_d; // Paper - package private NibbleArray field_76679_g; private NibbleArray field_76685_h; // Paper start - Anti-Xray - Support default constructor public ExtendedBlockStorage(int i, boolean flag) { this(i, flag, (IBlockState[]) null); } // Paper end public ExtendedBlockStorage(int i, boolean flag, IBlockState[] predefinedBlockData) { // Paper - Anti-Xray - Add predefined block data this.field_76684_a = i; this.field_177488_d = new BlockStateContainer(predefinedBlockData); // Paper - Anti-Xray - Add predefined block data this.field_76679_g = new NibbleArray(); if (flag) { this.field_76685_h = new NibbleArray(); } } // Paper start - Anti-Xray - Support default constructor public ExtendedBlockStorage(int y, boolean flag, char[] blockIds) { this(y, flag, blockIds, null); } // Paper end // CraftBukkit start public ExtendedBlockStorage(int y, boolean flag, char[] blockIds, IBlockState[] predefinedBlockData) { // Paper - Anti-Xray - Add predefined block data this.field_76684_a = y; this.field_177488_d = new BlockStateContainer(predefinedBlockData); // Paper - Anti-Xray - Add predefined block data for (int i = 0; i < blockIds.length; i++) { int xx = i & 15; int yy = (i >> 8) & 15; int zz = (i >> 4) & 15; this.field_177488_d.func_186013_a(xx, yy, zz, Block.field_176229_d.func_148745_a(blockIds[i])); } this.field_76679_g = new NibbleArray(); if (flag) { this.field_76685_h = new NibbleArray(); } func_76672_e(); } // CraftBukkit end public IBlockState func_177485_a(int i, int j, int k) { return this.field_177488_d.func_186016_a(i, j, k); } public void func_177484_a(int i, int j, int k, IBlockState iblockdata) { IBlockState iblockdata1 = this.func_177485_a(i, j, k); Block block = iblockdata1.func_177230_c(); Block block1 = iblockdata.func_177230_c(); if (block != Blocks.field_150350_a) { --this.field_76682_b; if (block.func_149653_t()) { --this.field_76683_c; } } if (block1 != Blocks.field_150350_a) { ++this.field_76682_b; if (block1.func_149653_t()) { ++this.field_76683_c; } } this.field_177488_d.func_186013_a(i, j, k, iblockdata); } public boolean func_76663_a() { return false; // CraftBukkit - MC-80966 } public boolean func_76675_b() { return this.field_76683_c > 0; } public int func_76662_d() { return this.field_76684_a; } public void func_76657_c(int i, int j, int k, int l) { this.field_76685_h.func_76581_a(i, j, k, l); } public int func_76670_c(int i, int j, int k) { return this.field_76685_h.func_76582_a(i, j, k); } public void func_76677_d(int i, int j, int k, int l) { this.field_76679_g.func_76581_a(i, j, k, l); } public int func_76674_d(int i, int j, int k) { return this.field_76679_g.func_76582_a(i, j, k); } public void func_76672_e() { this.field_76682_b = 0; this.field_76683_c = 0; for (int i = 0; i < 16; ++i) { for (int j = 0; j < 16; ++j) { for (int k = 0; k < 16; ++k) { Block block = this.func_177485_a(i, j, k).func_177230_c(); if (block != Blocks.field_150350_a) { ++this.field_76682_b; if (block.func_149653_t()) { ++this.field_76683_c; } } } } } } public BlockStateContainer func_186049_g() { return this.field_177488_d; } public NibbleArray func_76661_k() { return this.field_76679_g; } public NibbleArray func_76671_l() { return this.field_76685_h; } public void func_76659_c(NibbleArray nibblearray) { this.field_76679_g = nibblearray; } public void func_76666_d(NibbleArray nibblearray) { this.field_76685_h = nibblearray; } }
31.098039
155
0.598991
2b464fe5ae95a60482002e3a6aaa104cc0a253b8
1,402
package Distributed_System_Java_Src.dc_socket; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class SocketServer { public static void main(String[] args) throws IOException{ //define server socket ServerSocket ss = new ServerSocket(1286); //accept from client Socket s = ss.accept(); // define output stream from the server OutputStream socketOutputStream = s.getOutputStream(); DataOutputStream socketDOS = new DataOutputStream(socketOutputStream); //send an output from server to client socketDOS.writeUTF("Server connected"); //define server's input InputStream sIn = s.getInputStream(); DataInputStream socketDIS = new DataInputStream(sIn); while(true) { //receive message from client String receive = socketDIS.readUTF(); String sent_string= receive; //send back to client socketDOS.writeUTF(sent_string); if(receive.equals("quit")) break; } socketDOS.close(); socketDIS.close(); s.close(); ss.close(); } }
28.612245
79
0.607703
5b7d10cd5001559980e18a7d13480939fa05e45d
3,129
package org.jpo.gui.swing; import org.jpo.testground.PlayWithFontAwesome; import java.awt.*; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /* Copyright (C) 2020-2021 Richard Eigenmann. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. The license is in gpl.txt. See http://www.gnu.org/copyleft/gpl.html for the details. */ /** * Static class that loads the Font Awesome Font into a Java Font object. * * @see <a href="https://stackoverflow.com/questions/24177348/font-awesome-with-swing">https://stackoverflow.com/questions/24177348/font-awesome-with-swing</a> */ public class FontAwesomeFont { private FontAwesomeFont() { throw new IllegalStateException("Utility class"); } private static final Logger LOGGER = Logger.getLogger(FontAwesomeFont.class.getName()); private static Font fontAwesomeRegular24; private static Font fontAwesomeRegular18; private static Font fontAwesomeSolid24; static { try (final var regular = PlayWithFontAwesome.class.getResourceAsStream("/Font Awesome 5 Free-Regular-400.otf"); final var solid = PlayWithFontAwesome.class.getResourceAsStream("/Font Awesome 5 Free-Solid-900.otf")) { final var baseFontRegular = Font.createFont(Font.TRUETYPE_FONT, regular); fontAwesomeRegular24 = baseFontRegular.deriveFont(Font.PLAIN, 24f); fontAwesomeRegular18 = baseFontRegular.deriveFont(Font.PLAIN, 18f); final var baseFontSolid = Font.createFont(Font.TRUETYPE_FONT, solid); fontAwesomeSolid24 = baseFontSolid.deriveFont(Font.PLAIN, 24f); } catch (final IOException | FontFormatException e) { LOGGER.log(Level.SEVERE, "Could not load FontAwesome font. Exception: {0}", e.getMessage()); } } /** * Returns the static instance of the 24 size Font Awesome Font Regular-400 * * @return The Java Font object */ public static Font getFontAwesomeRegular24() { return fontAwesomeRegular24; } /** * Returns the static instance of the 24 size Font Awesome Font Solid-900 * * @return The Java Font object */ public static Font getFontAwesomeSolid24() { return fontAwesomeSolid24; } /** * Returns the static instance of the 18 size Font Awesome Font * * @return The Java Font object */ public static Font getFontAwesomeRegular18() { return fontAwesomeRegular18; } }
35.965517
159
0.712049
5c2770a28aad62428ab85d40e067c9a2752ce8a5
347
package com.oxchains.themis.notice.dao; import com.oxchains.themis.notice.domain.SearchType; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * @author luoxuri * @create 2017-10-27 10:39 **/ @Repository public interface SearchTypeDao extends CrudRepository<SearchType,Long> { }
24.785714
72
0.801153
72389de580f36f63f0562064bd9847a1574d2856
1,295
package me.interair.lexer.mr; import lombok.extern.slf4j.Slf4j; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.tree.ParseTree; @Slf4j class AstPrinter { private boolean ignoringWrappers = true; public void setIgnoringWrappers(boolean ignoringWrappers) { this.ignoringWrappers = ignoringWrappers; } public void print(RuleContext ctx) { explore(ctx, 0); } private void explore(RuleContext ctx, int indentation) { boolean toBeIgnored = ignoringWrappers && ctx.getChildCount() == 1 && ctx.getChild(0) instanceof ParserRuleContext; if (!toBeIgnored) { String ruleName = MrParser.ruleNames[ctx.getRuleIndex()]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < indentation; i++) { sb.append("--|"); } System.out.println(sb.toString() + ruleName + ": " + ctx.getText()); } for (int i = 0; i < ctx.getChildCount(); i++) { ParseTree element = ctx.getChild(i); if (element instanceof RuleContext) { explore((RuleContext) element, indentation + (toBeIgnored ? 0 : 1)); } } } }
31.585366
84
0.599228
2ce84799ea39ef55b298f99f1f38c5e1ec17cea2
1,537
package com.hozakan.emailchecker.ui.adapter; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import com.hozakan.emailchecker.R; import com.hozakan.emailchecker.data.contract.AccountContract; /** * Created by gimbert on 15-07-08. */ public class AccountAdapter extends CursorAdapter { private final LayoutInflater mInflater; private View mTmpView; private ViewHolder mTmpHolder; public AccountAdapter(Context context, Cursor cursor) { super(context, cursor, 0); mInflater = LayoutInflater.from(context); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { mTmpView = mInflater.inflate(R.layout.list_item_account, parent, false); mTmpView.setTag(new ViewHolder(mTmpView)); return mTmpView; } @Override public void bindView(View view, Context context, Cursor cursor) { mTmpHolder = (ViewHolder) view.getTag(); mTmpHolder.accountName.setText(cursor.getString(AccountContract.COL_ACCOUNT_NAME)); } @Override public long getItemId(int position) { return super.getItemId(position); } static class ViewHolder { public final TextView accountName; public ViewHolder(View itemView) { accountName = (TextView) itemView.findViewById(R.id.tv_account_name); } } }
27.945455
91
0.716981
f8bb71ae05a794de379c75b9a6d0595d4378b23d
2,272
/* * #%L * wcm.io * %% * Copyright (C) 2018 wcm.io * %% * 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. * #L% */ package io.wcm.qa.galenium.listeners; import org.slf4j.Logger; import org.slf4j.Marker; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.TestListenerAdapter; import io.wcm.qa.galenium.reporting.GaleniumReportUtil; /** * Logs memory usage. */ public class MemoryUsageListener extends TestListenerAdapter { private static final Marker MEMORY_MARKER = GaleniumReportUtil.getMarker("galenium.listener.memory"); @Override public void onFinish(ITestContext testContext) { logMemory(); } @Override public void onStart(ITestContext testContext) { logMemory(); super.onStart(testContext); } @Override public void onTestFailure(ITestResult tr) { logMemory(); super.onTestFailure(tr); } @Override public void onTestSkipped(ITestResult tr) { logMemory(); super.onTestSkipped(tr); } @Override public void onTestStart(ITestResult result) { logMemory(); } @Override public void onTestSuccess(ITestResult tr) { logMemory(); super.onTestSuccess(tr); } private String getMemoryMessage() { Runtime runtime = Runtime.getRuntime(); StringBuilder memoryMessage = new StringBuilder() .append("free memory: ") .append(runtime.freeMemory()) .append("\ntotal memory: ") .append(runtime.totalMemory()) .append("\nmax memory: ") .append(runtime.maxMemory()); return memoryMessage.toString(); } private void logMemory() { getLogger().trace(getMemoryMessage()); } private static Logger getLogger() { return GaleniumReportUtil.getMarkedLogger(MEMORY_MARKER); } }
23.183673
103
0.702025
0a3913aa93ecb66aadec8af1a039eafb09b8d67e
3,012
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.api.mapper.entity.naming; import com.datastax.oss.driver.api.mapper.annotations.Entity; import com.datastax.oss.driver.api.mapper.annotations.NamingStrategy; /** * A built-in convention to infer CQL column names from the names used in an {@link * Entity}-annotated class. * * @see NamingStrategy */ public enum NamingConvention { /** * Uses the Java name as-is, as a <em>case-insensitive</em> CQL name, for example {@code Product * => Product, productId => productId}. * * <p>In practice this is the same as lower-casing everything ({@code product, productid}), but it * makes generated queries a bit easier to read. */ CASE_INSENSITIVE, /** * Uses the Java name as-is, as a <em>case-sensitive</em> CQL name, for example {@code Product => * "Product", productId => "productId"}. * * <p>Use this if your schema uses camel case and you want to preserve capitalization in table * names. */ EXACT_CASE, /** * Divide the Java name into words, splitting on upper-case characters; capitalize every word * except the first; then concatenate the words and make the result a <em>case-sensitive</em> CQL * name, for example {@code Product => "product", productId => "productId"}. */ LOWER_CAMEL_CASE, /** * Divide the Java name into words, splitting on upper-case characters; capitalize every word; * then concatenate the words and make the result a <em>case-sensitive</em> CQL name, for example * {@code Product => "Product", productId => "ProductId"}. */ UPPER_CAMEL_CASE, /** * Divide the Java name into words, splitting on upper-case characters; lower-case everything; * then concatenate the words with underscore separators, and make the result a * <em>case-insensitive</em> CQL name, for example {@code Product => product, productId => * product_id}. */ SNAKE_CASE_INSENSITIVE, /** * Divide the Java name into words, splitting on upper-case characters; upper-case everything; * then concatenate the words with underscore separators, and make the result a * <em>case-sensitive</em> CQL name, for example {@code Product => "PRODUCT", productId => * "PRODUCT_ID"}. */ UPPER_SNAKE_CASE, /** * Upper-case everything, and make the result a <em>case-sensitive</em> CQL name, for example * {@code Product => "PRODUCT", productId => "PRODUCTID"}. */ UPPER_CASE, }
36.289157
100
0.701859
8bd8442935f571c3620153d26f569a7903a9b986
1,710
package com.hazelcast.yarn.mapreverser; import com.hazelcast.yarn.api.dag.Vertex; import com.hazelcast.yarn.api.tuple.Tuple; import com.hazelcast.yarn.api.tuple.io.TupleInputStream; import com.hazelcast.yarn.api.tuple.io.TupleOutputStream; import com.hazelcast.yarn.api.container.ContainerContext; import com.hazelcast.yarn.api.processor.TupleContainerProcessor; import com.hazelcast.yarn.api.processor.TupleContainerProcessorFactory; import java.util.concurrent.atomic.AtomicInteger; public class Reverser implements TupleContainerProcessor<Integer, String, String, Integer> { public static final AtomicInteger ii = new AtomicInteger(0); @Override public void beforeProcessing(ContainerContext containerContext) { } @Override public boolean process(TupleInputStream<Integer, String> inputStream, TupleOutputStream<String, Integer> outputStream, String sourceName, ContainerContext containerContext) throws Exception { for (Tuple tuple : inputStream) { ii.incrementAndGet(); Object key = tuple.getKey(0); Object value = tuple.getValue(0); tuple.setKey(0, value); tuple.setValue(0, key); outputStream.consume(tuple); } return true; } @Override public boolean finalizeProcessor(TupleOutputStream<String, Integer> outputStream, ContainerContext containerContext) { return true; } public static class Factory implements TupleContainerProcessorFactory { public TupleContainerProcessor getProcessor(Vertex vertex) { return new Reverser(); } } }
34.2
122
0.696491
c2ddb81a0729c06ba936c1af81b238019bb9c9f9
12,506
/* * Copyright 2017-2019 original 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 io.micronaut.security.oauth2.openid.endpoints.authorization; import io.micronaut.context.annotation.Requires; import io.micronaut.core.util.StringUtils; import io.micronaut.http.HttpRequest; import io.micronaut.http.uri.UriBuilder; import io.micronaut.security.oauth2.openid.OpenIdScope; import io.micronaut.security.oauth2.openid.configuration.OpenIdProviderMetadata; import io.micronaut.security.oauth2.openid.endpoints.DefaultRedirectUrlProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.inject.Singleton; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Default implementation of {@link io.micronaut.security.oauth2.openid.endpoints.authorization.AuthorizationRedirectUrlProvider}. * * @author Sergio del Amo * @since 1.0.0 */ @Singleton @Requires(beans = {AuthenticationRequestProvider.class, OpenIdProviderMetadata.class}) public class DefaultAuthorizationRedirectUrlProvider implements AuthorizationRedirectUrlProvider { private static final Logger LOG = LoggerFactory.getLogger(DefaultAuthorizationRedirectUrlProvider.class); @Nonnull private final AuthenticationRequestProvider authenticationRequestProvider; @Nonnull private final OpenIdProviderMetadata openIdProviderMetadata; @Nonnull private final DefaultRedirectUrlProvider defaultRedirectUrlProvider; /** * * @param authenticationRequestProvider Authentication Request provider * @param openIdProviderMetadata OpenID provider metadata. * @param defaultRedirectUrlProvider Default Redirect Url Provider */ public DefaultAuthorizationRedirectUrlProvider(AuthenticationRequestProvider authenticationRequestProvider, OpenIdProviderMetadata openIdProviderMetadata, DefaultRedirectUrlProvider defaultRedirectUrlProvider) { this.authenticationRequestProvider = authenticationRequestProvider; this.openIdProviderMetadata = openIdProviderMetadata; this.defaultRedirectUrlProvider = defaultRedirectUrlProvider; } /** * @param request the Original request prior redirect. * @return A URL to redirect the user to the OpenID Provider authorization endpoint. */ @Override public String resolveAuthorizationRedirectUrl(HttpRequest<?> request) { AuthenticationRequest authenticationRequest = authenticationRequestProvider.generateAuthenticationRequest(request); Map<String, Object> arguments = instantiateParameters(authenticationRequest); String baseUrl = this.openIdProviderMetadata.getAuthorizationEndpoint(); String expandedUri = expandedUri(baseUrl, arguments); if (LOG.isDebugEnabled()) { LOG.debug("authorization redirect url {}", expandedUri); } return expandedUri; } /** * @param baseUrl Base Url * @param queryParams Query Parameters * @return The Expanded URI */ protected String expandedUri(@Nonnull String baseUrl, @Nonnull Map<String, Object> queryParams) { UriBuilder builder = UriBuilder.of(baseUrl); for (String k : queryParams.keySet()) { Object val = queryParams.get(k); if (val != null) { builder.queryParam(k, val); } } return builder.toString(); } /** * * @param authenticationRequest Authentication Request * @return A parameter map which contains the URL variables used to construct the authorization redirect url. */ protected Map<String, Object> instantiateParameters(AuthenticationRequest authenticationRequest) { Map<String, Object> parameters = new HashMap<>(); populateScope(authenticationRequest, parameters); populateResponseType(authenticationRequest, parameters); populateClientId(authenticationRequest, parameters); populateRedirectUri(authenticationRequest, parameters); populateState(authenticationRequest, parameters); populateResponseMode(authenticationRequest, parameters); populateNonce(authenticationRequest, parameters); populateDisplay(authenticationRequest, parameters); populatePrompt(authenticationRequest, parameters); populateMaxAge(authenticationRequest, parameters); populateUiLocales(authenticationRequest, parameters); populateIdTokenHint(authenticationRequest, parameters); populateLoginHint(authenticationRequest, parameters); populateAcrValues(authenticationRequest, parameters); return parameters; } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateScope(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { Optional<String> optionalStr = authenticationRequest.getScopes().stream().reduce((a, b) -> a + StringUtils.SPACE + b); parameters.put(AuthenticationRequest.PARAMETER_SCOPE, optionalStr.orElse(OpenIdScope.OPENID.getScope())); } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateResponseType(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { parameters.put(AuthenticationRequest.PARAMETER_RESPONSE_TYPE, authenticationRequest.getResponseType()); } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateClientId(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { parameters.put(AuthenticationRequest.PARAMETER_CLIENT_ID, authenticationRequest.getClientId()); } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateRedirectUri(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { parameters.put(AuthenticationRequest.PARAMETER_REDIRECT_URI, authenticationRequest.getRedirectUri() != null ? authenticationRequest.getRedirectUri() : defaultRedirectUrlProvider.getRedirectUri()); } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateState(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getState() != null) { parameters.put(AuthenticationRequest.PARAMETER_STATE, authenticationRequest.getState()); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateResponseMode(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getResponseMode() != null) { parameters.put(AuthenticationRequest.PARAMETER_RESPONSE_MODE, authenticationRequest.getResponseMode()); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateNonce(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getNonce() != null) { parameters.put(AuthenticationRequest.PARAMETER_NONCE, authenticationRequest.getNonce()); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateDisplay(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getDisplay() != null) { parameters.put(AuthenticationRequest.PARAMETER_DISPLAY, authenticationRequest.getDisplay()); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populatePrompt(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getPrompt() != null) { parameters.put(AuthenticationRequest.PARAMETER_PROMPT, authenticationRequest.getPrompt()); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateMaxAge(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getMaxAge() != null) { parameters.put(AuthenticationRequest.PARAMETER_MAX_AGE, authenticationRequest.getMaxAge()); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateUiLocales(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getUiLocales() != null) { Optional<String> optionalUiLocales = authenticationRequest.getUiLocales().stream().reduce((a, b) -> a + StringUtils.SPACE + b); optionalUiLocales.ifPresent(uiLocales -> parameters.put(AuthenticationRequest.PARAMETER_UI_LOCALES, uiLocales)); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateIdTokenHint(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getIdTokenHint() != null) { parameters.put(AuthenticationRequest.PARAMETER_ID_TOKEN_HINT, authenticationRequest.getIdTokenHint()); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateLoginHint(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getLoginHint() != null) { parameters.put(AuthenticationRequest.PARAMETER_LOGIN_HINT, authenticationRequest.getLoginHint()); } } /** * * @param authenticationRequest Authentication Request * @param parameters Authentication Request Parameters */ protected void populateAcrValues(@Nonnull AuthenticationRequest authenticationRequest, @Nonnull Map<String, Object> parameters) { if (authenticationRequest.getAcrValues() != null) { Optional<String> optionalAcrValues = authenticationRequest.getAcrValues().stream().reduce((a, b) -> a + StringUtils.SPACE + b); optionalAcrValues.ifPresent(acrValues -> parameters.put(AuthenticationRequest.PARAMETER_ACR_VALUES, acrValues)); } } }
43.273356
204
0.697665
cfdecfc6b925acd5417644038f1d142247296717
1,041
package com.blagoy.officemaps.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table public class Door { @Id @GeneratedValue private long id; private double leftX; private double rightX; private double leftY; private double rightY; public long getId() { return id; } public double getLeftX() { return leftX; } public void setLeftX(double leftX) { this.leftX = leftX; } public double getRightX() { return rightX; } public void setRightX(double rightX) { this.rightX = rightX; } public double getLeftY() { return leftY; } public void setLeftY(double leftY) { this.leftY = leftY; } public double getRightY() { return rightY; } public void setRightY(double rightY) { this.rightY = rightY; } public void setId(long id) { this.id = id; } }
16.52381
42
0.610951
d6d320489280d8a31a886832d3700df51fd90fee
232
// SPDX-License-Identifier: MIT package com.mercedesbenz.sechub.adapter.testclasses; import com.mercedesbenz.sechub.adapter.WebScanAdapterConfig; public interface TestWebScanAdapterConfigInterface extends WebScanAdapterConfig { }
29
81
0.857759
4d2b6d4f76f1fbce53a224521427a5ae1e30c9cb
2,857
package com.alternativeinfrastructures.noise.views.debug; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.alternativeinfrastructures.noise.R; import com.raizlabs.android.dbflow.list.FlowCursorList; import com.raizlabs.android.dbflow.list.FlowQueryList; import com.raizlabs.android.dbflow.sql.language.SQLite; import com.alternativeinfrastructures.noise.storage.UnknownMessage; import com.alternativeinfrastructures.noise.storage.UnknownMessage_Table; import java.util.UUID; public class RawMessageList extends AppCompatActivity { public static final String TAG = "RawMessageList"; private static final byte TEST_ZERO_BITS = 10; private static final UUID TEST_TYPE = new UUID(0, 0); private FlowQueryList<UnknownMessage> messages; private ArrayAdapter<UnknownMessage> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_raw_message_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle(R.string.raw_message_view_title); // TODO: Use a query list that's smarter about not copying the entire list at once messages = SQLite.select().from(UnknownMessage.class).orderBy(UnknownMessage_Table.payload, true).flowQueryList(); messages.registerForContentChanges(this); adapter = new ArrayAdapter<UnknownMessage>(this, android.R.layout.simple_list_item_1, messages); messages.addOnCursorRefreshListener(new FlowCursorList.OnCursorRefreshListener<UnknownMessage>() { @Override public void onCursorRefreshed(FlowCursorList<UnknownMessage> cursorList) { Log.d(TAG, "Displaying new unknown message"); adapter.notifyDataSetChanged(); } }); ListView listView = (ListView) findViewById(R.id.content_raw_message_list_view); listView.setAdapter(adapter); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { byte[] payload = "This is an unencrypted test message".getBytes(); UnknownMessage.Companion.rawCreateAndSignAsync(payload, TEST_ZERO_BITS, TEST_TYPE).subscribe(); } catch (UnknownMessage.PayloadTooLargeException e) { Log.e(TAG, "Message not created", e); } } }); } }
40.814286
122
0.715436
52bc826ccc9a008391a46148f16a725ffd9a4c83
308
package com.haut.music.utils; import javax.servlet.http.HttpServletRequest; import com.haut.music.model.User; /** * 获取userSession */ public class Request { public static User getUserFromHttpServletRequest(HttpServletRequest request) { return (User) request.getSession().getAttribute("user"); } }
18.117647
79
0.762987
13fd12c4146c09e037573cc6921b97dbba97e2eb
1,728
package com.qaprosoft.carina.demo.cucumber.steps.manali; import org.openqa.selenium.interactions.touch.TouchActions; import com.qaprosoft.carina.core.foundation.cucumber.CucumberRunner; import com.qaprosoft.carina.demo.mobile.gui.pages.common.EguruLoginPageBase; import com.qaprosoft.carina.demo.mobile.gui.pages.common.EguruMainPageBase; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class EguruStepdef extends CucumberRunner{ EguruLoginPageBase login=null; EguruMainPageBase Main=null; @Given("^launch your app$") public void Mainpage() { login = initPage(getDriver(), EguruLoginPageBase.class); System.out.println("Application launched"); pause(8); } @When("^click on userid and pw$") public void enteruserid() { login.EnterUserid("PV10_SPMA"); System.out.println("Entered userid"); login.EnterPassword("Tata@2019"); } @Then("^click on login$") public void clicklogin() { login.ClickLogin(); System.out.println("clicked login button"); pause(8); } @And("^Click OK$") public void ClickOK() { login.ClickOK(); } @And("^ClickNavigation$") public void Clicknavigation() { login.Clicknavigation(); } @And("^click Logout$") public void Clicklogout() { login.Clicklogout(); //System.out.println("Logged"); } @Then("^clickContacts$") public void clickContacts() { Main = initPage(getDriver(), EguruMainPageBase.class); Main.clickContacts(); } @And("^Enter Basic Details$") public void enterbasicdetails() { Main.enterbasicdetails("qktest","test","8888888888","[email protected]"); } }
25.043478
78
0.699074
3b4521c53be5947416c8a8e0fd16664681128f7c
2,635
/* * 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.typeutils; import org.apache.flink.api.common.typeutils.TypeInformationTestBase; /** Test for {@link PojoTypeInfo}. */ class PojoTypeInfoTest extends TypeInformationTestBase<PojoTypeInfo<?>> { @Override protected PojoTypeInfo<?>[] getTestData() { return new PojoTypeInfo<?>[] { (PojoTypeInfo<?>) TypeExtractor.getForClass(TestPojo.class), (PojoTypeInfo<?>) TypeExtractor.getForClass(AlternatePojo.class), (PojoTypeInfo<?>) TypeExtractor.getForClass(PrimitivePojo.class), (PojoTypeInfo<?>) TypeExtractor.getForClass(UnderscorePojo.class) }; } public static final class TestPojo { public int someInt; private String aString; public Double[] doubleArray; public void setaString(String aString) { this.aString = aString; } public String getaString() { return aString; } } public static final class AlternatePojo { public int someInt; private String aString; public Double[] doubleArray; public void setaString(String aString) { this.aString = aString; } public String getaString() { return aString; } } public static final class PrimitivePojo { private int someInt; public void setSomeInt(Integer someInt) { this.someInt = someInt; } public Integer getSomeInt() { return this.someInt; } } public static final class UnderscorePojo { private int some_int; public void setSomeInt(int some_int) { this.some_int = some_int; } public Integer getSomeInt() { return this.some_int; } } }
27.447917
77
0.648577
e21ecd7eac6dbf395f1c93f4d306f16ebe1c4e2b
788
package br.com.mgr.rh.service.reajuste; import br.com.mgr.rh.ValidacaoException; import br.com.mgr.rh.model.Funcionario; import java.math.BigDecimal; import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class ValidacaoPeriodicidadeEntreReajustes implements ValidacaoReajuste { @Override public void validar(Funcionario funcionario, BigDecimal aumento) { final LocalDate dataUltimoReajuste = funcionario.getDataUltimoReajuste(); final LocalDate dataAtual = LocalDate.now(); final long mesesDesdoUltimoReajuste = ChronoUnit.MONTHS.between(dataUltimoReajuste, dataAtual); if (mesesDesdoUltimoReajuste < 6 ) { throw new ValidacaoException("Intervalo entre reajuste deve ser no minimo de 6 meses!"); } } }
37.52381
103
0.755076
9c6f46b129f95f250f98210f920c43acdcf5d781
5,005
package com.lgy.oms.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.lgy.common.constant.Constants; import com.lgy.common.utils.StringUtils; import com.lgy.common.utils.reflect.ReflectUtils; import com.lgy.oms.domain.StrategyDistributionWarehouseLogistics; import com.lgy.oms.domain.StrategyDistributionWarehouseRule; import com.lgy.oms.domain.order.OrderMain; import com.lgy.oms.mapper.StrategyDistributionWarehouseLogisticsMapper; import com.lgy.oms.service.IStrategyDistributionWarehouseLogisticsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 配货策略分仓物流规则 服务层实现 * * @author lgy * @date 2020-02-01 */ @Service public class StrategyDistributionWarehouseLogisticsServiceImpl extends ServiceImpl<StrategyDistributionWarehouseLogisticsMapper, StrategyDistributionWarehouseLogistics> implements IStrategyDistributionWarehouseLogisticsService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public List<StrategyDistributionWarehouseLogistics> getStrategyByGco(String gco) { QueryWrapper<StrategyDistributionWarehouseLogistics> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("gco", gco); return this.list(queryWrapper); } @Override public boolean updatePrePriority(Long id, int i) { StrategyDistributionWarehouseLogistics entity = new StrategyDistributionWarehouseLogistics(); entity.setId(id); entity.setPriority(i); return this.updateById(entity); } @Override public boolean changeField(Long id, String field, int value) { StrategyDistributionWarehouseLogistics rule = new StrategyDistributionWarehouseLogistics(); rule.setId(id); ReflectUtils.setFieldValue(rule, field, value); return updateById(rule); } @Override public List<String> getLogisticsWarehouse(List<String> warehouseList, OrderMain orderMain, String gco, StrategyDistributionWarehouseRule warehouseRule) { if (StringUtils.isEmpty(orderMain.getLogistics())) { return warehouseList; } List<StrategyDistributionWarehouseLogistics> logisticsList = getStrategyByGcoAndLogistics(gco, orderMain.getLogistics()); // 当条件为空是,返回原仓库信息 if (logisticsList == null || logisticsList.isEmpty()) { return warehouseList; } //排除物流不到达的仓库 List<StrategyDistributionWarehouseLogistics> list = new ArrayList<>(logisticsList.size()); for (StrategyDistributionWarehouseLogistics logistics : logisticsList) { if (Constants.NO.equals(logistics.getArrive())) { list.add(logistics); if (warehouseList.contains(logistics.getWarehouse())) { logger.debug("订单[{}]根据配货策略[{}]分仓规则-物流仓库规则,物流商[{}]不到达仓库[{}],移除该仓库", orderMain.getOrderId(), gco, orderMain.getLogistics(), logistics.getWarehouse()); warehouseList.remove(logistics.getWarehouse()); } } } logisticsList = list; for (StrategyDistributionWarehouseLogistics logistics : logisticsList) { if (warehouseList.contains(logistics.getWarehouse())) { if (Constants.YES.equals(warehouseRule.getMust())) { //必须规则 warehouseList.clear(); warehouseList.add(logistics.getWarehouse()); logger.debug("订单[{}]匹配仓库:物流分配仓库规则匹配仓库(必须规则)[{}]", orderMain.getOrderId(), warehouseList); return warehouseList; } else { //非必须规则,调整仓库优先级为最高 warehouseList.remove(logistics.getWarehouse()); warehouseList.add(0, logistics.getWarehouse()); logger.debug("订单[{}]匹配仓库:物流分配仓库规则匹配仓库(非必须规则):[{}]", orderMain.getOrderId(), warehouseList); return warehouseList; } } } return warehouseList; } /** * 根据策略编码和订单物流获取匹配策略列表 * * @param gco 策略编码 * @param logistics 物流商编码 * @return 策略列表 */ private List<StrategyDistributionWarehouseLogistics> getStrategyByGcoAndLogistics(String gco, String logistics) { QueryWrapper<StrategyDistributionWarehouseLogistics> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("gco", gco); if (logistics.contains(Constants.COMMA)) { //包含逗号,说明有多条 queryWrapper.in("logistics", Arrays.asList(logistics.split(Constants.COMMA))); } else { queryWrapper.eq("logistics", logistics); } queryWrapper.orderByAsc("priority"); return this.list(queryWrapper); } }
40.362903
228
0.667333
3873045b53d037187791893231a48e81ca798608
2,227
package nuc.web.pojo; /** * 部门表 */ public class Department { private int id; private int department_number; private String name; private String manager; private String telephone; private String address; private String notes; public Department() { } public Department(int id, int department_number, String name, String manager, String telephone, String address, String notes) { this.id = id; this.department_number = department_number; this.name = name; this.manager = manager; this.telephone = telephone; this.address = address; this.notes = notes; } public int getId() { return id; } public int getDepartment_number() { return department_number; } public void setDepartment_number(int department_number) { this.department_number = department_number; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getManager() { return manager; } public void setManager(String manager) { this.manager = manager; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } @Override public String toString() { return "Department{" + "id=" + id + ", department_number=" + department_number + ", name='" + name + '\'' + ", manager='" + manager + '\'' + ", telephone='" + telephone + '\'' + ", address='" + address + '\'' + ", notes='" + notes + '\'' + '}'; } }
22.494949
132
0.527167
2467e97e249058d5f3d6da6a842759bc9257db35
3,042
package com.doctoredapps.androidjeopardy.model; import android.database.Observable; import android.support.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.HashMap; /** * Created by MattDupree on 10/26/14. */ public class Game implements Round.OnRoundEndedListener { public static final int GAME_STATE_NEW_ROUND = 0; public static final int GAME_STATE_FINAL_JEOPARDY = 1; public static final int GAME_STATE_END = 2; private final Round[] rounds; private final HashMap<String, Player> players; private Round currentRound; private int currentRoundIndex; private Player playerWithControl; private GameStateObservable gameStateObservable; Game(Round[] rounds, HashMap<String, Player> players) { this.rounds = rounds; this.players = players; this.currentRound = rounds[currentRoundIndex]; this.currentRound.registerObserver(this); this.gameStateObservable = new GameStateObservable(); } public void incrementPlayerScore(String playerId) { players.get(playerId).increaseScoreBy(currentRound.getCurrentAnswer().getScoreValue()); } public void decrementPlayerScore(String playerId) { players.get(playerId).decreaseScoreBy(currentRound.getCurrentAnswer().getScoreValue()); } public void givePlayerControl(String playerId) { playerWithControl.setInControl(false); Player player = players.get(playerId); playerWithControl = player; player.setInControl(true); } @Override public void onRoundEnded() { dispatchGameStateChangedNotification(); } private void dispatchGameStateChangedNotification() { if (noMoreRounds()) { gameStateObservable.notifyGameStateChanged(GAME_STATE_END); return; } if (finalJeopardyIsNextRound()) { gameStateObservable.notifyGameStateChanged(GAME_STATE_FINAL_JEOPARDY); } else { gameStateObservable.notifyGameStateChanged(GAME_STATE_NEW_ROUND); } currentRound = rounds[++currentRoundIndex]; } private boolean finalJeopardyIsNextRound() { return currentRoundIndex < rounds.length - 1; } private boolean noMoreRounds() { return currentRoundIndex == rounds.length; } @Retention(RetentionPolicy.SOURCE) @IntDef({GAME_STATE_NEW_ROUND, GAME_STATE_FINAL_JEOPARDY, GAME_STATE_END}) public @interface GAME_STATE { } /** * Created by MattDupree on 10/26/14. */ public interface OnGameStateChangedListner { void onGameStateChanged(@GAME_STATE int newGameState); } private static class GameStateObservable extends Observable<OnGameStateChangedListner> { public void notifyGameStateChanged(@GAME_STATE int newGameState) { for (OnGameStateChangedListner listner : mObservers) { listner.onGameStateChanged(newGameState); } } } }
30.42
95
0.70217
ed035eec3232e0ce003fa97921af68145ec480d1
1,020
//Powered By ZSCAT, Since 2014 - 2020 package com.zsTrade.web.bases.model; import javax.persistence.Table; import com.zsTrade.common.base.BaseEntity; /** * * @author zsCat 2016-11-2 17:13:42 * @Email: [email protected] * @version 4.0v * 优惠劵管理 */ @SuppressWarnings({ "unused"}) @Table(name="shop_favorites") public class Favorites extends BaseEntity { private static final long serialVersionUID = 1L; private Long favId; public Long getFavId() {return this.getLong("favId");} public void setFavId(Long favId) {this.set("favId",favId);} private String favType; public String getFavType() {return this.getString("favType");} public void setFavType(String favType) {this.set("favType",favType);} private Long favTime; public Long getFavTime() {return this.getLong("favTime");} public void setFavTime(Long favTime) {this.set("favTime",favTime);} private Long memberId; public Long getMemberId() {return this.getLong("memberId");} public void setMemberId(Long memberId) {this.set("memberId",memberId);} }
26.842105
71
0.742157
0c49361e1f3f64baee175424b6433c18f2d59143
144
package br.com.sidney; public class RedLight implements Semaphore { @Override public void doAction() { System.out.println("Red."); } }
12
44
0.701389
0565b9579912efa30cab14e6b3d3f9de0da7358e
76
package com.deeal.activity.callback; public class FashionShowCallback { }
12.666667
36
0.802632
946367126cdb2832729f647c850351bdf7db1e6f
2,447
package uk.ac.ebi.subs.repository.model.templates; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import org.json.JSONObject; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @Builder(toBuilder = true) @Data @NoArgsConstructor @AllArgsConstructor public class DateFieldCapture implements Capture { @NonNull private String fieldName; private static final JsonFieldType fieldType = JsonFieldType.String; @Builder.Default private boolean required = false; private String displayName; @Override public Capture copy() { return this.toBuilder().build(); } private final static DateFormat[] inputDateFormats = intialiseInputDateFormats(); private static DateFormat[] intialiseInputDateFormats() { DateFormat[] formats = { new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("yyyy/MM/dd"), new SimpleDateFormat("dd-MM-yyyy"), new SimpleDateFormat("dd/MM/yyyy") }; for (DateFormat df : formats) { df.setLenient(false); } return formats; } private final static DateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd"); @Override public int capture(int position, List<String> headers, List<String> values, JSONObject document) { String value = values.get(position); String safeValue = sanitizeValue(value); if (safeValue != null && !safeValue.isEmpty()) { fieldType.addValueToDocument(fieldName, safeValue, document); } return ++position; } private String sanitizeValue(String value) { if (value == null) return null; value = value.trim(); if (value.isEmpty()) return null; for (DateFormat df : inputDateFormats) { try { Date date = df.parse(value); return outputDateFormat.format(date); } catch (ParseException e) { //this is expected, } } return null; } @Override public int map(int position, List<Capture> captures, List<String> headers) { this.setCaptureInList(position, captures, headers.get(position)); return ++position; } }
25.489583
102
0.642419
910e5e524e72b2ca8a61e9d3aa625233cec3ab2b
1,172
package com.app.linio_app.Services.Firebase_Services; import android.content.Context; import android.support.annotation.NonNull; import com.app.linio_app.Services.ErrorDialogs; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class AccountReset { Context context; private FirebaseAuth auth = FirebaseAuth.getInstance(); private DatabaseReference database = FirebaseDatabase.getInstance().getReference(); public AccountReset(Context context) { this.context = context; } public void resetAccount(String email) { auth = FirebaseAuth.getInstance(); auth.sendPasswordResetEmail(email) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (!task.isSuccessful()) new ErrorDialogs(context).getFailedPasswordReset(); } }); } }
32.555556
101
0.697952
e5c2d63a1ce63818d89323c7c0a738cfbb5cc611
14,432
/* * Copyright (c) Ovidiu Serban, [email protected] * web:http://ovidiu.roboslang.org/ * All Rights Reserved. Use is subject to license terms. * * This file is part of AgentSlang Project (http://agent.roboslang.org/). * * AgentSlang is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License and CECILL-B. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * The CECILL-B license file should be a part of this project. If not, * it could be obtained at <http://www.cecill.info/>. * * The usage of this project makes mandatory the authors citation in * any scientific publication or technical reports. For websites or * research projects the AgentSlang website and logo needs to be linked * in a visible area. */ package org.agent.slang.in.facereader; import javolution.xml.stream.XMLStreamException; import org.jdesktop.swingx.JXStatusBar; import org.jdesktop.swingx.JXTaskPane; import org.jdesktop.swingx.JXTaskPaneContainer; import org.jdesktop.swingx.VerticalLayout; import javax.swing.*; import javax.swing.event.EventListenerList; import java.awt.*; import java.awt.event.*; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.EventListener; interface FaceReaderConnectionListener extends EventListener { void onFaceReaderConnection(FaceReaderReceiver receiver, FaceReaderSender sender); } /** * @author Sami Boukortt, [email protected] * @version 1, 5/28/15 */ public class GUI extends JFrame implements ClassificationListener, ResponseMessageListener { private final Object socketLock = new Object(); private Socket socket; private FaceReaderReceiver receiver; private FaceReaderSender sender; private final JLabel statusMessage = new JLabel(); private final JTextField addressField = new JTextField(); private final JSpinner portSpinner = new JSpinner(); private final JComboBox<String> stimulusList = new JComboBox<>(); private final JComboBox<String> eventMarkerList = new JComboBox<>(); private final JTextArea stateLog = new JTextArea(); private final JTextArea detailedLog = new JTextArea(); private final EventListenerList listeners = new EventListenerList(); private final JCheckBox stateLogCheckBox = new JCheckBox("State log"); private final JCheckBox detailedLogCheckBox = new JCheckBox("Detailed log"); public void addFaceReaderConnectionListener(FaceReaderConnectionListener listener) { listeners.add(FaceReaderConnectionListener.class, listener); } public void removeFaceReaderConnectionListener(FaceReaderConnectionListener listener) { listeners.remove(FaceReaderConnectionListener.class, listener); } private Action createAction(String label, final ActionMessage message) { Action action = new AbstractAction() { @Override public void actionPerformed(ActionEvent event) { sendMessage(message); } }; action.putValue(Action.NAME, label); return action; } private void sendMessage(final ActionMessage message) { new Thread(new Runnable() { @Override public void run() { try { synchronized (socketLock) { sender.sendActionMessage(message); } } catch (XMLStreamException | IOException e) { updateStatusMessage(String.format("%s: %s", e.getClass().getSimpleName(), e.getLocalizedMessage())); } } }).start(); } public GUI() { setTitle("FaceReader"); setLayout(new BorderLayout()); //region the status bar JXStatusBar statusBar = new JXStatusBar(); statusBar.add(statusMessage); add(statusBar, BorderLayout.PAGE_END); //endregion //region the action panel on the right { JPanel actionPanel = new JXTaskPaneContainer(); actionPanel.setLayout(new VerticalLayout()); { JXTaskPane connectionPane = new JXTaskPane(); connectionPane.setTitle("Connection"); connectionPane.add(new JLabel("Address: ")); connectionPane.add(addressField); connectionPane.add(new JLabel("Port: ")); connectionPane.add(portSpinner); JButton connectButton = new JButton("Connect"); connectButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { new Thread(new Runnable() { @Override public void run() { try { connectTo(InetAddress.getByName(addressField.getText()), (Integer) portSpinner.getValue()); } catch (UnknownHostException e) { updateStatusMessage(String.format("Unknown host: %s", e.getLocalizedMessage())); } } }).start(); } }); connectionPane.add(connectButton); actionPanel.add(connectionPane); } { JXTaskPane analysisTasks = new JXTaskPane(); analysisTasks.setTitle("Analysis"); Action start = createAction("Start", ActionMessage.startAnalyzing()), stop = createAction("Stop", ActionMessage.stopAnalyzing()); analysisTasks.add(start); analysisTasks.add(stop); actionPanel.add(analysisTasks); } add(actionPanel, BorderLayout.EAST); } //endregion { JPanel centralPanel = new JPanel(); centralPanel.setLayout(new VerticalLayout()); //region the panel for selecting which logs to receive { JPanel receivePanel = new JPanel(); receivePanel.setLayout(new FlowLayout(FlowLayout.LEADING)); receivePanel.setBorder(BorderFactory.createTitledBorder("Receive:")); stateLogCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { sendMessage(ActionMessage.startStateLogSending()); } else if (e.getStateChange() == ItemEvent.DESELECTED) { sendMessage(ActionMessage.stopStateLogSending()); } } }); detailedLogCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { sendMessage(ActionMessage.startDetailedLogSending()); } else if (e.getStateChange() == ItemEvent.DESELECTED) { sendMessage(ActionMessage.stopDetailedLogSending()); } } }); receivePanel.add(stateLogCheckBox); receivePanel.add(detailedLogCheckBox); centralPanel.add(receivePanel); } //endregion //region the panel for scoring stimuli and event markers { JPanel stimuliAndEventMarkers = new JPanel(); stimuliAndEventMarkers.setLayout(new GridBagLayout()); stimuliAndEventMarkers.setBorder(BorderFactory.createTitledBorder("Stimuli and Event Markers")); GridBagConstraints textConstraints = new GridBagConstraints(), comboBoxConstraints = new GridBagConstraints(), buttonConstraints = new GridBagConstraints(); textConstraints.gridx = 0; textConstraints.gridy = 0; textConstraints.anchor = GridBagConstraints.LINE_END; comboBoxConstraints.gridx = 1; comboBoxConstraints.gridy = 0; comboBoxConstraints.weightx = 1; comboBoxConstraints.fill = GridBagConstraints.HORIZONTAL; buttonConstraints.gridx = 2; buttonConstraints.gridy = 0; stimuliAndEventMarkers.add(new JLabel("Stimuli: "), textConstraints); stimuliAndEventMarkers.add(stimulusList, comboBoxConstraints); JButton refreshStimuliButton = new JButton("Refresh list"); refreshStimuliButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendMessage(ActionMessage.getStimuli()); } }); stimuliAndEventMarkers.add(refreshStimuliButton, buttonConstraints); JButton scoreStimulusButton = new JButton("Score stimulus"); scoreStimulusButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendMessage(ActionMessage.scoreStimulus((String) stimulusList.getSelectedItem())); } }); ++buttonConstraints.gridx; stimuliAndEventMarkers.add(scoreStimulusButton); ++textConstraints.gridy; ++comboBoxConstraints.gridy; ++buttonConstraints.gridy; buttonConstraints.gridx = 2; stimuliAndEventMarkers.add(new JLabel("Event markers: "), textConstraints); stimuliAndEventMarkers.add(eventMarkerList, comboBoxConstraints); JButton refreshEventMarkersButton = new JButton("Refresh list"); refreshEventMarkersButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendMessage(ActionMessage.getEventMarkers()); } }); stimuliAndEventMarkers.add(refreshEventMarkersButton, buttonConstraints); JButton scoreEventMarkerButton = new JButton("Score event marker"); scoreEventMarkerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendMessage(ActionMessage.scoreEventMarker((String) eventMarkerList.getSelectedItem())); } }); ++buttonConstraints.gridx; stimuliAndEventMarkers.add(scoreEventMarkerButton, buttonConstraints); centralPanel.add(stimuliAndEventMarkers); } //endregion //region the panel that displays the logs { JPanel logPanel = new JPanel(); logPanel.setLayout(new VerticalLayout()); JPanel stateLogPanel = new JPanel(); stateLogPanel.setLayout(new VerticalLayout()); stateLogPanel.setBorder(BorderFactory.createTitledBorder("State log")); stateLog.setEditable(false); stateLog.setLineWrap(true); stateLogPanel.add(stateLog); JPanel detailedLogPanel = new JPanel(); detailedLogPanel.setLayout(new VerticalLayout()); detailedLogPanel.setBorder(BorderFactory.createTitledBorder("Detailed log")); detailedLog.setEditable(false); detailedLog.setLineWrap(true); detailedLogPanel.add(detailedLog); logPanel.add(stateLogPanel); logPanel.add(detailedLogPanel); centralPanel.add(logPanel); } //endregion add(centralPanel, BorderLayout.CENTER); } pack(); setMinimumSize(getPreferredSize()); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { try { if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }); } private void updateStatusMessage(final String message) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { statusMessage.setText(message); } }); } public void connectTo(final InetAddress address, final int port) { final GUI that = this; new Thread(new Runnable() { @Override public void run() { synchronized (socketLock) { if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { addressField.setText(address.getHostAddress()); portSpinner.setModel(new SpinnerNumberModel(port, 0, 65535, 1)); for (JCheckBox logCheckBox: new JCheckBox[] {stateLogCheckBox, detailedLogCheckBox}) { ItemListener[] listeners = logCheckBox.getItemListeners(); for (ItemListener listener: listeners) { logCheckBox.removeItemListener(listener); } logCheckBox.setSelected(false); for (ItemListener listener: listeners) { logCheckBox.addItemListener(listener); } } } }); try { socket = new Socket(address, port); receiver = new FaceReaderReceiver(socket.getInputStream()); sender = new FaceReaderSender(socket.getOutputStream()); } catch (IOException e) { updateStatusMessage(String.format("IOException: %s", e.getLocalizedMessage())); return; } receiver.addClassificationListener(that); receiver.addResponseMessageListener(that); new Thread(receiver).start(); updateStatusMessage(String.format("Connected to FaceReader ([%s]:%d).", address, port)); } for (FaceReaderConnectionListener listener: listeners.getListeners(FaceReaderConnectionListener.class)) { listener.onFaceReaderConnection(receiver, sender); } } }).start(); } @Override public void onClassification(Classification classification) { switch (classification.getLogType()) { case StateLog: stateLog.setText(classification.toString()); break; case DetailedLog: detailedLog.setText(classification.toString()); break; } } @Override public void onResponseMessage(final ResponseMessage message) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { switch (message.type) { case FaceReader_Sends_Error: updateStatusMessage(String.format("Error: %s", message.information)); break; case FaceReader_Sends_Success: updateStatusMessage(message.information.toString()); break; case FaceReader_Sends_Stimuli: updateStatusMessage(""); stimulusList.setModel(new DefaultComboBoxModel<>(message.information.toArray(new String[message.information.size()]))); break; case FaceReader_Sends_EventMarkers: updateStatusMessage(""); eventMarkerList.setModel(new DefaultComboBoxModel<>(message.information.toArray(new String[message.information.size()]))); break; } } }); } public static void main(String[] arguments) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException ignored) {} GUI gui = new GUI(); gui.connectTo(InetAddress.getLoopbackAddress(), 9090); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.setVisible(true); } }); } }
31.579869
129
0.713345
0e86254acd4dbe79045bc7c640521ac294dfc3e5
863
package org.vibioh.spring.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.vibioh.ioc.Operation; import org.vibioh.ioc.Reader; import org.vibioh.ioc.Writer; import org.vibioh.spring.Process; import java.io.IOException; import java.util.logging.Level; @Component public class ProcessImpl<I> implements Process { @Autowired private Reader<I> reader; @Autowired private Operation<I, Object> operation; @Autowired private Writer<Object> writer; @Override public int execute() { try { writer.write(operation.compute(reader.read().orElse(null)).orElse(null)); return 0; } catch (final IOException e) { getLogger().log(Level.SEVERE, "Something went wrong", e); return 1; } } }
25.382353
85
0.68482
ad4537068c80224fd92a7c17a46c2f7c04551efd
2,837
/** * */ package com.cas.circuit; import com.cas.circuit.consts.ServoConst; /** * @author 张振宇 2015年10月9日 下午3:28:16 */ public final class PulseLong implements Comparable<PulseLong> { private int resolution; private long boutCount; // a bout count 一转信号个数 private int minorCount; /** * */ public PulseLong() { this(ServoConst.RESOLUTION); } /** * */ public PulseLong(int resolution) { this.resolution = resolution; } public final void addPulse() { minorCount++; if (minorCount == resolution) { boutCount++; minorCount = 0; } } /** * */ public final void confirm() { // System.out.println("PulseLong.confirm(boutCount" + boutCount + ", minorCount" + minorCount + ")"); } /** * @return the aBoutCount */ public long getBoutCount() { return boutCount; } /** * @param boutCount the aBoutCount to set */ public void setBoutCount(long boutCount) { this.boutCount = boutCount; } /** * @return the minorCount */ public int getMinorCount() { return minorCount; } /** * @param minorCount the minorCount to set */ public void setMinorCount(int minorCount) { this.minorCount = minorCount; } /** * @return the resolution */ public int getResolution() { return resolution; } // // /* // * (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // return super.hashCode(); //// final int prime = 31; //// int result = 1; //// result = prime * result + (int) (boutCount ^ (boutCount >>> 32)); //// result = prime * result + minorCount; //// result = prime * result + resolution; //// return result; // } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!(obj instanceof PulseLong)) { return false; } PulseLong other = (PulseLong) obj; if (boutCount != other.boutCount) { return false; } if (minorCount != other.minorCount) { return false; } if (resolution != other.resolution) { return false; } return true; } /* * (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(PulseLong obj) { if (obj == null) { return 1; } if (resolution != obj.resolution) { throw new RuntimeException("无法比较, 分辨率不统一"); } if (boutCount > obj.boutCount) { return 1; } if (boutCount < obj.boutCount) { return -1; } if (minorCount > obj.minorCount) { return 1; } if (minorCount < obj.minorCount) { return -1; } return 0; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "hashCode:" + hashCode() + "[圈数=" + boutCount + ", 剩脉冲数=" + minorCount + "]"; } }
17.842767
102
0.614734
3d55b341a5f0bf3f0704c3e19c25b6f74894533c
1,500
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.06.12 at 09:16:35 AM EDT // package com.vmware.vim25; /** * */ @SuppressWarnings("all") public class ArrayOfVirtualMachineMetadataManagerVmMetadataInput { private final static com.vmware.vim25.VirtualMachineMetadataManagerVmMetadataInput[] NULL_VIRTUAL_MACHINE_METADATA_MANAGER_VM_METADATA_INPUT_ARRAY = new com.vmware.vim25.VirtualMachineMetadataManagerVmMetadataInput[ 0 ] ; public com.vmware.vim25.VirtualMachineMetadataManagerVmMetadataInput[] VirtualMachineMetadataManagerVmMetadataInput; public com.vmware.vim25.VirtualMachineMetadataManagerVmMetadataInput[] getVirtualMachineMetadataManagerVmMetadataInput() { if ((VirtualMachineMetadataManagerVmMetadataInput) == null) { return (NULL_VIRTUAL_MACHINE_METADATA_MANAGER_VM_METADATA_INPUT_ARRAY); } return VirtualMachineMetadataManagerVmMetadataInput; } public void setVirtualMachineMetadataManagerVmMetadataInput(com.vmware.vim25.VirtualMachineMetadataManagerVmMetadataInput[] VirtualMachineMetadataManagerVmMetadataInput) { this.VirtualMachineMetadataManagerVmMetadataInput = VirtualMachineMetadataManagerVmMetadataInput; } }
44.117647
226
0.785333
8fd64122c0f5ac6773d68bae16caed40949b7922
4,974
package com.aurora.account.web; import com.aurora.account.model.Activity; import com.aurora.account.model.TempUser; import com.aurora.account.model.User; import com.aurora.account.service.ActivityService; import com.aurora.account.service.ApplicantService; import com.aurora.account.service.SecurityService; import com.aurora.account.service.UserService; import com.aurora.account.validator.ChangePassValidator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller public class UserController extends AbstractController { @Autowired private UserService userService; @Autowired private ChangePassValidator changePassValidator; @Autowired private ActivityService activityService; @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(Model model, String error, String logout) { if (error != null) { model.addAttribute("error", "Invalid Credentials!."); } if (logout != null) { model.addAttribute("message", "<div class='alert alert-info'>You have been logged out successfully.</div>"); } return "login"; } @RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET) public String welcome(Model model, String error403,String error404) { if(!setNav(model,0)){ return "redirect:/changepass?force"; } if(error403!=null) { model.addAttribute("message",contentgen.get403()); } else if(error404!=null) { model.addAttribute("message",contentgen.get404()); } else { model.addAttribute("message",contentgen.getNormal()); } return "welcome"; } @RequestMapping(value = "/changepass", method = RequestMethod.GET) public String changepass(Model model, String ok,String force) { model.addAttribute("changeForm", new TempUser()); if(force!=null){ model.addAttribute("message","You must change password!"); } else if(!setNav(model,4)){ return "redirect:/changepass?force"; } if (ok != null) { setNav(model,4); model.addAttribute("message", "<div class='alert alert-info'>password changed successfully.</div>"); } return "changepass"; } @RequestMapping(value = "/changepass", method = RequestMethod.POST) public String changepass(@ModelAttribute("changeForm") TempUser changeForm, BindingResult bindingResult, Model model) { User authUser = null; String currentUserName=getAuth(); authUser=userService.findByUsername(currentUserName); User tempUser=new User(); changePassValidator.validate(changeForm, authUser, bindingResult); if (bindingResult.hasErrors()) { setNav(model,4); return "changepass"; } tempUser.setUsername("tempUser"); tempUser.setOccupation(authUser.getOccupation()); tempUser.setPassword(changeForm.getPassword()); tempUser.setPasswordConfirm(changeForm.getPasswordConfirm()); tempUser.setId(authUser.getId()); tempUser.setUsername(authUser.getUsername()); Activity activity=new Activity(); activity.setUser_id(tempUser.getId()); activity.setActivity("password changed"); userService.save(tempUser); activityService.saveActivity(activity); return "redirect:/changepass?ok"; } @RequestMapping(value = "/profile", method = RequestMethod.GET) public String profile(Model model) { if(!setNav(model,4)){ return "redirect:/changepass?force"; } setProfile(model); return "profile"; } @RequestMapping(value = "/viewusers", method = RequestMethod.GET) public String viewusers(Model model) { if(!setNav(model,3)){ return "redirect:/changepass?force"; } String content="<form id='contact' method='POST' >"; List<User> users = userService.getAll(); for(User user : users) { contentgen.setGen(user.getUsername()); content+=(contentgen.getProfile()+"<hr><br>"); } content+="</form>"; model.addAttribute("content", content); return "viewusers"; } @RequestMapping("checkUserName") @ResponseBody public String checkUser(String username){ return String.valueOf(userService.availabaleUserName(username)); } }
29.258824
121
0.635304