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
8fb16efc03f49207fdfc8c9bb776490554a203ae
2,527
/** * Copyright 2017 Pivotal Software, 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 org.springframework.metrics.instrument.internal; import org.springframework.metrics.instrument.Clock; import org.springframework.metrics.instrument.Tag; import org.springframework.metrics.instrument.Timer; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; public abstract class AbstractTimer implements Timer { protected Clock clock; protected MeterId id; protected AbstractTimer(MeterId id, Clock clock) { this.clock = clock; this.id = id; } @Override public <T> T recordCallable(Callable<T> f) throws Exception { final long s = clock.monotonicTime(); try { return f.call(); } finally { final long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } @Override public <T> T record(Supplier<T> f) { final long s = clock.monotonicTime(); try { return f.get(); } finally { final long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } @Override public <T> Callable<T> wrap(Callable<T> f) { return () -> { final long s = clock.monotonicTime(); try { return f.call(); } finally { final long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } }; } @Override public void record(Runnable f) { final long s = clock.monotonicTime(); try { f.run(); } finally { final long e = clock.monotonicTime(); record(e - s, TimeUnit.NANOSECONDS); } } @Override public String getName() { return id.getName(); } @Override public Iterable<Tag> getTags() { return id.getTags(); } }
27.769231
75
0.60744
7b7e2be637dd8b11940f4fda3ff19393c3d8d2e9
2,190
package net.covers1624.wt.util; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.function.Predicate; /** * Created by covers1624 on 16/12/19. */ public class JarStripper { public static void stripJar(Path input, Path output, Predicate<Path> predicate) { if (Files.notExists(output)) { if (Files.notExists(output.getParent())) { Utils.sneaky(() -> Files.createDirectories(output.getParent())); } } if (Files.exists(output)) { Utils.sneaky(() -> Files.delete(output)); } try (FileSystem inFs = Utils.getJarFileSystem(input, true);// FileSystem outFs = Utils.getJarFileSystem(output, true)) { Path inRoot = inFs.getPath("/"); Path outRoot = outFs.getPath("/"); Files.walkFileTree(inRoot, new Visitor(inRoot, outRoot, predicate)); } catch (IOException e) { throw new RuntimeException(e); } } private static class Visitor extends SimpleFileVisitor<Path> { private final Path inRoot; private final Path outRoot; private final Predicate<Path> predicate; private Visitor(Path inRoot, Path outRoot, Predicate<Path> predicate) { this.inRoot = inRoot; this.outRoot = outRoot; this.predicate = predicate; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path outDir = outRoot.resolve(inRoot.relativize(dir).toString()); if (Files.notExists(outDir)) { Files.createDirectories(outDir); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path inFile, BasicFileAttributes attrs) throws IOException { Path rel = inRoot.relativize(inFile); Path outFile = outRoot.resolve(rel.toString()); if (predicate.test(rel)) { Files.copy(inFile, outFile); } return FileVisitResult.CONTINUE; } } }
33.692308
106
0.607306
42ee9abf4c381b8fda323c1a3469ab07a3590fda
530
package org.springframework.samples.petclinic.repository; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.samples.petclinic.model.Hotel; import org.springframework.stereotype.Repository; @Repository public interface HotelRepository extends CrudRepository<Hotel, Integer>{ @Query("select h from Hotel h where h.pet.id=?1") List<Hotel> findByPetId(int petId); Hotel findById(int hotelId); }
29.444444
73
0.790566
5ff2b7d0d0e5eb4fb9b4f79d6e5c1bc9d07b1a57
1,384
package com.adeptj.modules.data.mybatis.internal; import org.osgi.service.metatype.annotations.AttributeDefinition; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import static com.adeptj.modules.data.mybatis.api.MyBatisInfoProvider.DEFAULT_MYBATIS_CONFIG; @ObjectClassDefinition( name = "AdeptJ MyBatis Configuration", description = "AdeptJ MyBatis Configuration" ) public @interface MyBatisConfig { String DEFAULT_ENV_ID = "development"; @AttributeDefinition( name = "MyBatis Config XML Location", description = "Location of the MyBatis config xml file" ) String config_xml_location() default DEFAULT_MYBATIS_CONFIG; @AttributeDefinition( name = "Override Provider MyBatis Config XML Location", description = "Whether to override the MyBatis config xml location provided by MyBatisInfoProvider" ) boolean override_provider_config_xml_location(); @AttributeDefinition( name = "Disable MyBatis XML Configuration", description = "Whether to disable XML based MyBatis configuration" ) boolean disable_xml_configuration(); @AttributeDefinition( name = "MyBatis Environment Identifier", description = "MyBatis symbolic environment identifier" ) String environment_id() default DEFAULT_ENV_ID; }
34.6
111
0.726156
4d7fdaaec11e925d4937e89d98b721762367866c
2,923
package buildcraft.api.transport.pluggable; import javax.annotation.Nullable; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import buildcraft.api.core.InvalidInputDataException; import buildcraft.api.transport.pipe.IPipeHolder; public final class PluggableDefinition { public final ResourceLocation identifier; public final IPluggableNetLoader loader; public final IPluggableNbtReader reader; @Nullable public final IPluggableCreator creator; public PluggableDefinition(ResourceLocation identifier, IPluggableNbtReader reader, IPluggableNetLoader loader) { this.identifier = identifier; this.reader = reader; this.loader = loader; this.creator = null; } public PluggableDefinition(ResourceLocation identifier, @Nullable IPluggableCreator creator) { this.identifier = identifier; this.reader = creator; this.loader = creator; this.creator = creator; } public PipePluggable readFromNbt(IPipeHolder holder, EnumFacing side, NBTTagCompound nbt) { return reader.readFromNbt(this, holder, side, nbt); } public PipePluggable loadFromBuffer(IPipeHolder holder, EnumFacing side, PacketBuffer buffer) throws InvalidInputDataException { return loader.loadFromBuffer(this, holder, side, buffer); } @FunctionalInterface public interface IPluggableNbtReader { /** Reads the pipe pluggable from NBT. Unlike {@link IPluggableNetLoader} (which is allowed to fail and throw an * exception if the wrong data is given) this should make a best effort to read the pluggable from nbt, or fall * back to sensible defaults. */ PipePluggable readFromNbt(PluggableDefinition definition, IPipeHolder holder, EnumFacing side, NBTTagCompound nbt); } @FunctionalInterface public interface IPluggableNetLoader { PipePluggable loadFromBuffer(PluggableDefinition definition, IPipeHolder holder, EnumFacing side, PacketBuffer buffer) throws InvalidInputDataException; } @FunctionalInterface public interface IPluggableCreator extends IPluggableNbtReader, IPluggableNetLoader { @Override default PipePluggable loadFromBuffer(PluggableDefinition definition, IPipeHolder holder, EnumFacing side, PacketBuffer buffer) { return createSimplePluggable(definition, holder, side); } @Override default PipePluggable readFromNbt(PluggableDefinition definition, IPipeHolder holder, EnumFacing side, NBTTagCompound nbt) { return createSimplePluggable(definition, holder, side); } PipePluggable createSimplePluggable(PluggableDefinition definition, IPipeHolder holder, EnumFacing side); } }
37.961039
120
0.736572
761e365a8c861f1e5254659b87d6b45f141c714a
425
import java.util.Arrays; public class Traverse { public static void main(String[] args) { String s = "the sky is blue"; String[] strs = s.split(" "); String[] res = new String[strs.length]; int n = strs.length; n--; for(String str : strs ) { res[n--] = str; } String str = Arrays.toString(res).trim(); System.out.println(str); } }
23.611111
49
0.515294
3b2cde9cfa7f2b966100a3597ef627b900329c55
762
package com.lg.ble; /** * Create by laoge * on 2020/7/16 0016 */ class EventChannelConstant { public static int FOUND_DEVICES=1;//搜索到蓝牙设备 public static int START_SACN=2;//开始扫描 public static int STOP_SACN=3;//开始扫描 public static int STATE_CONNECTED=4;//蓝牙状态改变,连接上了蓝牙 public static int STATE_DISCONNECTED=5;//蓝牙状态改变,蓝牙连接断开 public static int GATT_SERVICES_DISCOVERED=6;//发现可用的蓝牙服务 public static int DOES_NOT_SUPPORT_UART=7;//服务或特征值不可用 public static int DATA_AVAILABLE=8;//收到蓝牙设备发送的数据 public static int BLUETOOTHOFF=9;//蓝牙关闭通知 public static int BLUETOOTHON=10;//蓝牙开启通知 public static int STATE_RECONNECTED=11;//蓝牙状态改变,重连上了之前的蓝牙,不需要发现服务 public static int SERVICE_CHARACTERISTICS=12;//发现服务及其子特征值 }
36.285714
70
0.734908
38dd3fc5ed0f938823cc7787e18b0846691c3ade
999
import java.awt.*; import java.util.ArrayList; import javax.swing.*; public class CalcFrame extends JFrame{ private CalcHandler handler; private CalcPanel panel; public ArrayList<JButton> numpad; public CalcFrame(CalcHandler handler){ numpad = new ArrayList<JButton>(); numpad.add(new JButton("1")); numpad.add(new JButton("2")); numpad.add(new JButton("3")); numpad.add(new JButton("4")); numpad.add(new JButton("5")); numpad.add(new JButton("6")); numpad.add(new JButton("7")); numpad.add(new JButton("8")); numpad.add(new JButton("9")); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(1000, 1000); this.add((panel = new CalcPanel(handler))); panel.setLayout(new GridLayout(3,3)); for(JButton b: numpad){ panel.add(b); } this.setVisible(true); this.handler = handler; } public CalcPanel getCalcPanel(){ return panel; } public ArrayList<JButton> getNumpad(){ return numpad; } }
24.975
49
0.660661
abacd63d620fadbe90d4ae1531f9c423c0514db8
209
package pl.redny.album.infrastructure.brainz.model; import lombok.Data; @Data public class BrainzArtistCredit { private String name; private BrainzArtist artist; private String joinphrase; }
13.933333
51
0.755981
cb4e16affee5cf00bf78364d6803b297c37ee9a6
3,288
package com.vmware.eucenablement.sample; import com.vmware.eucenablement.oauth.OAuth2Config; import com.vmware.eucenablement.oauth.impl.VIDMOAuth2Impl; import com.vmware.eucenablement.oauth.util.HttpRequest; import com.vmware.eucenablement.oauth.util.OAuthUtil; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * Created by chenzhang on 2017-08-25. */ public class VIDMServlet implements Servlet { private static Logger log = LoggerFactory.getLogger(VIDMServlet.class); public static final String APP_ID = "Sample_AppOAuth"; public static final String APP_SECRET = "bnDqMk8j25LeZLYgTr76KurM0lzpVBJ1cJHfJkGV2ECMOs7h"; public static final String REDIRECT_URI = "https://127.0.0.1:8443/WebApp/oauth"; @Override public void init(ServletConfig servletConfig) throws ServletException { } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { Request request=(Request)req; Response response=(Response)res; VIDMOAuth2Impl vidmoAuth2=getVIDMOAuth(request); String code=request.getParameter("code"); if (OAuthUtil.isStringNullOrEmpty(code)) { response.sendRedirect("userpage.jsp?errmsg="+ URLEncoder.encode("Return code is null!", "utf-8")); return; } try { vidmoAuth2.getAccessTokenFromOAuthServer(code); String username=vidmoAuth2.getUsername(), email=vidmoAuth2.getEmail(); request.getSession().setAttribute("username", username); request.getSession().setAttribute("email", email); response.sendRedirect("userpage.jsp"); } catch (Exception e) { response.sendRedirect("userpage.jsp?errmsg="+URLEncoder.encode(e.getMessage(), "utf-8")); } } @Override public String getServletInfo() { return null; } @Override public void destroy() { } public static VIDMOAuth2Impl getVIDMOAuth(HttpServletRequest req) { if (req==null) return null; HttpSession session=req.getSession(); VIDMOAuth2Impl vidmoAuth2=(VIDMOAuth2Impl)session.getAttribute("oauth"); if (vidmoAuth2==null) { vidmoAuth2=new VIDMOAuth2Impl(new OAuth2Config(APP_ID, APP_SECRET, REDIRECT_URI)); session.setAttribute("oauth", vidmoAuth2); } return vidmoAuth2; } public static boolean isValidHost(String host) { try { SslUtilities.trustAllCertificates(); //Trust all certificate in sample. This should be removed in a real production environment. return host!=null && HttpRequest.get(host+"/SAAS/API/1.0/GET/metadata/idp.xml").code()==200; } catch (Exception e) {return false;} } }
32.554455
137
0.700122
49eafb9771a6ea9f9e785a0fe736f0ddf806ae26
1,370
package com.RSen.Commandr.builtincommands; import android.content.Context; import android.content.Intent; import com.RSen.Commandr.R; import com.RSen.Commandr.core.MostWantedCommand; import com.RSen.Commandr.util.GoogleNowUtil; /** * Created by Daniel Quah on 11/10/2014. */ public class ThankYouGoogleCommand extends MostWantedCommand { private static String TITLE; private static String DEFAULT_PHRASE; public ThankYouGoogleCommand(Context ctx) { DEFAULT_PHRASE = ctx.getString(R.string.thank_you_google_phrase); TITLE = ctx.getString(R.string.thank_you_google_title); } @Override public void execute(final Context context, String predicate){ GoogleNowUtil.resetGoogleNow(context); GoogleNowUtil.returnPreviousApp(); } /** * It is enabled if the phone has a flash feature */ @Override public boolean isAvailable (Context context){ return true; } @Override public String getTitle () { return TITLE; } @Override public String getDefaultPhrase () { return DEFAULT_PHRASE; } // If this is disabled then it redirects users away from the Super User permission dialog. @Override public boolean isHandlingGoogleNowReset() { return true; } }
23.62069
94
0.664964
f8ae4aa51ace60fe7eddb01c5f9c04ec31b4ae26
1,224
package info.u250.c2d.engine; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.utils.Array; /** * Sometimes you may want to has muti layer of the scenes , that's what the {@link #SceneGroup()} do . * Such as a HUD scene on top of a Game scene . Its simply draw them together and all is up to you . * @author xjjdog */ public class SceneGroup extends Array<Scene> implements Scene { final private InputMultiplexer input = new InputMultiplexer(); @Override public void update(float delta) { for(Scene scene:this){ scene.update(delta); } } @Override public void render(float delta) { for(Scene scene:this){ scene.render(delta); } } @Override public void show() { for(Scene scene:this){ scene.show(); } } @Override public void hide() { for(Scene scene:this){ scene.hide(); } } @Override public InputProcessor getInputProcessor() { if(this.size>0){ input.clear(); for(int i=this.size-1;i>=0;i--){ if(null!=this.get(i).getInputProcessor()){ input.addProcessor(this.get(i).getInputProcessor()); } } return input; } return null; } }
21.473684
103
0.648693
cd41657c2d0d8f433acede9bebf13cea2213b9bb
3,786
/** * 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.camel.component.spring.integration.adapter.config; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.apache.camel.component.spring.integration.adapter.CamelTargetAdapter; import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.ConfigurationException; import org.springframework.integration.endpoint.HandlerEndpoint; import org.springframework.util.StringUtils; /** * Parser for the &lt;camelTarget/&gt; element * @author Willem Jiang * * @version $Revision$ */ public class CamelTargetAdapterParser extends AbstractCamelContextBeanDefinitionParaser { protected Class<?> getBeanClass(Element element) { return HandlerEndpoint.class; } protected boolean shouldGenerateId() { return false; } protected boolean shouldGenerateIdAsFallback() { return true; } protected void parseAttributes(Element element, ParserContext ctx, BeanDefinitionBuilder bean) { NamedNodeMap atts = element.getAttributes(); for (int i = 0; i < atts.getLength(); i++) { Attr node = (Attr) atts.item(i); String val = node.getValue(); String name = node.getLocalName(); if (!name.equals("requestChannel") && !name.equals("replyChannel")) { mapToProperty(bean, name, val); } } } protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { BeanDefinitionBuilder adapterDefBuilder = BeanDefinitionBuilder.rootBeanDefinition(CamelTargetAdapter.class); String requestChannel = element.getAttribute("requestChannel"); String replyChannel = element.getAttribute("replyChannel"); // Check the requestChannel if (!StringUtils.hasText(requestChannel)) { throw new ConfigurationException("The 'requestChannel' attribute is required."); } // Set the adapter bean's property parseAttributes(element, parserContext, adapterDefBuilder); parseCamelContext(element, parserContext, adapterDefBuilder); String adapterBeanName = parserContext.getReaderContext().generateBeanName(adapterDefBuilder.getBeanDefinition()); parserContext.registerBeanComponent(new BeanComponentDefinition(adapterDefBuilder.getBeanDefinition(), adapterBeanName)); builder.addConstructorArgReference(adapterBeanName); builder.addPropertyValue("inputChannelName", requestChannel); if (StringUtils.hasText(replyChannel)) { builder.addPropertyValue("outputChannelName", replyChannel); } } }
43.517241
129
0.741152
bb1d6c386ef64b5026b1bcb3089457d0c4e10bd7
4,148
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/firestore/admin/v1/field.proto package com.google.firestore.admin.v1; public final class FieldProto { private FieldProto() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_firestore_admin_v1_Field_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_firestore_admin_v1_Field_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_firestore_admin_v1_Field_IndexConfig_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_firestore_admin_v1_Field_IndexConfig_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n%google/firestore/admin/v1/field.proto\022" + "\031google.firestore.admin.v1\032%google/fires" + "tore/admin/v1/index.proto\032\034google/api/an" + "notations.proto\"\345\001\n\005Field\022\014\n\004name\030\001 \001(\t\022" + "B\n\014index_config\030\002 \001(\0132,.google.firestore" + ".admin.v1.Field.IndexConfig\032\211\001\n\013IndexCon" + "fig\0221\n\007indexes\030\001 \003(\0132 .google.firestore." + "admin.v1.Index\022\034\n\024uses_ancestor_config\030\002" + " \001(\010\022\026\n\016ancestor_field\030\003 \001(\t\022\021\n\trevertin" + "g\030\004 \001(\010B\270\001\n\035com.google.firestore.admin.v" + "1B\nFieldProtoP\001Z>google.golang.org/genpr" + "oto/googleapis/firestore/admin/v1;admin\242" + "\002\004GCFS\252\002\037Google.Cloud.Firestore.Admin.V1" + "\312\002\037Google\\Cloud\\Firestore\\Admin\\V1b\006prot" + "o3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.firestore.admin.v1.IndexProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), }, assigner); internal_static_google_firestore_admin_v1_Field_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_firestore_admin_v1_Field_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_firestore_admin_v1_Field_descriptor, new java.lang.String[] { "Name", "IndexConfig", }); internal_static_google_firestore_admin_v1_Field_IndexConfig_descriptor = internal_static_google_firestore_admin_v1_Field_descriptor.getNestedTypes().get(0); internal_static_google_firestore_admin_v1_Field_IndexConfig_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_firestore_admin_v1_Field_IndexConfig_descriptor, new java.lang.String[] { "Indexes", "UsesAncestorConfig", "AncestorField", "Reverting", }); com.google.firestore.admin.v1.IndexProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
48.8
97
0.731919
97a68864429cea90d845bf5b8d1e9db31ff0e57e
17,301
import java.util.Scanner; public class ChoiceDesert{ public static boolean drill; public static void main(String[] args) throws InterruptedException { Scanner s = new Scanner(System.in); boolean dead; int days, number; String gamOv = " GAME OVER"; System.out.println("You walk for days. \n This seems to be a promising route."); stop(1); System.out.println("You approach...an Oasis. They try to pull you in with their rock.\n Do you listen closer, L, or run away, R?"); char dUnCho = s.nextLine().charAt(0); days = (int)((Math.random())*10)+3; if (dUnCho == 'L') { //LIStEN CLOSER! //numChoice += 1; System.out.println("You approach the Oasis, and as you do, you realize your eardrums are bleeding. \n And then, you remember!"); stop(1); System.out.print("That's your..."); stop(1); System.out.println("wait no, memory gone. \n You keep approaching, until an unspoken ultimatum occurs: \n Search your inventory, I, or attempt to survive, S."); dUnCho = s.nextLine().charAt(0); if (dUnCho == 'I'){ //numChoice += 1; number = (int)(Math.random()*100); System.out.println(number); if (number <= 25){//SAX System.out.println("You look into your inventory, to find a sword. "); System.out.println("You approach to slay the band, but they overtake you! \n They surround you and invite you to their band, to sing with them."); System.out.println(gamOv); dead = true; }else if (number >= 26 && number <= 50){//DRAX drill = true; System.out.println("You look into your inventory to find a drill."); stop(1); System.out.println("You drill down and stumble upon some gold! \n Added to inventory. \n You keep drilling down, until you fall down and realize it was all a trap! Down there, an angry brother clones himself and surrounds you. Do you go back to surface, S, or go further down, D?"); dUnCho = s.nextLine().charAt(0); if (dUnCho == 'S'){ System.out.println("You drill back to the surface. However, the Oasis is still there. \n Your head begins to hurt."); System.out.println(gamOv); }else if (dUnCho == 'D'){ System.out.print("You drill down, and"); cave(false); }//DIG STRAIGHT DOWN }else if (number >= 51 && number <= 75){//VAX System.out.println("Looking in your inventory, you find something labeled a 'Memory Vaccine'. You inject the Epi-Pen looking device into your leg and voila! You feel a bit dizzy as your memories rush back, and you sit down on a ledge."); stop(1); System.out.println("Except...No. Something definitely isn't right. These aren't your memories, these are stock photos from Google. You look down at the bottle, and bright red text flashes, 'You didn't think it'd be that easy, did you?'"); stop(1); System.out.println("You fall off the ledge, unconscious"); cave(false); }else if (number >= 76 && number <= 100){//WAX System.out.println("You find wax!\nYou plug your ears and are now immune to the music. \n You keep going through the desert, and see a house in the distance. "); stop(1); System.out.println("You walk towards it."); house(); }//THE INVENTORY }//INVENTORY else if (dUnCho == 'S'){ number = (int)(Math.random()*100); System.out.println(number); if (number <= 50){ System.out.println("You keep listening, and you kinda like it. \n Then"); stop(1); System.out.println("BAM!"); System.out.println(gamOv); }else if (number >=100){ System.out.println("You realize your head hurts and you run past them. \n You see a house in the distance, and run to it."); house(); }//DIE OR SURVIVE? }//SURVIVE } else if (dUnCho == 'R') { //RUN AWAY! System.out.println("You leave the Oasis. Now out of water and nutrients, you have " + days + " days left to live."); System.out.println("But wait!"); stop(1); System.out.println("You..."); stop(1); System.out.print("you remember something."); stop(1); System.out.println("Something about...a house! \n A house in the desert! \n But where is it?"); stop(1); System.out.println("Looking around, you realize the sun is being blocked by something to the West."); stop(1); System.out.println("You can walk towards it, W, or go back to your hut, H."); dUnCho = s.nextLine().charAt(0); if (dUnCho == 'W'){ house(); } else if (dUnCho == 'H'){ Opening.opening(0); }//GO BIG OR GO HOME }//DESERT PAGE UNO CHOICES }//STATIC VOID public static void house() throws InterruptedException { char dDoCho; double number; Scanner s = new Scanner(System.in); System.out.println("You finally reach the house, but two men guard the doors."); stop(1); System.out.println("'One of us tells truth, the other tells lies.' \nYou ask 91/7, and the man on the right, R, says 13. \nThe man on the left, L, says 12. Which door do you go through?"); dDoCho = s.nextLine().charAt(0); if (dDoCho == 'R'){ System.out.println("Congratulations! You beat the game. "); stop(2); System.out.println("Just kidding! You've made it to a strange new world: The Console. This is your new home. Let's find your memories."); stop(1); System.out.println("Woah! Is that a dog? Wanna keep it? Y/N"); dDoCho = s.nextLine().charAt(0); if (dDoCho == 'Y'){ boolean dumb = true; System.out.println("He seems to be leading us somewhere! Let's follow him. \n What a...dark cave. \n Wait, it kinda smells like chlorofo-"); System.out.println("GAME OVER"); }else if (dDoCho == 'N'){ boolean noFun = true; System.out.print("Sad..."); stop(1); System.out.println("But understandable. We must keep searching. Now what is this...a locked door? \n We must have missed some type of key. Should we brute force, B, or go back, G?"); dDoCho = s.nextLine().charAt(0); if (dDoCho == 'B'){ System.out.print("You smash against the door to..."); number = (Math.random()*10); if (number <= 5){ System.out.println("no avail."); System.out.println("That's ok, lets go back and look for the key. Look! A cave! Let's go explore."); cave(true); }else { System.out.println("success!"); boss(); } }else if (dDoCho == 'G'){ System.out.println("Hey, it looks like there's a cave over there! Let's go explore."); cave(true); } }else if (dDoCho == 'L'){ System.out.println("Oh no! You've fallen and you can't get up! 2 choices: Get up or die. \n But I get to choose... "); stop(1); number = (Math.random()*10); if (number == 4.379795454379471 || number == 1){ System.out.println("Wtf...you survived. Sorry, pardon my french. It's just...\n I Didn't expect for this to happen. There was a 2 in 27,000,000,000,000,000 chance that this would happen. Anyways, \n HACKER"); System.out.println("GAME un-OVER?"); } else { System.out.println("Sorry, you died. \n GAME OVER"); } } } }//HOUSE METHOD public static void cave(boolean door) throws InterruptedException { Scanner s = new Scanner(System.in); if (door){ System.out.println("What's that?"); }else if (!door){ int decisive = (int)(Math.random()*10); if (decisive <=5){ System.out.println("You fall, unconscious, down a dark cave and splash into an underground river."); System.out.println("Wow! I can't believe we survived that! \n Let's explore the cave. What's that?"); }else if (decisive >= 6){ System.out.println("GAME OVER"); System.exit(0); } } System.out.println("It appears to be...some kind of KEY_TOKEN left here by the devs."); stop(1); System.out.println("Who are the devs? To be honest, I have no idea. But I assume they're the ones who took...you know what."); boolean key = true; System.out.println("Anyways, let's move on and find the lock to this key."); System.out.println("You Move forwards and approach a dead end. Check your inventory, maybe you picked something up."); if (drill){ System.out.println("It's the gold! You craft a golden pickaxe and break down the wall."); }else { System.out.println("Nothing in your inventory... maybe look around? Look- a fallen drill! Maybe we can use that."); } System.out.println("The wall breaks! Behind it is some sort of...old door. Very thick, and mossy, and a hard wood. \n Oh wait! There's a lock that seems to fit our key, K. Let's try it!"); char dTrCho = s.nextLine().charAt(0); if (dTrCho == 'k' || dTrCho == 'K'){ if (key){ System.out.println("creeeeaaaaaakkk"); stop(1); System.out.println("The door opened! Oh my! It's a boss fight. Press A to attack."); System.out.print("You have 50/50 health, while the boss...this..."); stop(1); System.out.println("CompSci teacher has...150/150??"); System.out.println("Again, click A to fight."); dTrCho = s.nextLine().charAt(0); if (dTrCho == 'a' || dTrCho == 'A'){ System.out.println("You swing, and hit! He is now at 100 health. However, he hits you with his usual move-- A LONG ASSIGNMENT!!!! \n DUHN DUHN DUHHHHHHN \n Do you...dodge, D, or attack back, A?"); dTrCho = s.nextLine().charAt(0); switch(dTrCho){ case 'D': System.out.println("You dodge, and just barely survive. \n Stats: \n You: 35/50 \n That...evil thing: 75/150."); stop(1); System.out.println("Turning around, you leap forwards and immediatly obfuscate your code, making his job 100 times harder...wait no! \n He's using an online deobfuscator! He jumps forwards, already done grading. You, my friend, are done for. I'll see you on the other side."); System.out.println("GAME OVER: Made it all this way, just to die. Pathetic. Play again to win."); break; case 'A': System.out.println("You attack back, and you hit him! He staggers back, dazed by your blow! \n"); System.out.println("Stats: \n You: 45/50 \n CompSci Teacher: 50/100 \n He hits you with his final move..."); stop(2); System.out.println("A text-adventure project."); stop(1); System.out.println("You fall down, now at 25 health. You get back up and hit one more time, \n and you knock him backwards, taking your code from StackOverflow. He falls down, dropping a FizzBuzz script from an interview, and another script, that holds your memories. \n Click D to claim and continue."); dTrCho = s.nextLine().charAt(0); switch(dTrCho){ case 'D': System.out.println("Your memories! You found them. Well, I guess this is it. Goodbye!"); System.out.println("GAME OVER: The 2 in 27,000,000,000,000,000. You win."); break; case 'F': fizzbuzz.main(new String[0]); System.out.println("Oh..I guess it works? Idk, anyways, let's go, we lost the memories so you work for the devs now. \n I hear he's a CompSci 2 student now."); System.out.println("GAME OVER: What an idiot. The devs already know who you are. \n We will reach out shortly ;)."); break; } break; } } }else if (!key){ System.out.println("Begone, Hacker! Only real players get to play."); } } }//CAVE METHOD public static void boss() throws InterruptedException { char dQuCho; Scanner s = new Scanner(System.in); System.out.println("creeeeaaaaaakkk"); stop(1); System.out.println("The door opened! Oh my! It's a boss fight. Press A to attack."); System.out.print("You have 50/50 health, while the boss...this..."); stop(1); System.out.println("CompSci teacher has...150/150??"); System.out.println("Again, click A to fight."); dQuCho = s.nextLine().charAt(0); if (dQuCho == 'a' || dQuCho == 'A'){ System.out.println("You swing, and hit! He is now at 100 health. However, he hits you with his usual move-- A LONG ASSIGNMENT!!!! \n DUHN DUHN DUHHHHHHN \n Do you...dodge, D, or attack back, A?"); dQuCho = s.nextLine().charAt(0); switch(dQuCho){ case 'D': System.out.println("You dodge, and just barely survive. \n Stats: \n You: 35/50 \n That...evil thing: 75/150."); stop(1); System.out.println("Turning around, you leap forwards and immediatly obfuscate your code, making his job 100 times harder...wait no! \n He's using an online deobfuscator! He jumps forwards, already done grading. You, my friend, are done for. I'll see you on the other side."); System.out.println("GAME OVER: Made it all this way, just to die. Pathetic. Play again to win."); break; case 'A': System.out.println("You attack back, and you hit him! He staggers back, dazed by your blow! \n"); System.out.println("Stats: \n You: 45/50 \n CompSci Teacher: 50/100 \n He hits you with his final move..."); stop(2); System.out.println("A text-adventure project."); stop(1); System.out.println("You fall down, now at 25 health. You get back up and hit one more time, \n and you knock him backwards, taking your code from StackOverflow. He falls down, dropping a script, that holds your memories. \n Click D to claim and continue."); dQuCho = s.nextLine().charAt(0); switch(dQuCho){ case 'D': System.out.println("Your memories! You found them. Well, I guess this is it. Goodbye!"); System.out.println("GAME OVER: The 2 in 27,000,000,000,000,000. You win."); break; } } } }//bossroom public static void stop(int ms) throws InterruptedException { Thread.sleep((ms * 1000)); } }//PUBLIC CLASS
62.233813
333
0.508121
6fb2671d8b9fde15f36aef4fa74c431c80dd0cee
2,827
package com.daedafusion.sf; import com.daedafusion.sf.config.ManagedObjectDescription; import com.daedafusion.sf.config.ServiceConfiguration; import com.daedafusion.sf.impl.DefaultServiceRegistry; import com.daedafusion.sf.Base64Encoder; import org.apache.commons.codec.binary.Base64; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; /** * Created by mphilpot on 7/2/14. */ public class BasicTest { private static final Logger log = LogManager.getLogger(BasicTest.class); @Test public void main() throws ServiceFrameworkException { // Construct manually ServiceFramework sf = new ServiceFramework(); ServiceRegistry registry = new DefaultServiceRegistry(); registry.setServiceConfiguration(buildConfig()); sf.setServiceRegistry(registry); sf.start(); // Theoretically done by ServletContextListener in a service Base64Encoder encoder = sf.getService(Base64Encoder.class); assertThat(encoder, is(notNullValue())); String test = "This is a test of the emergency broadcast system"; String encoded = encoder.encode(test.getBytes()); assertThat(test, is(not(encoded))); String base = Base64.encodeBase64String(test.getBytes()); assertThat(encoded, is(base)); sf.stop(); try { Base64Encoder tmp = sf.getService(Base64Encoder.class); fail("Exception should have been thrown"); } catch(ServiceFrameworkException e) { // Pass } sf.teardown(); // Factory needs to be notified of this... } private ServiceConfiguration buildConfig() { ServiceConfiguration config = new ServiceConfiguration(); ManagedObjectDescription sd = new ManagedObjectDescription(); sd.setImplClass("com.daedafusion.sf.impl.Base64EncoderServiceImpl"); sd.setInfClass("com.daedafusion.sf.Base64Encoder"); config.getManagedObjectDescriptions().add(sd); ManagedObjectDescription pd = new ManagedObjectDescription(); pd.setImplClass("com.daedafusion.sf.providers.impl.ApacheCommonsCodecProvider"); pd.setInfClass("com.daedafusion.sf.providers.Base64EncoderProvider"); config.getManagedObjectDescriptions().add(pd); config.compile(); return config; } @Test public void testConventionFallback() { ManagedObjectDescription mod = new ManagedObjectDescription(); mod.setInfClass("com.test.framework.MyService"); assertThat(mod.getImplClass(), is("com.test.framework.impl.MyServiceImpl")); } }
30.074468
88
0.695437
ba9628fdfcc9a3ddeffc4e0561d6b72c4ed3895a
9,685
package org.apache.helix.tools.commandtools; /* * 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. */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.helix.PropertyKey; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.manager.zk.ZNRecordSerializer; import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory; import org.apache.helix.zookeeper.api.client.HelixZkClient; import org.apache.helix.tools.ClusterExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier; import org.apache.helix.tools.ClusterVerifiers.ClusterLiveNodesVerifier; import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * collection of test utilities for integration tests */ public class IntegrationTestUtil { private static Logger LOG = LoggerFactory.getLogger(IntegrationTestUtil.class); public static final long DEFAULT_TIMEOUT = 30 * 1000; // in milliseconds public static final String help = "help"; public static final String zkSvr = "zkSvr"; public static final String timeout = "timeout"; public static final String verifyExternalView = "verifyExternalView"; public static final String verifyLiveNodes = "verifyLiveNodes"; public static final String readZNode = "readZNode"; public static final String readLeader = "readLeader"; public static final String verifyClusterState = "verifyClusterState"; final HelixZkClient _zkclient; final ZNRecordSerializer _serializer; final long _timeoutValue; public IntegrationTestUtil(HelixZkClient zkclient, long timeoutValue) { _zkclient = zkclient; _timeoutValue = timeoutValue; _serializer = new ZNRecordSerializer(); } public void verifyExternalView(String[] args) { if (args == null || args.length == 0) { System.err.println("Illegal arguments for " + verifyExternalView); return; } String clusterName = args[0]; List<String> liveNodes = new ArrayList<String>(); for (int i = 1; i < args.length; i++) { liveNodes.add(args[i]); } ClusterExternalViewVerifier verifier = new ClusterExternalViewVerifier(_zkclient, clusterName, liveNodes); boolean success = verifier.verifyByPolling(_timeoutValue); System.out.println(success ? "Successful" : "Failed"); if (!success) { System.exit(1); } } public void verifyClusterState(String[] args) { if (args == null || args.length == 0) { System.err.println("Illegal arguments for " + verifyExternalView); return; } String clusterName = args[0]; ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_zkclient).build(); boolean success = clusterVerifier.verify(_timeoutValue); System.out.println(success ? "Successful" : "Failed"); if (!success) { System.exit(1); } } public void verifyLiveNodes(String[] args) { if (args == null || args.length == 0) { System.err.println("Illegal arguments for " + verifyLiveNodes); return; } String clusterName = args[0]; List<String> liveNodes = new ArrayList<String>(); for (int i = 1; i < args.length; i++) { liveNodes.add(args[i]); } ClusterLiveNodesVerifier verifier = new ClusterLiveNodesVerifier(_zkclient, clusterName, liveNodes); boolean success = verifier.verify(_timeoutValue); System.out.println(success ? "Successful" : "Failed"); if (!success) { System.exit(1); } } public void readZNode(String path) { ZNRecord record = _zkclient.readData(path, true); if (record == null) { System.out.println("null"); } else { System.out.println(new String(_serializer.serialize(record))); } } @SuppressWarnings("static-access") static Options constructCommandLineOptions() { Option helpOption = OptionBuilder.withLongOpt(help).withDescription("Prints command-line options information") .create(); Option zkSvrOption = OptionBuilder.hasArgs(1).isRequired(true).withArgName("zookeeperAddress") .withLongOpt(zkSvr).withDescription("Provide zookeeper-address").create(); Option timeoutOption = OptionBuilder.hasArgs(1).isRequired(true).withArgName("timeout") .withLongOpt(timeout).withDescription("Provide timeout (in ms)").create(); Option verifyExternalViewOption = OptionBuilder.hasArgs().isRequired(false).withArgName("clusterName node1 node2..") .withLongOpt(verifyExternalView).withDescription("Verify external-view").create(); Option verifyClusterStateOption = OptionBuilder.hasArgs().isRequired(false).withArgName("clusterName") .withLongOpt(verifyClusterState).withDescription("Verify Bestpossible ClusterState").create(); Option verifyLiveNodesOption = OptionBuilder.hasArg().isRequired(false).withArgName("clusterName node1, node2..") .withLongOpt(verifyLiveNodes).withDescription("Verify live-nodes").create(); Option readZNodeOption = OptionBuilder.hasArgs(1).isRequired(false).withArgName("zkPath").withLongOpt(readZNode) .withDescription("Read znode").create(); Option readLeaderOption = OptionBuilder.hasArgs(1).isRequired(false).withArgName("clusterName") .withLongOpt(readLeader).withDescription("Read cluster controller").create(); OptionGroup optGroup = new OptionGroup(); optGroup.setRequired(true); optGroup.addOption(verifyExternalViewOption); optGroup.addOption(verifyClusterStateOption); optGroup.addOption(verifyLiveNodesOption); optGroup.addOption(readZNodeOption); optGroup.addOption(readLeaderOption); Options options = new Options(); options.addOption(helpOption); options.addOption(zkSvrOption); options.addOption(timeoutOption); options.addOptionGroup(optGroup); return options; } static void printUsage(Options cliOptions) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setWidth(1000); helpFormatter.printHelp("java " + ClusterExternalViewVerifier.class.getName(), cliOptions); } static void processCommandLineArgs(String[] cliArgs) { CommandLineParser cliParser = new GnuParser(); Options cliOptions = constructCommandLineOptions(); CommandLine cmd = null; try { cmd = cliParser.parse(cliOptions, cliArgs); } catch (ParseException pe) { System.err.println("failed to parse command-line args: " + Arrays.asList(cliArgs) + ", exception: " + pe.toString()); printUsage(cliOptions); System.exit(1); } HelixZkClient.ZkClientConfig clientConfig = new HelixZkClient.ZkClientConfig(); clientConfig.setZkSerializer(new ZNRecordSerializer()); HelixZkClient zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(cmd.getOptionValue(zkSvr)), clientConfig); long timeoutValue = DEFAULT_TIMEOUT; if (cmd.hasOption(timeout)) { String timeoutStr = cmd.getOptionValue(timeout); try { timeoutValue = Long.valueOf(timeoutStr); } catch (NumberFormatException ex) { System.err.println( "Invalid timeout value " + timeoutStr + ". Using default value: " + timeoutValue); } } IntegrationTestUtil util = new IntegrationTestUtil(zkClient, timeoutValue); if (cmd != null) { if (cmd.hasOption(verifyExternalView)) { String[] args = cmd.getOptionValues(verifyExternalView); util.verifyExternalView(args); } else if (cmd.hasOption(verifyClusterState)) { String[] args = cmd.getOptionValues(verifyClusterState); util.verifyClusterState(args); } else if (cmd.hasOption(verifyLiveNodes)) { String[] args = cmd.getOptionValues(verifyLiveNodes); util.verifyLiveNodes(args); } else if (cmd.hasOption(readZNode)) { String path = cmd.getOptionValue(readZNode); util.readZNode(path); } else if (cmd.hasOption(readLeader)) { String clusterName = cmd.getOptionValue(readLeader); PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName); util.readZNode(keyBuilder.controllerLeader().getPath()); } else { printUsage(cliOptions); } } } public static void main(String[] args) { processCommandLineArgs(args); } }
37.10728
106
0.718121
44020f877256f8ffca71d618e09e20e6432bd954
765
package com.marondal.marondalgram.post.comment.bo; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.marondal.marondalgram.post.comment.dao.CommentDAO; import com.marondal.marondalgram.post.comment.model.Comment; @Service public class CommentBO { @Autowired private CommentDAO commentDAO; public int addComment(int postId, int userId, String userName, String content) { return commentDAO.insertComment(postId, userId, userName, content); } public List<Comment> getCommentList(int postId) { return commentDAO.selectCommentList(postId); } public int deleteCommentByPostId(int postId) { return commentDAO.deleteCommentByPostId(postId); } }
23.90625
81
0.792157
25d22ecd458a1cf3b2bbf26e636b42c363c27688
1,666
/* * Copyright 2019 Wultra s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getlime.security.powerauth.app.nextstep.converter; import io.getlime.security.powerauth.app.nextstep.repository.model.entity.UserContactEntity; import io.getlime.security.powerauth.lib.nextstep.model.entity.UserContactDetail; /** * Converter for user contacts. * * @author Roman Strobl, [email protected] */ public class UserContactConverter { /** * Convert user contact entity to detail. * @param contact User contact entity. * @return User contact detail. */ public UserContactDetail fromEntity(UserContactEntity contact) { final UserContactDetail contactDetail = new UserContactDetail(); contactDetail.setContactName(contact.getName()); contactDetail.setContactType(contact.getType()); contactDetail.setContactValue(contact.getValue()); contactDetail.setPrimary(contact.isPrimary()); contactDetail.setTimestampCreated(contact.getTimestampCreated()); contactDetail.setTimestampLastUpdated(contact.getTimestampLastUpdated()); return contactDetail; } }
37.863636
92
0.743097
69534ac756ab88ee3aa34b23cb5ad3d9145f3c6d
812
package org.gr1m.mc.mup.bugfix.mc118710.mixin; import com.mojang.authlib.GameProfile; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.world.World; import org.gr1m.mc.mup.bugfix.mc118710.IEntityPlayerSP; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @Mixin(EntityPlayerSP.class) public abstract class MixinEntityPlayerSP extends AbstractClientPlayer implements IEntityPlayerSP { @Shadow private void onUpdateWalkingPlayer() { } public MixinEntityPlayerSP(World worldIn, GameProfile playerProfile) { super(worldIn, playerProfile); } public void updateWalkingPlayer() { this.onUpdateWalkingPlayer(); } }
30.074074
100
0.742611
b60059b32cca22f2721d0699c18f390c763bb575
2,683
/* * Copyright 2016 Ben Manes. 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.github.benmanes.caffeine.cache.simulator.parser; import static java.util.Objects.requireNonNull; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; import com.github.benmanes.caffeine.cache.simulator.policy.AccessEvent; import com.google.common.io.Closeables; /** * A skeletal implementation that reads the trace file as binary data. * * @author [email protected] (Ben Manes) */ public abstract class BinaryTraceReader extends AbstractTraceReader { protected BinaryTraceReader(String filePath) { super(filePath); } @Override @SuppressWarnings("PMD.CloseResource") public Stream<AccessEvent> events() { var input = new DataInputStream(readFile()); var stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize( new TraceIterator(input), Spliterator.ORDERED), /* parallel */ false); return stream.onClose(() -> Closeables.closeQuietly(input)); } /** Returns the next event from the input stream. */ protected abstract AccessEvent readEvent(DataInputStream input) throws IOException; private final class TraceIterator implements Iterator<AccessEvent> { final DataInputStream input; AccessEvent next; boolean ready; TraceIterator(DataInputStream input) { this.input = requireNonNull(input); } @Override public boolean hasNext() { if (ready) { return true; } try { next = readEvent(input); ready = true; return true; } catch (EOFException e) { return false; } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public AccessEvent next() { if (!hasNext()) { throw new NoSuchElementException(); } ready = false; return next; } } }
29.163043
85
0.712262
146ff37267eb3e3ec95d952039a67396df2abe92
320
import java.util.Scanner; public class Difference_Main { /** Main method */ public static void main(String[] args) { Difference absDiff = new Difference(); absDiff.setN(30); int absResult = absDiff.diff21(absDiff.getN()); System.out.println("The result of the absolute difference is : " + absResult); } }
20
80
0.703125
bab367b934c1ba87bdc6dbb95e8c533e40990c32
2,086
/* Copyright (c) 2014 Wolfgang Imig This file is part of the library "Java Add-in for Microsoft Office". This file must be used according to the terms of MIT License, http://opensource.org/licenses/MIT */ package com.wilutions.com; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; /** * This class is the base class for IDispatch implementations in Java. The * native library finds via reflection the implemented interfaces and makes them * available for COM - only IDispatch interfaces can be provide by a Java * object, VTBL interfaces are not supported (since they use a native function * pointer table). */ public class DispatchImpl implements IDispatch { /** * Internal pointer. This value is internally used as a pointer to * the corresponding native object. */ private long nptr; private final ConnectionPointContainer connectionPointContainer = new ConnectionPointContainer(); public DispatchImpl() { if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "DispatchImpl("); JoaDll.nativeInit(this); if (log.isLoggable(Level.FINE)) log.log(Level.FINE, ")DispatchImpl"); } public ConnectionPointContainer getConnectionPointContainer() { return connectionPointContainer; } public <T extends IUnknown> void _fireEvent(Class<T> listenerClass, Consumer<T> action) { ConnectionPoint<T> listeners = getConnectionPointContainer().findConnectionPoint(listenerClass); if (listeners != null) { listeners.forEach(action); } } public static void initLogger(String logFile, String logLevel, boolean append) { JoaDll.nativeInitLogger(logFile, logLevel, append); } public static void doneLogger() { JoaDll.nativeDoneLogger(); } public static void initCOM(Object module) throws ComException { JoaDll.nativeInitCOM(module); } public static void doneCOM() { JoaDll.nativeDoneCOM(); } public String toString() { return "[DispatchImpl " + Long.toHexString(nptr) + "]"; } private final static Logger log = Logger.getLogger("DispatchImpl"); }
28.575342
98
0.74209
c10d684239b81710a0840347c7544c37380ce81c
782
package easy.LengthOfLastWord; /** * @description: * 作者:LeetCode-Solution * 链接:https://leetcode-cn.com/problems/length-of-last-word/solution/zui-hou-yi-ge-dan-ci-de-chang-du-by-leet-51ih/ * 来源:力扣(LeetCode) * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 * @author: jefferyqjy * @datetime: 2021/10/4 16:31 */ public class OfficialSolution { /** * 官方的解法和MySolution中的解法二一样,只不过用while代替了for循环,在代码量上更简洁了一点 * * @param s * @return */ public int lengthOfLastWord(String s) { int index = s.length() - 1; while (s.charAt(index) == ' ') { index--; } int wordLength = 0; while (index >= 0 && s.charAt(index) != ' ') { wordLength++; index--; } return wordLength; } }
23
114
0.57289
10f24abea516f075058a2b45ef00d99510aa8478
56,780
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2007 Sun Microsystems, Inc. */ package org.netbeans.modules.cnd.dwarfdiscovery.provider; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.netbeans.api.project.Project; import org.netbeans.modules.cnd.api.remote.PathMap; import org.netbeans.modules.cnd.api.remote.RemoteSyncSupport; import org.netbeans.modules.cnd.api.toolchain.PredefinedToolKind; import org.netbeans.modules.cnd.api.utils.CndFileVisibilityQuery; import org.netbeans.modules.cnd.discovery.api.DiscoveryUtils; import org.netbeans.modules.cnd.discovery.api.DriverFactory; import org.netbeans.modules.cnd.discovery.api.ItemProperties; import org.netbeans.modules.cnd.discovery.api.ItemProperties.LanguageKind; import org.netbeans.modules.cnd.discovery.api.Progress; import org.netbeans.modules.cnd.discovery.api.ProjectProxy; import org.netbeans.modules.cnd.discovery.api.SourceFileProperties; import org.netbeans.modules.cnd.dwarfdump.source.Artifacts; import org.netbeans.modules.cnd.dwarfdump.source.CompileLineOrigin; import org.netbeans.modules.cnd.makeproject.api.configurations.ConfigurationDescriptorProvider; import org.netbeans.modules.cnd.makeproject.api.configurations.MakeConfiguration; import org.netbeans.modules.cnd.makeproject.api.configurations.MakeConfigurationDescriptor; import org.netbeans.modules.cnd.makeproject.spi.configurations.PkgConfigManager; import org.netbeans.modules.cnd.makeproject.spi.configurations.PkgConfigManager.PackageConfiguration; import org.netbeans.modules.cnd.makeproject.spi.configurations.PkgConfigManager.PkgConfig; import org.netbeans.modules.cnd.support.Interrupter; import org.netbeans.modules.cnd.utils.CndPathUtilities; import org.netbeans.modules.cnd.utils.MIMENames; import org.netbeans.modules.cnd.utils.MIMESupport; import org.netbeans.modules.cnd.utils.cache.CharSequenceUtils; import org.netbeans.modules.cnd.utils.cache.CndFileUtils; import org.netbeans.modules.nativeexecution.api.ExecutionEnvironment; import org.netbeans.modules.nativeexecution.api.ExecutionEnvironmentFactory; import org.netbeans.modules.nativeexecution.api.HostInfo; import org.netbeans.modules.nativeexecution.api.util.ConnectionManager.CancellationException; import org.netbeans.modules.nativeexecution.api.util.HostInfoUtils; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileSystem; import org.openide.util.Utilities; /** * */ public class MakeLogReader { private String workingDir; private String guessWorkingDir; private String baseWorkingDir; private final String root; private final FileObject logFileObject; private List<SourceFileProperties> result; private List<String> buildArtifacts; private Map<LanguageKind,Map<String,Integer>> buildTools; private final PathMap pathMapper; private final ProjectProxy project; private final CompilerSettings compilerSettings; private final RelocatablePathMapper localMapper; private final FileSystem fileSystem; private final RelocatablePathMapper.FS fs; private final Map<String,String> alreadyConverted = new HashMap<String,String>(); private final Set<String> C_NAMES; private final Set<String> CPP_NAMES; private final Set<String> FORTRAN_NAMES; private boolean isWindows = false; public MakeLogReader(FileObject logFileObject, String root, ProjectProxy project, RelocatablePathMapper relocatablePathMapper, FileSystem fileSystem) { if (root.length()>0) { this.root = CndFileUtils.normalizeAbsolutePath(fileSystem, root); } else { this.root = root; } this.logFileObject = logFileObject; this.project = project; this.pathMapper = getPathMapper(project); this.compilerSettings = new CompilerSettings(project); this.localMapper = relocatablePathMapper; this.fileSystem = fileSystem; fs = new FSImpl(fileSystem); C_NAMES = DiscoveryUtils.getCompilerNames(project, PredefinedToolKind.CCompiler); CPP_NAMES = DiscoveryUtils.getCompilerNames(project, PredefinedToolKind.CCCompiler); FORTRAN_NAMES = DiscoveryUtils.getCompilerNames(project, PredefinedToolKind.FortranCompiler); } private String convertPath(String path){ if (isPathAbsolute(path)) { String originalPath = path; String converted = alreadyConverted.get(path); if (converted != null) { return converted; } if(pathMapper != null) { String local = pathMapper.getLocalPath(path); if (local != null) { path = local; } } if (localMapper != null && fileSystem != null) { FileObject fo = fileSystem.findResource(path); if (fo == null || !fo.isValid()) { RelocatablePathMapper.ResolvedPath resolvedPath = localMapper.getPath(path); if (resolvedPath == null) { if (root != null) { if (localMapper.discover(fs, root, path)) { resolvedPath = localMapper.getPath(path); fo = fileSystem.findResource(resolvedPath.getPath()); if (fo != null && fo.isValid()) { path = fo.getPath(); } } } } else { fo = fileSystem.findResource(resolvedPath.getPath()); if (fo != null && fo.isValid()) { path = fo.getPath(); } } } else { RelocatablePathMapper.ResolvedPath resolvedPath = localMapper.getPath(fo.getPath()); if (resolvedPath == null) { if (root != null) { RelocatablePathMapper.FS fs = new FSImpl(fileSystem); if (localMapper.discover(fs, root, path)) { resolvedPath = localMapper.getPath(path); fo = fileSystem.findResource(resolvedPath.getPath()); if (fo != null && fo.isValid()) { path = fo.getPath(); } } } } else { path = fo.getPath(); fo = fileSystem.findResource(resolvedPath.getPath()); if (fo != null && fo.isValid()) { path = fo.getPath(); } } } } alreadyConverted.put(originalPath, path); } return path; } private PathMap getPathMapper(ProjectProxy project) { if (project != null) { Project p = project.getProject(); if (p != null) { // it won't now return null for local environment return RemoteSyncSupport.getPathMap(p); } } return null; } private ExecutionEnvironment getExecutionEnvironment(MakeConfiguration conf) { ExecutionEnvironment env = null; if (conf != null) { env = conf.getDevelopmentHost().getExecutionEnvironment(); } if (env == null) { env = ExecutionEnvironmentFactory.getLocal(); } return env; } private MakeConfiguration getConfiguration(ProjectProxy project) { if (project != null && project.getProject() != null) { ConfigurationDescriptorProvider pdp = project.getProject().getLookup().lookup(ConfigurationDescriptorProvider.class); if (pdp != null && pdp.gotDescriptor()) { MakeConfigurationDescriptor confDescr = pdp.getConfigurationDescriptor(); if (confDescr != null) { return confDescr.getActiveConfiguration(); } } } return null; } private void runImpl(Progress progress, CompileLineStorage storage) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "LogReader is run for {0}", logFileObject); //NOI18N } Pattern pattern = Pattern.compile(";|\\|\\||&&"); // ;, ||, && //NOI18N result = new ArrayList<SourceFileProperties>(); buildArtifacts = new ArrayList<String>(); buildTools = new HashMap<LanguageKind,Map<String,Integer>>(); buildTools.put(LanguageKind.C, new HashMap<String,Integer>()); buildTools.put(LanguageKind.CPP, new HashMap<String,Integer>()); buildTools.put(LanguageKind.Fortran, new HashMap<String,Integer>()); buildTools.put(LanguageKind.Unknown, new HashMap<String,Integer>()); if (logFileObject != null && logFileObject.isValid() && logFileObject.canRead()) { try { MakeConfiguration conf = getConfiguration(this.project); ExecutionEnvironment executionEnvironment = getExecutionEnvironment(conf); try { HostInfo hostInfo = HostInfoUtils.getHostInfo(executionEnvironment); if (hostInfo.getOSFamily() == HostInfo.OSFamily.WINDOWS) { isWindows = true; } } catch (CancellationException ex) { ex.printStackTrace(System.err); } PkgConfig pkgConfig = PkgConfigManager.getDefault().getPkgConfig(executionEnvironment, conf); BufferedReader in = new BufferedReader(new InputStreamReader(logFileObject.getInputStream())); long length = logFileObject.getSize(); long read = 0; int done = 0; if (length <= 0){ progress = null; } if (progress != null) { progress.start(100); } int nFoundFiles = 0; try { while(true){ if (isStoped.cancelled()) { break; } String line = in.readLine(); if (line == null){ break; } read += line.length()+1; line = line.trim(); while (line.endsWith("\\")) { // NOI18N String oneMoreLine = in.readLine(); if (oneMoreLine == null) { break; } line = line.substring(0, line.length() - 1) + " " + oneMoreLine.trim(); //NOI18N } line = trimBackApostropheCalls(line, pkgConfig); String[] cmds = pattern.split(line); for (int i = 0; i < cmds.length; i++) { if (parseLine(cmds[i].trim(), storage)){ nFoundFiles++; } } if (read*100/length > done && done < 100){ done++; if (progress != null) { progress.increment(null); } } } } finally { if (progress != null) { progress.done(); } } if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "Files found: {0}", nFoundFiles); //NOI18N DwarfSource.LOG.log(Level.FINE, "Files included in result: {0}", result.size()); //NOI18N } in.close(); } catch (IOException ex) { DwarfSource.LOG.log(Level.INFO, "Cannot read file "+logFileObject, ex); // NOI18N } } } public List<SourceFileProperties> getResults(Progress progress, Interrupter isStoped, CompileLineStorage storage) { if (result == null) { run(isStoped, progress, storage); } return result; } public List<String> getArtifacts(Progress progress, Interrupter isStoped, CompileLineStorage storage) { if (buildArtifacts == null) { run(isStoped, progress, storage); } return buildArtifacts; } public Map<LanguageKind,Map<String,Integer>> getTools(Progress progress, Interrupter isStoped, CompileLineStorage storage) { if (buildTools == null) { run(isStoped, progress, storage); } return buildTools; } private Interrupter isStoped; private void run(Interrupter isStoped, Progress progress, CompileLineStorage storage) { this.isStoped = isStoped; setWorkingDir(root); runImpl(progress, storage); if (subFolders != null) { subFolders.clear(); subFolders = null; findBase.clear(); findBase = null; } this.isStoped = null; } private final ArrayList<List<String>> makeStack = new ArrayList<List<String>>(); private int getMakeLevel(String line){ int i1 = line.indexOf('['); if (i1 > 0){ int i2 = line.indexOf(']'); if (i2 > i1) { String s = line.substring(i1+1, i2); try { int res = Integer.parseInt(s); return res; } catch (NumberFormatException ex) { } } } return -1; } private void enterMakeStack(String dir, int level){ if (level < 0) { return; } for(int i = makeStack.size(); i <= level; i++) { makeStack.add(new ArrayList<String>()); } List<String> list = makeStack.get(level); list.add(dir); } private boolean leaveMakeStack(String dir, int level) { if (level < 0) { return false; } if (makeStack.size() <= level) { return false; } List<String> list = makeStack.get(level); for(String s : list) { if (s.equals(dir)) { list.remove(s); return true; } } return false; } private List<String> getMakeTop(int level){ ArrayList<String> res = new ArrayList<String>(); for(int i = Math.min(makeStack.size(), level-1); i >=0; i--){ List<String> list = makeStack.get(i); if (list.size() > 0) { if (res.isEmpty()) { res.addAll(list); } else { if (list.size() > 1) { res.addAll(list); } } } } return res; } private static final String CURRENT_DIRECTORY = "Current working directory"; //NOI18N private static final String ENTERING_DIRECTORY = "Entering directory"; //NOI18N private static final String LEAVING_DIRECTORY = "Leaving directory"; //NOI18N private static final Pattern MAKE_DIRECTORY = Pattern.compile(".*make(?:\\.exe)?(?:\\[([0-9]+)\\])?: .*`([^']*)'$"); //NOI18N private boolean isEntered; private final Stack<Integer> relativesLevel = new Stack<Integer>(); private final Stack<String> relativesTo = new Stack<String>(); private void popPath() { if (relativesTo.size() > 1) { relativesTo.pop(); } } private String peekPath() { if (relativesTo.size() > 1) { return relativesTo.peek(); } return root; } private void popLevel() { if (relativesLevel.size() > 1) { relativesLevel.pop(); } } private Integer peekLevel() { if (relativesLevel.size() > 1) { return relativesLevel.peek(); } return 0; } private String convertWindowsRelativePath(String path) { if (Utilities.isWindows()) { if (path.startsWith("/") || path.startsWith("\\")) { // NOI18N if (path.length() > 3 && (path.charAt(2) == '/' || path.charAt(2) == '\\') && Character.isLetter(path.charAt(1))) { // MinGW path: //make[1]: Entering directory `/c/Test/qlife-qt4-0.9/build' path = ""+path.charAt(1)+":"+path.substring(2); // NOI18N } else if (path.startsWith("/cygdrive/")) { // NOI18N path = path.substring("/cygdrive/".length()); // NOI18N path = "" + path.charAt(0) + ':' + path.substring(1); // NOI18N } else { if (root.length()>1 && root.charAt(1)== ':') { path = root.substring(0,2)+path; } } } } return path; } private boolean checkDirectoryChange(String line) { String workDir = null, message = null; if (line.startsWith(CURRENT_DIRECTORY)) { workDir = convertPath(line.substring(CURRENT_DIRECTORY.length() + 1).trim()); workDir = convertWindowsRelativePath(workDir); if (DwarfSource.LOG.isLoggable(Level.FINE)) { message = "**>> by [" + CURRENT_DIRECTORY + "] "; //NOI18N } } else if (line.contains(ENTERING_DIRECTORY)) { String dirMessage = line.substring(line.indexOf(ENTERING_DIRECTORY) + ENTERING_DIRECTORY.length() + 1).trim(); workDir = convertPath(dirMessage.replaceAll("`|'|\"", "")); //NOI18N if (DwarfSource.LOG.isLoggable(Level.FINE)) { message = "**>> by [" + ENTERING_DIRECTORY + "] "; //NOI18N } workDir = convertWindowsRelativePath(workDir); baseWorkingDir = workDir; enterMakeStack(workDir, getMakeLevel(line)); } else if (line.contains(LEAVING_DIRECTORY)) { String dirMessage = line.substring(line.indexOf(LEAVING_DIRECTORY) + LEAVING_DIRECTORY.length() + 1).trim(); workDir = convertPath(dirMessage.replaceAll("`|'|\"", "")); //NOI18N workDir = convertWindowsRelativePath(workDir); if (DwarfSource.LOG.isLoggable(Level.FINE)) { message = "**>> by [" + LEAVING_DIRECTORY + "] "; //NOI18N } int level = getMakeLevel(line); if (leaveMakeStack(workDir, level)){ List<String> paths = getMakeTop(level); if (paths.size()== 1) { baseWorkingDir = paths.get(0); } else { // TODO: make is performed in several threads // algorithm should have guessing to select needed top of stack //System.err.println(""); } } else { // This is root or error //System.err.println(""); } } else if (line.startsWith(LABEL_CD)) { int end = line.indexOf(MAKE_DELIMITER); workDir = convertPath((end == -1 ? line : line.substring(0, end)).substring(LABEL_CD.length()).trim()); if (DwarfSource.LOG.isLoggable(Level.FINE)) { message = "**>> by [ " + LABEL_CD + "] "; //NOI18N } if (workDir.startsWith("/")){ // NOI18N workDir = convertWindowsRelativePath(workDir); baseWorkingDir = workDir; } } else if (line.startsWith("/") && !line.contains(" ")) { //NOI18N workDir = convertPath(line.trim()); workDir = convertWindowsRelativePath(workDir); if (DwarfSource.LOG.isLoggable(Level.FINE)) { message = "**>> by [just path string] "; //NOI18N } } else if (line.contains("make") && line.length() < 2000) { //NOI18N Matcher m = MAKE_DIRECTORY.matcher(line); boolean found = m.find(); if (found && m.start() == 0) { String levelString = m.group(1); int level = levelString == null ? 0 : Integer.parseInt(levelString); int baseLavel = peekLevel(); workDir = m.group(2); workDir = convertPath(workDir); workDir = convertWindowsRelativePath(workDir); if (level > baseLavel) { isEntered = true; relativesLevel.push(level); isEntered = true; } else if (level == baseLavel) { isEntered = !this.isEntered; } else { isEntered = false; popLevel(); } if (isEntered) { relativesTo.push(workDir); } else { popPath(); workDir = peekPath(); } } } if (workDir == null || workDir.length() == 0) { return false; } if (Utilities.isWindows() && CndFileUtils.isLocalFileSystem(fileSystem) && workDir.startsWith("/cygdrive/") && workDir.length()>11){ // NOI18N workDir = ""+workDir.charAt(10)+":"+workDir.substring(11); // NOI18N } if (workDir.charAt(0) == '/' || workDir.charAt(0) == '\\' || (workDir.length() > 1 && workDir.charAt(1) == ':')) { if ((fs.exists(workDir))) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE,message); } setWorkingDir(workDir); return true; } else { String netFile = fixNetHost(workDir); if (netFile != null) { setWorkingDir(netFile); } } } String dir = workingDir + CndFileUtils.getFileSeparatorChar(fileSystem) + workDir; if (fs.exists(dir)) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE,message); } setWorkingDir(dir); return true; } if (Utilities.isWindows() && CndFileUtils.isLocalFileSystem(fileSystem) && workDir.length()>3 && workDir.charAt(0)=='/' && workDir.charAt(2)=='/'){ String d = ""+workDir.charAt(1)+":"+workDir.substring(2); // NOI18N if (fs.exists(d)) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE,message); } setWorkingDir(d); return true; } } if (baseWorkingDir != null) { dir = baseWorkingDir + CndFileUtils.getFileSeparatorChar(fileSystem) + workDir; if (fs.exists(dir)) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE,message); } setWorkingDir(dir); return true; } } return false; } private String fixNetHost(String dir) { if (root.startsWith("/net/")) { // NOI18N int i = root.indexOf('/', 5); if (i > 0) { String localPath = root.substring(i); String prefix = root.substring(0,i); if (dir.startsWith(localPath)) { String netFile = prefix + dir; if (fs.exists(netFile)) { return netFile; } } } } return null; } /*package-local*/ enum CompilerType { CPP, C, FORTRAN, UNKNOWN; }; /*package-local*/ static class LineInfo { public String compileLine; public String compiler; public CompilerType compilerType = CompilerType.UNKNOWN; LineInfo(String line) { compileLine = line; } ItemProperties.LanguageKind getLanguage() { switch (compilerType) { case C: return ItemProperties.LanguageKind.C; case CPP: return ItemProperties.LanguageKind.CPP; case FORTRAN: return ItemProperties.LanguageKind.Fortran; case UNKNOWN: default: return ItemProperties.LanguageKind.Unknown; } } } private static final String LABEL_CD = "cd "; //NOI18N private static final String MAKE_DELIMITER = ";"; //NOI18N private String[] findCompiler(String line, Set<String> patterns, boolean checkExe){ for(String pattern : patterns) { int[] find = find(line, pattern); if (find != null) { return new String[]{pattern,line.substring(find[2])}; } if (checkExe) { find = find(line, pattern+".exe"); //NOI18N if (find != null) { return new String[]{pattern,line.substring(find[2])}; } } } return null; } private int[] find(String line, String pattern) { int fromIndex = 0; while(true) { int start = line.indexOf(pattern, fromIndex); if (start < 0) { return null; } fromIndex = start + 1; char prev = ' '; if (start > 0) { prev = line.charAt(start-1); } if (prev == ' ' || prev == '\t' || prev == '/' || prev == '\\' || prev == '"') { if (start + pattern.length() >= line.length()) { continue; } char next = line.charAt(start+pattern.length()); if (next == ' ' || next == '\t') { int binaryStart = start; if (prev == '/' || prev == '\\') { char first = prev; for(int i = start - 2; i >= 0; i--) { char c = line.charAt(i); if (c == ' ' || c == '\t') { break; } binaryStart = i; first = c; } if (first == '-') { continue; } } int end = start + pattern.length(); return new int[]{start,end, binaryStart}; } else if (next == '"' && prev == '"') { //NOI18N int end = start + pattern.length(); return new int[]{start,end, end+1}; } } } } /*package-local*/ LineInfo testCompilerInvocation(String line) { LineInfo li = new LineInfo(line); String[] compiler = findCompiler(line, C_NAMES, isWindows); if (compiler != null) { li.compilerType = CompilerType.C; li.compiler = compiler[0]; li.compileLine = compiler[1]; } else { compiler = findCompiler(line, CPP_NAMES, isWindows); if (compiler != null) { li.compilerType = CompilerType.CPP; li.compiler = compiler[0]; li.compileLine = compiler[1]; } else { compiler = findCompiler(line, FORTRAN_NAMES, isWindows); if (compiler != null) { li.compilerType = CompilerType.FORTRAN; li.compiler = compiler[0]; li.compileLine = compiler[1]; } } } return li; } private void setWorkingDir(String workingDir) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "**>> new working dir: {0}", workingDir); } this.workingDir = CndFileUtils.normalizeAbsolutePath(fileSystem, workingDir); } private void setGuessWorkingDir(String workingDir) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "**>> alternative guess working dir: {0}", workingDir); } this.guessWorkingDir = CndFileUtils.normalizeAbsolutePath(fileSystem, workingDir); } private boolean parseLine(String line, CompileLineStorage storage){ if (checkDirectoryChange(line)) { return false; } if (workingDir == null) { return false; } //if (!workingDir.startsWith(root)){ // return false; //} LineInfo li = testCompilerInvocation(line); if (li.compilerType != CompilerType.UNKNOWN) { gatherLine(li, storage); return true; } return false; } private static final String PKG_CONFIG_PATTERN = "pkg-config "; //NOI18N private static final String ECHO_PATTERN = "echo "; //NOI18N private static final String CYGPATH_PATTERN = "cygpath "; //NOI18N /*package-local*/ static String trimBackApostropheCalls(String line, PkgConfig pkgConfig) { int i = line.indexOf('`'); //NOI18N if (line.lastIndexOf('`') == i) { //NOI18N // do not trim unclosed `quotes` return line; } if (i < 0 || i == line.length() - 1) { return line; } else { StringBuilder out = new StringBuilder(); if (i > 0) { out.append(line.substring(0, i)); } line = line.substring(i+1); int j = line.indexOf('`'); //NOI18N if (j < 0) { return line; } String pkg = line.substring(0,j); if (pkg.startsWith(PKG_CONFIG_PATTERN)) { //NOI18N pkg = pkg.substring(PKG_CONFIG_PATTERN.length()); StringTokenizer st = new StringTokenizer(pkg); boolean readFlags = false; String findPkg = null; while(st.hasMoreTokens()) { String aPkg = st.nextToken(); if (aPkg.equals("--cflags")) { //NOI18N readFlags = true; continue; } if (aPkg.startsWith("-")) { //NOI18N readFlags = false; continue; } findPkg = aPkg; } if (readFlags && pkgConfig != null && findPkg != null) { PackageConfiguration pc = pkgConfig.getPkgConfig(findPkg); if (pc != null) { for(String p : pc.getIncludePaths()){ out.append(" -I").append(p); //NOI18N } for(String p : pc.getMacros()){ out.append(" -D").append(p); //NOI18N } out.append(" "); //NOI18N } } } else if (pkg.startsWith(CYGPATH_PATTERN)) { pkg = pkg.substring(CYGPATH_PATTERN.length()); int start = 0; for(int i1 = 0; i1 < pkg.length(); i1++) { char c = pkg.charAt(i1); if (c == ' ' || c == '\t') { start = i1; if (i1 + 1 < pkg.length() && pkg.charAt(i1 + 1) != '-') { break; } } } pkg = pkg.substring(start).trim(); if (pkg.startsWith("'") && pkg.endsWith("'")) { //NOI18N out.append(pkg.substring(1, pkg.length()-1)); } else { out.append(pkg); } } else if (pkg.startsWith(ECHO_PATTERN)) { pkg = pkg.substring(ECHO_PATTERN.length()); if (pkg.startsWith("'") && pkg.endsWith("'")) { //NOI18N out.append(pkg.substring(1, pkg.length()-1)); } else { StringTokenizer st = new StringTokenizer(pkg); if (st.hasMoreTokens()) { out.append(st.nextToken()); } } } else if (pkg.contains(ECHO_PATTERN)) { pkg = pkg.substring(pkg.indexOf(ECHO_PATTERN)+ECHO_PATTERN.length()); if (pkg.startsWith("'") && pkg.endsWith("'")) { //NOI18N out.append(pkg.substring(1, pkg.length()-1)); //NOI18N } else { StringTokenizer st = new StringTokenizer(pkg); if (st.hasMoreTokens()) { out.append(st.nextToken()); } } } out.append(line.substring(j+1)); return trimBackApostropheCalls(out.toString(), pkgConfig); } } // boost // #./b2 -a -d+2 // prints: // gcc.compile.c++ bin.v2/libs/graph/build/gcc-4.5.2/release/threading-multi/read_graphviz_new.o // // "g++" -ftemplate-depth-128 -O3 -finline-functions -Wno-inline -Wall -pthreads -fPIC -DBOOST_ALL_NO_LIB=1 -DBOOST_GRAPH_DYN_LINK=1 -DNDEBUG -I"." -I"libs/graph/src" -c -o "bin.v2/libs/graph/build/gcc-4.5.2/release/threading-multi/read_graphviz_new.o" "libs/graph/src/read_graphviz_new.cpp" private void gatherLine(LineInfo li, CompileLineStorage storage) { String line = li.compileLine; Artifacts artifacts = compilerSettings.getDriver().gatherCompilerLine(line, CompileLineOrigin.BuildLog, li.compilerType == CompilerType.CPP); for(String what : artifacts.getInput()) { if (what == null){ continue; } if (what.endsWith(".s") || what.endsWith(".S")) { //NOI18N // It seems assembler file was compiled by C compiler. // Exclude assembler files from C/C++ code model. continue; } String file; boolean isRelative = true; if (isPathAbsolute(what)){ what = convertWindowsRelativePath(what); isRelative = false; file = what; } else { file = workingDir+"/"+what; //NOI18N } List<String> userIncludesCached = new ArrayList<String>(artifacts.getUserIncludes().size()); for(String s : artifacts.getUserIncludes()){ s = convertWindowsRelativePath(s); userIncludesCached.add(PathCache.getString(s)); } List<String> userFilesCached = new ArrayList<String>(artifacts.getUserFiles().size()); for(String s : artifacts.getUserFiles()){ userFilesCached.add(PathCache.getString(s)); } Map<String, String> userMacrosCached = new HashMap<String, String>(artifacts.getUserMacros().size()); for(Map.Entry<String,String> e : artifacts.getUserMacros().entrySet()){ if (e.getValue() == null) { userMacrosCached.put(PathCache.getString(e.getKey()), null); } else { userMacrosCached.put(PathCache.getString(e.getKey()), PathCache.getString(e.getValue())); } } if (fs.exists(file) /*&& isData*/) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "**** Gotcha: {0}", file); } result.add(new CommandLineSource(li, artifacts, workingDir, convertSymbolicLink(what), userIncludesCached, userFilesCached, userMacrosCached, storage)); continue; } if (!isRelative) { file = convertPath(what); if (!file.equals(what)) { what = file; if (fs.exists(file) /*&& isData*/) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "**** Gotcha: {0}", file); } result.add(new CommandLineSource(li, artifacts, workingDir, convertSymbolicLink(what), userIncludesCached, userFilesCached, userMacrosCached, storage)); continue; } } } if (guessWorkingDir != null && !what.startsWith("/")) { //NOI18N String f = guessWorkingDir+"/"+what; //NOI18N if (fs.exists(f)) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "**** Gotcha guess: {0}", f); } result.add(new CommandLineSource(li, artifacts, guessWorkingDir, convertSymbolicLink(what), userIncludesCached, userFilesCached, userMacrosCached, storage)); continue; } } if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "**** Not found {0}", file); //NOI18N } if (!what.startsWith("/") && artifacts.getUserIncludes().size()+artifacts.getUserMacros().size() > 0){ //NOI18N List<String> res = findFiles(what); if (res == null || res.isEmpty()) { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "** And there is no such file under root"); } } else { if (res.size() == 1) { result.add(new CommandLineSource(li, artifacts, res.get(0), convertSymbolicLink(what), userIncludesCached, userFilesCached, userMacrosCached, storage)); if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "** Gotcha: {0}{1}{2}", new Object[]{res.get(0), "/", what}); } // kinda adventure but it works setGuessWorkingDir(res.get(0)); continue; } else { if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "**There are several candidates and I'm not clever enough yet to find correct one."); } } } if (DwarfSource.LOG.isLoggable(Level.FINE)) { DwarfSource.LOG.log(Level.FINE, "{0} [{1}]", new Object[]{line.length() > 120 ? line.substring(0,117) + ">>>" : line, what}); //NOI18N } } } if (artifacts.getOutput() != null) { String what = artifacts.getOutput(); String baseName = CndPathUtilities.getBaseName(what); if (!(baseName.endsWith(".exe") || !baseName.contains("."))) { //NOI18N return; } String file; boolean isRelative = true; if (isPathAbsolute(what)){ what = convertWindowsRelativePath(what); isRelative = false; file = what; } else { file = workingDir+"/"+what; //NOI18N } if (fs.exists(file) /*&& isData*/) { if (!buildArtifacts.contains(file)) { buildArtifacts.add(file); } } else if (!isRelative) { file = convertPath(what); if (!file.equals(what)) { if (fs.exists(file) /*&& isData*/) { if (!buildArtifacts.contains(file)) { buildArtifacts.add(file); } } } } } } private String convertSymbolicLink(String fullName) { if (project.resolveSymbolicLinks()) { String resolvedLink = DiscoveryUtils.resolveSymbolicLink(fileSystem, fullName); if (resolvedLink != null) { fullName = resolvedLink; } } return fullName; } //copy of CndPathUtilities.isPathAbsolute(CharSequence) // except checking on windows private boolean isPathAbsolute(CharSequence path) { if (path == null || path.length() == 0) { return false; } else if (path.charAt(0) == '/') { return true; } else if (path.charAt(0) == '\\') { return true; } else if (CharSequenceUtils.indexOf(path, ':') == 1) { if (path.length()==2) { return false; } else if (path.charAt(2) == '\\' || path.charAt(2) == '/') { return true; } return false; } else { return false; } } static ItemProperties.LanguageKind detectLanguage(LineInfo li, Artifacts artifacts, String sourcePath) { ItemProperties.LanguageKind language = li.getLanguage(); if (artifacts.getLanguageArtifacts().contains("c")) { // NOI18N language = ItemProperties.LanguageKind.C; } else if (artifacts.getLanguageArtifacts().contains("c++")) { // NOI18N language = ItemProperties.LanguageKind.CPP; } else { if (language == LanguageKind.Unknown || "cl".equals(li.compiler)) { // NOI18N String mime =MIMESupport.getKnownSourceFileMIMETypeByExtension(sourcePath); if (MIMENames.CPLUSPLUS_MIME_TYPE.equals(mime)) { if (li.getLanguage() != ItemProperties.LanguageKind.CPP) { language = ItemProperties.LanguageKind.CPP; } } else if (MIMENames.C_MIME_TYPE.equals(mime)) { if (li.getLanguage() != ItemProperties.LanguageKind.C) { language = ItemProperties.LanguageKind.C; } } } else if (language == LanguageKind.C && !li.compiler.equals("cc")) { // NOI18N String mime =MIMESupport.getKnownSourceFileMIMETypeByExtension(sourcePath); if (MIMENames.CPLUSPLUS_MIME_TYPE.equals(mime)) { language = ItemProperties.LanguageKind.CPP; } } } return language; } class CommandLineSource extends RelocatableImpl implements SourceFileProperties { private String sourceName; private final String compiler; private final ItemProperties.LanguageKind language; private ItemProperties.LanguageStandard standard = LanguageStandard.Unknown; private final List<String> systemIncludes = Collections.<String>emptyList(); private final Map<String, String> userMacros; private final List<String> undefinedMacros; private final Map<String, String> systemMacros = Collections.<String, String>emptyMap(); private final CompileLineStorage storage; private int handler = -1; private final String importantFlags; CommandLineSource(LineInfo li, Artifacts artifacts, String compilePath, String sourcePath, List<String> userIncludes, List<String> userFiles, Map<String, String> userMacros, CompileLineStorage storage) { language = detectLanguage(li, artifacts, sourcePath); standard = DriverFactory.getLanguageStandard(standard, artifacts); this.compiler = li.compiler; this.compilePath =compilePath; sourceName = sourcePath; if (CndPathUtilities.isPathAbsolute(sourceName)){ fullName = sourceName; sourceName = DiscoveryUtils.getRelativePath(compilePath, sourceName); } else { fullName = compilePath+"/"+sourceName; //NOI18N } fullName = convertSymbolicLink(fullName); fullName = CndFileUtils.normalizeAbsolutePath(fileSystem, fullName); fullName = PathCache.getString(fullName); this.userIncludes = userIncludes; this.userFiles = userFiles; this.userMacros = userMacros; this.undefinedMacros = artifacts.getUserUndefinedMacros(); this.storage = storage; if (storage != null) { handler = storage.putCompileLine(normalizeCompileLine(li.compileLine)); } this.importantFlags = DriverFactory.importantFlagsToString(artifacts);; } private String normalizeCompileLine(String line) { List<String> args = MakeLogReader.this.compilerSettings.getDriver().splitCommandLine(line, CompileLineOrigin.BuildLog); StringBuilder buf = new StringBuilder(); for (String s : args) { if (buf.length() > 0) { buf.append(' '); } boolean isQuote = false; if (s.startsWith("'") && s.endsWith("'") || // NOI18N s.startsWith("\"") && s.endsWith("\"")) { // NOI18N if (s.length() >= 2) { s = s.substring(1, s.length() - 1); isQuote = true; } } if (s.startsWith("-D")) { // NOI18N String macro = s.substring(2); macro = DriverFactory.removeQuotes(macro); int i = macro.indexOf('='); if (i > 0) { String value = macro.substring(i + 1).trim(); value = DriverFactory.normalizeDefineOption(value, CompileLineOrigin.BuildLog, isQuote); String key = DriverFactory.removeEscape(macro.substring(0, i)); s = "-D"+key+"="+value; // NOI18N } else { String key = DriverFactory.removeEscape(macro); s = "-D"+key; // NOI18N } } String s2 = CndPathUtilities.quoteIfNecessary(s); if (s.equals(s2)) { if (s.indexOf('"') > 0) { // NOI18N int j = s.indexOf("\\\""); // NOI18N if (j < 0) { s = s.replace("\"", "\\\""); // NOI18N } } } else { s = s2; } buf.append(s); } return buf.toString(); } @Override public String getCompilePath() { return compilePath; } @Override public String getItemPath() { return fullName; } @Override public String getCompileLine() { if (storage != null && handler != -1) { return storage.getCompileLine(handler); } return null; } @Override public String getItemName() { return sourceName; } @Override public List<String> getUserInludePaths() { return userIncludes; } @Override public List<String> getUserInludeFiles() { return userFiles; } @Override public List<String> getSystemInludePaths() { return systemIncludes; } public Set<String> getIncludedFiles() { return includedFiles; } @Override public Map<String, String> getUserMacros() { return userMacros; } @Override public List<String> getUndefinedMacros() { return undefinedMacros; } @Override public Map<String, String> getSystemMacros() { return systemMacros; } @Override public ItemProperties.LanguageKind getLanguageKind() { return language; } @Override public String getCompilerName() { return compiler; } @Override public LanguageStandard getLanguageStandard() { return standard; } @Override public String getImportantFlags() { return importantFlags; } } private List<String> getFiles(String name){ getSubfolders(); return findBase.get(name); } private List<String> findFiles(String relativePath) { relativePath = relativePath.replace('\\', '/'); int i = relativePath.lastIndexOf('/'); String name; String relativeFolder = null; if (i > 0) { name = relativePath.substring(i+1); relativeFolder = relativePath.substring(0,i); } else { name = relativePath; } String subFolder = null; if (relativeFolder != null) { int j = relativeFolder.lastIndexOf("../"); // NOI18N if (j >= 0) { subFolder = relativePath.substring(j+2); } } List<String> files = getFiles(name); if (files != null) { List<String> res = new ArrayList<String>(files.size()); for(String s : files) { if (relativeFolder == null) { res.add(s); if (res.size() > 1) { return res; } } else { if (subFolder == null) { String path = s; if (path.endsWith(relativeFolder) && path.length() > relativeFolder.length() + 1) { path = path.substring(0,path.length()-relativeFolder.length()-1); res.add(path); if (res.size() > 1) { return res; } } } else { for(String sub : getSubfolders()) { String pathCandidate = normalizeFile(sub + "/" + relativePath); // NOI18N int j = pathCandidate.lastIndexOf('/'); if (j > 0) { pathCandidate = pathCandidate.substring(0,j); if (subFolders.contains(pathCandidate)){ res.add(sub); if (res.size() > 1) { return res; } } } } } } } return res; } return null; } private String normalizeFile(String path) { path = path.replace("/./", "/"); // NOI18N while (true) { int i = path.indexOf("/../"); // NOI18N if (i < 0) { break; } int prev = -1; for (int j = i - 1; j >= 0; j--) { if (path.charAt(j) == '/') { prev = j; break; } } if (prev == -1) { break; } path = path.substring(0, prev)+path.substring(i+3); } return path; } private Set<String> getSubfolders(){ if (subFolders == null){ subFolders = new HashSet<String>(); findBase = new HashMap<String,List<String>>(); FileObject rootFO = fileSystem.findResource(root); gatherSubFolders(rootFO, new LinkedList<String>()); } return subFolders; } private HashSet<String> subFolders; private Map<String,List<String>> findBase; private void gatherSubFolders(FileObject d, LinkedList<String> antiLoop){ if (d != null && d.isValid() && d.isFolder() && d.canRead()){ if (isStoped.cancelled()) { return; } if (CndPathUtilities.isIgnoredFolder(d.getNameExt())){ return; } String canPath; try { canPath = CndFileUtils.getCanonicalPath(d); } catch (IOException ex) { return; } if (!antiLoop.contains(canPath)){ antiLoop.addLast(canPath); subFolders.add(d.getPath().replace('\\', '/')); FileObject[] ff = d.getChildren(); if (ff != null) { for (int i = 0; i < ff.length; i++) { if (isStoped.cancelled()) { break; } if (ff[i].isFolder()) { gatherSubFolders(ff[i], antiLoop); } else if (ff[i].isData()) { if (CndFileVisibilityQuery.getDefault().isIgnored(ff[i].getNameExt())) { continue; } List<String> l = findBase.get(ff[i].getNameExt()); if (l==null){ l = new ArrayList<String>(); findBase.put(ff[i].getNameExt(),l); } l.add(d.getPath().replace('\\', '/')); } } } antiLoop.removeLast(); } } } }
41.354698
302
0.510814
1e59a067237ae155e7ffd0f80a2e288f5af3329c
597
package com.storedobject.chart; /** * Interface to denote that a {@link ComponentPart} supports animation. * * @author Syam */ public interface HasEmphasis { /** * Get the instance of this property. (If <code>true</code> is passed as the parameter, * a new instance will be created if not already exists). * * @param create Whether to create it or not. * @return Instance. */ Emphasis getEmphasis(boolean create); /** * Set it to this instance. * * @param instance Instance to set. */ void setEmphasis(Emphasis instance); }
22.961538
91
0.638191
358f095d82f19ce4e6307a39aae4d1f838dee214
2,114
package naver; import java.util.HashSet; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @ClassName NaverCachedData * @Descripiton * @Author initial_yang * @Date 2020/4/12 */ public class NaverCachedData<E> { private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final ReentrantReadWriteLock.WriteLock wl = rwl.writeLock(); private final ReentrantReadWriteLock.ReadLock rl = rwl.readLock(); private Set cacheSet = new HashSet(10); /** * processCachedData * @param e * @return */ public E processCachedData(E e) { E re; rl.lock(); if (!isDataValid(e)) { try { // in cacheSet, return re = (E) cacheSet.stream() .filter(c -> c.equals(e)) .findFirst() .orElse(null); System.out.println("e is cached, e:" + e); } finally { rl.unlock(); } } else { // not in cache, cache and return rl.unlock(); wl.lock(); try { cacheSet.add(e); System.out.println("cache e, e:" + e); // downgrade rl.lock(); try { E rle = (E) cacheSet.stream() .filter(c -> c.equals(e)) .findFirst() .orElse(null); System.out.println("after downgrade , e :" + e); re = rle; } finally { rl.unlock(); } } finally { wl.unlock(); } } return re; } /** * check data is in cacheSet * @param e * @return */ private boolean isDataValid(E e) { E cache = (E) cacheSet.stream() .filter(c -> c.equals(e)) .findFirst() .orElse(null); return cache == null; } }
26.098765
76
0.446074
b655d60344054f07bbef308739e2cf0e561777a1
293
package com.retail.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.math.BigDecimal; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class PurchaseDTO { public BigDecimal totalDiscount; }
17.235294
36
0.812287
f36276240b878402990ee5aa712b47f641333699
317
package com.fpt.capstone.wcs.repository.website; import com.fpt.capstone.wcs.model.entity.website.CookieData; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CookieDataRepository extends JpaRepository<CookieData,Long> { }
31.7
78
0.84858
5a4328a34bbc83165f5ffab9b99e6c8b51aaf406
1,163
package com.eixox.adapters; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.eixox.globalization.Culture; public final class StringAdapter extends ValueAdapter<String> { public StringAdapter() { super(String.class); } @Override public final String parse(Culture culture, String input) { return input; } @Override public final String format(Culture culture, String input) { return input; } @Override public final boolean IsNullOrEmpty(Object item) { return item == null || ((String) item).isEmpty(); } @Override public final String convert(Object value, Culture culture) { if (value == null) return null; else if (String.class.isInstance(value)) return (String) value; else return value.toString(); } @Override public int getSqlTypeId() { return java.sql.Types.VARCHAR; } @Override public void setParameterValue(PreparedStatement ps, int parameterIndex, String value) throws SQLException { ps.setString(parameterIndex, value); } @Override public String readValue(ResultSet rs, int ordinal) throws SQLException { return rs.getString(ordinal); } }
20.767857
108
0.741187
576e2df8646ed2113042a213f74ad530445ff142
11,495
package com.coding.exercise.bankapp.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.coding.exercise.bankapp.domain.AccountInformation; import com.coding.exercise.bankapp.domain.CustomerDetails; import com.coding.exercise.bankapp.domain.TransactionDetails; import com.coding.exercise.bankapp.domain.TransferDetails; import com.coding.exercise.bankapp.model.Account; import com.coding.exercise.bankapp.model.Address; import com.coding.exercise.bankapp.model.Contact; import com.coding.exercise.bankapp.model.Customer; import com.coding.exercise.bankapp.model.CustomerAccountXRef; import com.coding.exercise.bankapp.model.Transaction; import com.coding.exercise.bankapp.repository.AccountRepository; import com.coding.exercise.bankapp.repository.CustomerAccountXRefRepository; import com.coding.exercise.bankapp.repository.CustomerRepository; import com.coding.exercise.bankapp.repository.TransactionRepository; import com.coding.exercise.bankapp.service.helper.BankingServiceHelper; @Service @Transactional public class BankingServiceImpl implements BankingService { @Autowired private CustomerRepository customerRepository; @Autowired private AccountRepository accountRepository; @Autowired private TransactionRepository transactionRepository; @Autowired private CustomerAccountXRefRepository custAccXRefRepository; @Autowired private BankingServiceHelper bankingServiceHelper; public BankingServiceImpl(CustomerRepository repository) { this.customerRepository=repository; } public List<CustomerDetails> findAll() { List<CustomerDetails> allCustomerDetails = new ArrayList<>(); Iterable<Customer> customerList = customerRepository.findAll(); customerList.forEach(customer -> { allCustomerDetails.add(bankingServiceHelper.convertToCustomerDomain(customer)); }); return allCustomerDetails; } /** * CREATE Customer * * @param customerDetails * @return */ public ResponseEntity<Object> addCustomer(CustomerDetails customerDetails) { Customer customer = bankingServiceHelper.convertToCustomerEntity(customerDetails); customer.setCreateDateTime(new Date()); customerRepository.save(customer); return ResponseEntity.status(HttpStatus.CREATED).body("New Customer created successfully."); } /** * READ Customer * * @param customerNumber * @return */ public CustomerDetails findByCustomerNumber(Long customerNumber) { Optional<Customer> customerEntityOpt = customerRepository.findByCustomerNumber(customerNumber); if(customerEntityOpt.isPresent()) return bankingServiceHelper.convertToCustomerDomain(customerEntityOpt.get()); return null; } /** * UPDATE Customer * * @param customerDetails * @param customerNumber * @return */ public ResponseEntity<Object> updateCustomer(CustomerDetails customerDetails, Long customerNumber) { Optional<Customer> managedCustomerEntityOpt = customerRepository.findByCustomerNumber(customerNumber); Customer unmanagedCustomerEntity = bankingServiceHelper.convertToCustomerEntity(customerDetails); if(managedCustomerEntityOpt.isPresent()) { Customer managedCustomerEntity = managedCustomerEntityOpt.get(); if(Optional.ofNullable(unmanagedCustomerEntity.getContactDetails()).isPresent()) { Contact managedContact = managedCustomerEntity.getContactDetails(); if(managedContact != null) { managedContact.setEmailId(unmanagedCustomerEntity.getContactDetails().getEmailId()); managedContact.setHomePhone(unmanagedCustomerEntity.getContactDetails().getHomePhone()); managedContact.setWorkPhone(unmanagedCustomerEntity.getContactDetails().getWorkPhone()); } else managedCustomerEntity.setContactDetails(unmanagedCustomerEntity.getContactDetails()); } if(Optional.ofNullable(unmanagedCustomerEntity.getCustomerAddress()).isPresent()) { Address managedAddress = managedCustomerEntity.getCustomerAddress(); if(managedAddress != null) { managedAddress.setAddress1(unmanagedCustomerEntity.getCustomerAddress().getAddress1()); managedAddress.setAddress2(unmanagedCustomerEntity.getCustomerAddress().getAddress2()); managedAddress.setCity(unmanagedCustomerEntity.getCustomerAddress().getCity()); managedAddress.setState(unmanagedCustomerEntity.getCustomerAddress().getState()); managedAddress.setZip(unmanagedCustomerEntity.getCustomerAddress().getZip()); managedAddress.setCountry(unmanagedCustomerEntity.getCustomerAddress().getCountry()); } else managedCustomerEntity.setCustomerAddress(unmanagedCustomerEntity.getCustomerAddress()); } managedCustomerEntity.setUpdateDateTime(new Date()); managedCustomerEntity.setStatus(unmanagedCustomerEntity.getStatus()); managedCustomerEntity.setFirstName(unmanagedCustomerEntity.getFirstName()); managedCustomerEntity.setMiddleName(unmanagedCustomerEntity.getMiddleName()); managedCustomerEntity.setLastName(unmanagedCustomerEntity.getLastName()); managedCustomerEntity.setUpdateDateTime(new Date()); customerRepository.save(managedCustomerEntity); return ResponseEntity.status(HttpStatus.OK).body("Success: Customer updated."); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Customer Number " + customerNumber + " not found."); } } /** * DELETE Customer * * @param customerNumber * @return */ public ResponseEntity<Object> deleteCustomer(Long customerNumber) { Optional<Customer> managedCustomerEntityOpt = customerRepository.findByCustomerNumber(customerNumber); if(managedCustomerEntityOpt.isPresent()) { Customer managedCustomerEntity = managedCustomerEntityOpt.get(); customerRepository.delete(managedCustomerEntity); return ResponseEntity.status(HttpStatus.OK).body("Success: Customer deleted."); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Customer does not exist."); } //TODO: Delete all customer entries from CustomerAccountXRef } /** * Find Account * * @param accountNumber * @return */ public ResponseEntity<Object> findByAccountNumber(Long accountNumber) { Optional<Account> accountEntityOpt = accountRepository.findByAccountNumber(accountNumber); if(accountEntityOpt.isPresent()) { return ResponseEntity.status(HttpStatus.FOUND).body(bankingServiceHelper.convertToAccountDomain(accountEntityOpt.get())); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Account Number " + accountNumber + " not found."); } } /** * Create new account * * @param accountInformation * @param customerNumber * * @return */ public ResponseEntity<Object> addNewAccount(AccountInformation accountInformation, Long customerNumber) { Optional<Customer> customerEntityOpt = customerRepository.findByCustomerNumber(customerNumber); if(customerEntityOpt.isPresent()) { accountRepository.save(bankingServiceHelper.convertToAccountEntity(accountInformation)); // Add an entry to the CustomerAccountXRef custAccXRefRepository.save(CustomerAccountXRef.builder() .accountNumber(accountInformation.getAccountNumber()) .customerNumber(customerNumber) .build()); } return ResponseEntity.status(HttpStatus.CREATED).body("New Account created successfully."); } /** * Transfer funds from one account to another for a specific customer * * @param transferDetails * @param customerNumber * @return */ public ResponseEntity<Object> transferDetails(TransferDetails transferDetails, Long customerNumber) { List<Account> accountEntities = new ArrayList<>(); Account fromAccountEntity = null; Account toAccountEntity = null; Optional<Customer> customerEntityOpt = customerRepository.findByCustomerNumber(customerNumber); // If customer is present if(customerEntityOpt.isPresent()) { // get FROM ACCOUNT info Optional<Account> fromAccountEntityOpt = accountRepository.findByAccountNumber(transferDetails.getFromAccountNumber()); if(fromAccountEntityOpt.isPresent()) { fromAccountEntity = fromAccountEntityOpt.get(); } else { // if from request does not exist, 404 Bad Request return ResponseEntity.status(HttpStatus.NOT_FOUND).body("From Account Number " + transferDetails.getFromAccountNumber() + " not found."); } // get TO ACCOUNT info Optional<Account> toAccountEntityOpt = accountRepository.findByAccountNumber(transferDetails.getToAccountNumber()); if(toAccountEntityOpt.isPresent()) { toAccountEntity = toAccountEntityOpt.get(); } else { // if from request does not exist, 404 Bad Request return ResponseEntity.status(HttpStatus.NOT_FOUND).body("To Account Number " + transferDetails.getToAccountNumber() + " not found."); } // if not sufficient funds, return 400 Bad Request if(fromAccountEntity.getAccountBalance() < transferDetails.getTransferAmount()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Insufficient Funds."); } else { synchronized (this) { // update FROM ACCOUNT fromAccountEntity.setAccountBalance(fromAccountEntity.getAccountBalance() - transferDetails.getTransferAmount()); fromAccountEntity.setUpdateDateTime(new Date()); accountEntities.add(fromAccountEntity); // update TO ACCOUNT toAccountEntity.setAccountBalance(toAccountEntity.getAccountBalance() + transferDetails.getTransferAmount()); toAccountEntity.setUpdateDateTime(new Date()); accountEntities.add(toAccountEntity); accountRepository.saveAll(accountEntities); // Create transaction for FROM Account Transaction fromTransaction = bankingServiceHelper.createTransaction(transferDetails, fromAccountEntity.getAccountNumber(), "DEBIT"); transactionRepository.save(fromTransaction); // Create transaction for TO Account Transaction toTransaction = bankingServiceHelper.createTransaction(transferDetails, toAccountEntity.getAccountNumber(), "CREDIT"); transactionRepository.save(toTransaction); } return ResponseEntity.status(HttpStatus.OK).body("Success: Amount transferred for Customer Number " + customerNumber); } } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Customer Number " + customerNumber + " not found."); } } /** * Get all transactions for a specific account * * @param accountNumber * @return */ public List<TransactionDetails> findTransactionsByAccountNumber(Long accountNumber) { List<TransactionDetails> transactionDetails = new ArrayList<>(); Optional<Account> accountEntityOpt = accountRepository.findByAccountNumber(accountNumber); if(accountEntityOpt.isPresent()) { Optional<List<Transaction>> transactionEntitiesOpt = transactionRepository.findByAccountNumber(accountNumber); if(transactionEntitiesOpt.isPresent()) { transactionEntitiesOpt.get().forEach(transaction -> { transactionDetails.add(bankingServiceHelper.convertToTransactionDomain(transaction)); }); } } return transactionDetails; } }
36.842949
141
0.771988
b5be78f77976851302333de0eb02a3fb159fa095
1,136
package org.phoenix.leetcode.challenges; import org.junit.jupiter.api.Test; import java.util.List; class Problem29_VerticalOrderTraversalOfBinaryTreeTest { private final Problem29_VerticalOrderTraversalOfBinaryTree test = new Problem29_VerticalOrderTraversalOfBinaryTree(); @Test void verticalTraversal() { TreeNode root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7); printTree(test.verticalTraversal(root)); root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); printTree(test.verticalTraversal(root)); } private void printTree(List<List<Integer>> verticalOrderTraversal) { for (List<Integer> list : verticalOrderTraversal) { System.out.print(list + " "); } System.out.println(); } }
31.555556
121
0.651408
c0b4aa3ea91dcd2ef17e1e300fda0fe572889691
2,553
package com.nsk.cms.rabbitmq.sender; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicLong; import org.springframework.amqp.core.Message; import org.springframework.beans.factory.annotation.Autowired; import com.nsk.cms.common.Constants; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j public class RetryCache { private MessageSender messageSender; private boolean stop = false; private Map<String, MessageWithTime> map = new ConcurrentSkipListMap<>(); private static AtomicLong id = new AtomicLong(); public void setMessageSender(MessageSender messageSender){ this.messageSender = messageSender; startRetry(); } public String generateId() { return "" + id.incrementAndGet(); } public void add(String id,Object object) { map.put(id, new MessageWithTime(System.currentTimeMillis(), object)); } public void del(String id) { map.remove(id); } public Object get(String id) { return map.get(id); } public int count() { return map.size(); } private void startRetry() { new Thread(() ->{ while (!stop) { try { Thread.sleep(Constants.RETRY_TIME_INTERVAL); } catch (InterruptedException e) { e.printStackTrace(); } long now = System.currentTimeMillis(); for (Map.Entry<String, MessageWithTime> entry : map.entrySet()) { MessageWithTime message = entry.getValue(); if (null != message) { if (message.getTime() + 3 * Constants.VALID_TIME < now) { log.info("send message failed after 3 min " + message.getMessage()); del(entry.getKey()); } else if (message.getTime() + Constants.VALID_TIME < now) { DetailRes detailRes = messageSender.send(message.getMessage()); if (detailRes.isSuccess()) { del(entry.getKey()); } } } } } }, "c.n.c.Rabbitmq.s.RetryCache.startRetry").start(); } @NoArgsConstructor @AllArgsConstructor @Data private static class MessageWithTime { long time; Object message; } }
27.75
95
0.57501
b4a1b4099866b522edef170094640024a8728e99
4,168
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.service; import org.onosproject.store.primitives.DefaultConsistentTreeMap; import java.util.Map; import java.util.NavigableSet; import java.util.concurrent.CompletableFuture; /** * API for a distributed tree map implementation. */ public interface AsyncConsistentTreeMap<K, V> extends AsyncConsistentMap<K, V> { /** * Return the lowest key in the map. * * @return the key or null if none exist */ CompletableFuture<K> firstKey(); /** * Return the highest key in the map. * * @return the key or null if none exist */ CompletableFuture<K> lastKey(); /** * Returns the entry associated with the least key greater than or equal to the key. * * @param key the key * @return the entry or null */ CompletableFuture<Map.Entry<K, Versioned<V>>> ceilingEntry(K key); /** * Returns the entry associated with the greatest key less than or equal to key. * * @param key the key * @return the entry or null */ CompletableFuture<Map.Entry<K, Versioned<V>>> floorEntry(K key); /** * Returns the entry associated with the lest key greater than key. * * @param key the key * @return the entry or null */ CompletableFuture<Map.Entry<K, Versioned<V>>> higherEntry(K key); /** * Returns the entry associated with the largest key less than key. * * @param key the key * @return the entry or null */ CompletableFuture<Map.Entry<K, Versioned<V>>> lowerEntry(K key); /** * Return the entry associated with the lowest key in the map. * * @return the entry or null */ CompletableFuture<Map.Entry<K, Versioned<V>>> firstEntry(); /** * Return the entry assocaited with the highest key in the map. * * @return the entry or null */ CompletableFuture<Map.Entry<K, Versioned<V>>> lastEntry(); /** * Return and remove the entry associated with the lowest key. * * @return the entry or null */ CompletableFuture<Map.Entry<K, Versioned<V>>> pollFirstEntry(); /** * Return and remove the entry associated with the highest key. * * @return the entry or null */ CompletableFuture<Map.Entry<K, Versioned<V>>> pollLastEntry(); /** * Return the entry associated with the greatest key less than key. * * @param key the key * @return the entry or null */ CompletableFuture<K> lowerKey(K key); /** * Return the entry associated with the highest key less than or equal to key. * * @param key the key * @return the entry or null */ CompletableFuture<K> floorKey(K key); /** * Return the lowest key greater than or equal to key. * * @param key the key * @return the key or null */ CompletableFuture<K> ceilingKey(K key); /** * Return the lowest key greater than key. * * @param key the key * @return the key or null */ CompletableFuture<K> higherKey(K key); /** * Returns a navigable set of the keys in this map. * * @return a navigable key set */ CompletableFuture<NavigableSet<K>> navigableKeySet(); default ConsistentTreeMap<K, V> asTreeMap() { return asTreeMap(DistributedPrimitive.DEFAULT_OPERTATION_TIMEOUT_MILLIS); } default ConsistentTreeMap<K, V> asTreeMap(long timeoutMillis) { return new DefaultConsistentTreeMap<>(this, timeoutMillis); } }
27.24183
88
0.646593
d504ac0240189d55cbcf0890ec0da51f07803c3c
195
package ar.com.imango.digitalhospital; public interface Subscriptor { void eliminarMedidor(Medidor medidor); void agregarMedidor(Medidor medidor); void notificar(Medidor medidor); }
24.375
42
0.774359
3c6aad6795b7c52cc1f8b8cb3aa6cb4f9677d9a2
5,828
/** * 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.sqoop.manager.sqlserver; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.StringUtils; import org.apache.sqoop.SqoopOptions; import org.apache.sqoop.hive.TestHiveImport; import org.apache.sqoop.testcategories.thirdpartytest.SqlServerTest; import org.apache.sqoop.testutil.CommonArgs; import org.apache.sqoop.tool.SqoopTool; import org.junit.After; import org.junit.Before; import org.junit.experimental.categories.Category; import static org.junit.Assert.fail; /** * Test import to Hive from SQL Server. * * This uses JDBC to import data from an SQLServer database to HDFS. * * Since this requires an SQLServer installation, * this class is named in such a way that Sqoop's default QA process does * not run it. You need to run this manually with * -Dtestcase=SQLServerHiveImportTest or -Dthirdparty=true. * * You need to put SQL Server JDBC driver library (sqljdbc4.jar) in a location * where Sqoop will be able to access it (since this library cannot be checked * into Apache's tree for licensing reasons) and set it's path through -Dsqoop.thirdparty.lib.dir. * * To set up your test environment: * Install SQL Server Express 2012 * Create a database SQOOPTEST * Create a login SQOOPUSER with password PASSWORD and grant all * access for SQOOPTEST to SQOOPUSER. * Set these through -Dsqoop.test.sqlserver.connectstring.host_url, -Dsqoop.test.sqlserver.database and * -Dms.sqlserver.password */ @Category(SqlServerTest.class) public class SQLServerHiveImportTest extends TestHiveImport { @Before public void setUp() { super.setUp(); } @After public void tearDown() { try { dropTableIfExists(getTableName()); } catch (SQLException sqle) { LOG.info("Table clean-up failed: " + sqle); } finally { super.tearDown(); } } protected boolean useHsqldbTestServer() { return false; } protected String getConnectString() { return MSSQLTestUtils.getDBConnectString(); } //SQL Server pads out @Override protected String[] getTypes() { String[] types = { "VARCHAR(32)", "INTEGER", "VARCHAR(64)" }; return types; } /** * Drop a table if it already exists in the database. * @param table * the name of the table to drop. * @throws SQLException * if something goes wrong. */ protected void dropTableIfExists(String table) throws SQLException { Connection conn = getManager().getConnection(); String sqlStmt = "IF OBJECT_ID('" + table + "') IS NOT NULL DROP TABLE " + table; PreparedStatement statement = conn.prepareStatement(sqlStmt, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); try { statement.executeUpdate(); conn.commit(); } finally { statement.close(); } } protected SqoopOptions getSqoopOptions(Configuration conf) { String username = MSSQLTestUtils.getDBUserName(); String password = MSSQLTestUtils.getDBPassWord(); SqoopOptions opts = new SqoopOptions(conf); opts.setUsername(username); opts.setPassword(password); return opts; } SqoopOptions getSqoopOptions(String[] args, SqoopTool tool) { SqoopOptions opts = null; try { opts = tool.parseArguments(args, null, null, true); String username = MSSQLTestUtils.getDBUserName(); String password = MSSQLTestUtils.getDBPassWord(); opts.setUsername(username); opts.setPassword(password); } catch (Exception e) { LOG.error(StringUtils.stringifyException(e)); fail("Invalid options: " + e.toString()); } return opts; } protected String[] getArgv(boolean includeHadoopFlags, String[] moreArgs) { ArrayList<String> args = new ArrayList<String>(); System.out.println("Overridden getArgv is called.."); if (includeHadoopFlags) { CommonArgs.addHadoopFlags(args); } if (null != moreArgs) { for (String arg : moreArgs) { args.add(arg); } } args.add("--table"); args.add(getTableName()); args.add("--warehouse-dir"); args.add(getWarehouseDir()); args.add("--connect"); args.add(getConnectString()); args.add("--hive-import"); String[] colNames = getColNames(); if (null != colNames) { args.add("--split-by"); args.add(colNames[0]); } else { fail("Could not determine column names."); } args.add("--num-mappers"); args.add("1"); for (String a : args) { LOG.debug("ARG : " + a); } return args.toArray(new String[0]); } protected String[] getCodeGenArgs() { ArrayList<String> args = new ArrayList<String>(); args.add("--table"); args.add(getTableName()); args.add("--connect"); args.add(getConnectString()); args.add("--hive-import"); return args.toArray(new String[0]); } }
29.734694
105
0.689259
95f1d6e22f2cda11538b24a4b1a8048d85b6bb22
1,773
package com.cftechsol.rest.example; import javax.validation.ConstraintViolationException; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cftechsol.rest.controllers.GenericController; import com.cftechsol.rest.exceptions.NonUniqueException; /** * Example controller to execute test. * * @author Caio Frota {@literal <[email protected]>} * @version 1.0.0 * @since 1.0.0 */ @RestController @RequestMapping(path = "/example", produces = MediaType.APPLICATION_JSON_VALUE) public class ExampleController extends GenericController<ExampleService, ExampleEntity, Long> { @GetMapping(path="/filter") public ExampleEntity findByName(String name) { return this.getService().findByName(name); } @GetMapping(path="/exception") public void exeption() throws Exception { throw new Exception("Example Message"); } @GetMapping(path="/nonUniqueException") public void nonUniqueException() throws Exception { throw new NonUniqueException("Object", new String[] { "keys" }, new String[] { "values" }); } @PostMapping(path="/validationException") public void validationException(@RequestBody ExampleEntity object) throws Exception { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); throw new ConstraintViolationException(validator.validate(object)); } }
34.096154
95
0.794698
6a8a4896fba710c37e331c502602328e5a0a4cbe
1,092
package com.github.mickeer.codegen.fieldenum; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * For each class annotated with this annotation, an enum class with class' name * postfixed with "Fields" is generated. The enum class contains an enum value * for each of the fields of the annotated class. * * <p> E.g. for class {@code MyClass} with a field {@code date}, an enum class * {@code MyClassFields} is generated with enum value {@code DATE}. * * <p> The intention of this is to provide way to switch and loop over each field * of a class. Combined with IDE compilation settings (or SpotBugs check) * to require explicit handling of each enum value in a switch expression, this * ensures that each field is handled and if the annotated class is changed in a way * such as field is added, removed or renamed, the IDE will signal an error to be fixed. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface GenerateFieldEnum { }
40.444444
88
0.762821
46baf6a56bbed07426eea2a0132c413199fd9c91
761
package com.wfcrc.utils; import android.content.Context; import android.support.annotation.Nullable; import java.io.IOException; import java.io.InputStream; /** * Created by maria on 10/10/16. */ public class JSONUtils { @Nullable public static String loadJSONFromAsset(Context context, int rawResource) { String json = null; try { InputStream is = context.getResources().openRawResource(rawResource); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } }
24.548387
81
0.597898
b1101e5c668833c3537ce230477e2b67d61ea091
1,254
package ch.rhj.gradle.publish; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import org.gradle.api.Project; import org.junit.jupiter.api.Test; import org.mockito.Mock; public class DefaultInfoTests { @Test public void test(@Mock Project project) { DefaultProjectInfo info = new DefaultProjectInfo(project); when(project.getGroup()).thenReturn("group"); assertEquals("group", info.getGroup()); when(project.getName()).thenReturn("name"); assertEquals("name", info.getName()); when(project.getVersion()).thenReturn("version"); assertEquals("version", info.getVersion()); when(project.hasProperty("title")).thenReturn(false); assertEquals("name", info.getTitle()); when(project.hasProperty("title")).thenReturn(true); when(project.property("title")).thenReturn("title"); assertEquals("title", info.getTitle()); when(project.hasProperty("description")).thenReturn(false); assertEquals("title", info.getDescription()); when(project.hasProperty("description")).thenReturn(true); when(project.property("description")).thenReturn("description"); assertEquals("description", info.getDescription()); } }
30.585366
67
0.709729
e4de1323f6d7b9ebadd8e5ba3f91ea4244fd0c33
723
package de.strasser.peter.hexagonal.web.mapper; import de.strasser.peter.hexagonal.application.port.in.commands.AddAddressCommand; import de.strasser.peter.hexagonal.web.dto.request.AddAddressRequest; import org.mapstruct.Mapper; @Mapper public interface AddAddressWebMapper { /** * Can not be mapped by MapStruct currently, due to bug in JDK 16. * https://github.com/mapstruct/mapstruct/issues/2294 */ default AddAddressCommand toCmd(AddAddressRequest addAddressRequest) { return new AddAddressCommand( addAddressRequest.getType(), addAddressRequest.getStreet(), addAddressRequest.getCity(), addAddressRequest.getZipCode(), addAddressRequest.getCountry()); } }
32.863636
82
0.75242
1b501279c5651cf2e948a12de5c0bbca3ba97029
7,020
/* * Copyright 2017 Uniklinik Freiburg and The Hyve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.radarcns.biovotion; /** * Define some constants used in several activities and views. * * @author Christopher Métrailler ([email protected]) * @version 1.0 - 2016/07/20 */ public final class VsmConstants { /** * Key used to pass the DiscoveredEntity descriptor as intent argument. * The descriptor of the discovered VSM device is serialized and passed between activities. */ public final static String KEY_DESC_EXTRA = "key_extra_desc"; /** * Default Bluetooth connection timeout. If this timeout is reached, the callback * VsmDeviceListener#onVsmDeviceConnectionError(VsmDevice, VsmConnectionState) is called. * * <p> * The default timeout on Android is 30 seconds. Using the BLE library, the maximum timeout value * is fixed to 25 seconds. * When connecting the first time to a VSM device, the connection time can be up to 5 seconds because the pairing * process can take time and it is based on some internal delays. */ public final static int BLE_CONN_TIMEOUT_MS = 10000; /** * Parameter IDs according to VSM Bluetooth Comms Spec */ public final static int PID_INTERFACE_VERSION = 0x00; // R public final static int PID_UTC = 0x01; // RW public final static int PID_ALGO_MODE = 0x04; // RW public final static int PID_DEVICE_MODE = 0x05; // R public final static int PID_FIRMWARE_M4_VERSION = 0x06; // R public final static int PID_FIRMWARE_AS7000_VERSION = 0x08; // R public final static int PID_HW_VERSION = 0x09; // R public final static int PID_FIRMWARE_BLE_VERSION = 0x0B; // R public final static int PID_UNIQUE_DEVICE_ID = 0x12; // R public final static int PID_STORAGE_TIME = 0x15; // RW public final static int PID_NO_AVERAGE_PER_SAMPLE_AS7000 = 0x16; // RW public final static int PID_GSR_ON = 0x1D; // RW public final static int PID_ADVERTISING_NAME = 0x1E; // RW public final static int PID_DTM_MODE = 0x1F; // W public final static int PID_DISABLE_LOW_BAT_NOTIFICATION = 0x20; // RW public final static int PID_ENERGY_SUM_HOURS = 0x22; // R public final static int PID_STEPS_SUM_HOURS = 0x23; // R public final static int PID_SWITCH_DEVICE_OFF = 0x2A; // W public final static int PID_TX_POWER = 0x2B; // RW public final static int PID_SET_FACTORY_DEFAULT = 0x2C; // W public final static int PID_DISSCONNECT_BLE_CONN = 0x2D; // W public final static int PID_SELF_TEST_RESULT = 0x2E; // R public final static int PID_CLEAR_WHITE_LIST = 0x30; // W public final static int PID_BOOTLOADER_VERSIOM = 0x31; // R public final static int PID_BL_KEY_META_DATA = 0x32; // R public final static int PID_DISABLE_DOUBLE_TAP_NOTIFICATION = 0x33; // RW // GAP Request public final static int PID_GAP_REQUEST_STATUS = 0x21; // R public final static int PID_GAP_RECORD_REQUEST = 0x11; // W public final static int PID_SET_LAST_COUNTER_VALUE = 0x2F; // W public final static int PID_LAST_ERROR_COUNTER_VALUE = 0x0F; // R public final static int PID_LAST_LOG_COUNTER_VALUE = 0x10; // R public final static int PID_LAST_VITAL_DATA_COUNTER_VALUE = 0x0E; // R public final static int PID_LAST_IPI_DATA_COUNTER_VALUE = 0x27; // R public final static int PID_LAST_RAW_COUNTER_VALUE = 0x24; // R public final static int PID_NUMBER_OF_ERROR_LOG_SETS_IN_STORAGE = 0x1B; // R public final static int PID_NUMBER_OF_LOG_SETS_IN_STORAGE = 0x19; // R public final static int PID_NUMBER_OF_VITAL_DATA_SETS_IN_STORAGE = 0x17; // R public final static int PID_NUMBER_OF_IPI_DATA_SETS_IN_STORAGE = 0x28; // R public final static int PID_NUMBER_OF_RAW_DATA_SETS_IN_STORAGE = 0x25; // R /** * GAP request data types */ public final static int GAP_TYPE_ERROR_LOG = 0x00; public final static int GAP_TYPE_EVENT_LOG = 0x01; public final static int GAP_TYPE_VITAL = 0x02; public final static int GAP_TYPE_IPI = 0x03; public final static int GAP_TYPE_VITAL_RAW = 0x10; /** * GAP request maximum number of records per page, whole pages will be streamed if possible */ public final static int GAP_MAX_PER_PAGE_ERROR_LOG = 0x0C; public final static int GAP_MAX_PER_PAGE_EVENT_LOG = 0x09; public final static int GAP_MAX_PER_PAGE_VITAL = 0x09; public final static int GAP_MAX_PER_PAGE_IPI = 0x27; public final static int GAP_MAX_PER_PAGE_VITAL_RAW = 0x11; /** * GAP request miscellaneous */ public final static int GAP_NUM_PAGES = 10; // number of pages to get with one request public final static int GAP_INTERVAL_MS = 500; // try a new GAP request every x milliseconds public final static int GAP_NUM_LOOKUP = 0; // maximum number of pages to look into the past, if set to -1 will look as far as possible (more of a debug feature for now, not fully implemented) /** * UTC set time interval */ public final static int UTC_INTERVAL_MS = 60000; // set the device UTC time every x milliseconds /** * VSM algorithm modes */ public final static int MOD_VITAL_MODE = 0x00; public final static int MOD_VITAL_CAPPED_MODE = 0x01; public final static int MOD_RAW_DATA_VITAL_MODE = 0x04; public final static int MOD_RAW_DATA_HR_ONLY_MODE = 0x05; public final static int MOD_SELF_TEST_MODE = 0x06; public final static int MOD_MIXED_VITAL_RAW = 0x09; public final static int MOD_VITAL_MODE_AUTO_DATA = 0x0A; public final static int MOD_GREEN_ONLY_MODE = 0x0B; public final static int MOD_RAW_DATA_FIX_CURRENT = 0x0C; public final static int MOD_SHORT_SELF_TEST_MODE = 0x0D; public final static int MOD_MIXED_VITAL_RAW_SILENT = 0x0E; private VsmConstants() { // Private } }
48.413793
197
0.664387
2c32135c53952a725627229ef0a5be769d7eb024
3,687
package de.isc.cmdq.service; import de.isc.cmdq.conf.ServiceConfig; import de.isc.cmdq.domain.CmdRequest; import de.isc.cmdq.error.ScriptError; import org.apache.commons.lang3.RandomStringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.Map; @ExtendWith(SpringExtension.class) @Tag("unitTest") @ContextConfiguration(classes = {ServiceConfig.class}) @DirtiesContext class JythonServiceTest { private static Logger LOG; /* * Select a specific logging configuration for testing. */ @BeforeAll static void beforeClass() { System.setProperty("log4j.configurationFile","log4j2-test.xml"); LOG = LogManager.getLogger(JythonServiceTest.class); } @Autowired private ApplicationContext m_app; JythonServiceTest() {} @Test @DisplayName("Check application context") void test001BeanExistence() { LOG.info("Application-context present"); Assertions.assertNotNull(m_app); } @Test @DisplayName("Null script name") void test002ConstructorNullScriptName() { LOG.info("Null script name"); Assertions.assertThrows(BeanCreationException.class,() -> m_app.getBean(JythonService.class,new Object[] {null, null}) ); } @Test @DisplayName("Empty script name") void test003ConstructorEmptyScriptName() { LOG.info("empty script name"); Assertions.assertThrows(BeanCreationException.class,() -> m_app.getBean(JythonService.class,"", null) ); } @Test @DisplayName("Empty script") void test004ConstructorEmptyScript() { LOG.info("empty script (no code)"); Assertions.assertThrows(BeanCreationException.class,() -> m_app.getBean(JythonService.class,"empty.py", null) ); } @Test @DisplayName("Not existend script") void test004ConstructorNotExistent() { LOG.info("Not existent script"); Assertions.assertThrows(BeanCreationException.class,() -> m_app.getBean(JythonService.class,"not_existent_script.py", null) ); } @Test @DisplayName("Hello-script") void test005HelloScript() { LOG.info("Hello world"); m_app.getBean(JythonService.class,"hello.py", null) .execute(null); } @Test @DisplayName("Hello-script with parameters") void test006HelloScript() { LOG.info("Hello with parameter"); m_app.getBean(JythonService.class,"hello_param.py", null) .execute(Map.of("user","Homer Simpson")); } @Test @DisplayName("Multiple hello-script with parameters") void test007HelloScriptMultipleTimes() { LOG.info("Hello with parameter"); for(int i = 0; i < 50; ++i) { m_app.getBean(JythonService.class, "hello_param.py", null) .execute(Map.of("user", "Homer Simpson")); } StatisticsCollector stat = m_app.getBean(StatisticsCollector.class); LOG.info("Script calls: {}",stat.countScriptCalls()); } @Test @DisplayName("Script with exception") void test007ScriptWithException() { LOG.info("Script with exception"); Assertions.assertThrows(ScriptError.class,() -> m_app.getBean(JythonService.class,"error.py", null) .execute(Map.of("user","Homer Simpson")) ); } }
29.496
72
0.72498
3a69afc65d4dca948b1ce4dd1337bf762eb62937
1,009
/** * Copyright (c) 2015 https://github.com/howiefh * * Licensed under the Apache License, Version 2.0 (the "License"); */ package io.github.howiefh.jeews.modules.sys.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import org.springframework.hateoas.Link; import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.Resources; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; /** * * * @author howiefh */ public class ResourcesAssembler { /** * 将实体集entities转化为Resources * * @param entities * @param assembler * @param clazz * @return */ public static <T, D extends ResourceSupport> Resources<D> toResources(Iterable<T> entities, ResourceAssemblerSupport<T, D> assembler, Class<?> clazz) { Link link = linkTo(clazz).withSelfRel(); Resources<D> resources = new Resources<>(assembler.toResources(entities), link); return resources; } }
28.027778
95
0.703667
0c544070b4064cef36c59fdc052f1973757e7f1e
20,203
package hr.fer.zemris.jcms.desktop.satnica; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import hr.fer.zemris.jcms.parsers.TextService; import hr.fer.zemris.util.StringUtil; import hr.fer.zemris.util.time.DateStamp; import hr.fer.zemris.util.time.DateStampCache; import hr.fer.zemris.util.time.TemporalList; import hr.fer.zemris.util.time.TemporalNode; import hr.fer.zemris.util.time.TimeSpanCache; import hr.fer.zemris.util.time.TimeStampCache; import hr.fer.zemris.util.time.TemporalList.TL; public class PripremiSlobodneDvorane { /** * <p>Ovo je program koji se poziva iz komandne linije, i ne pakira se u web aplikaciju. * Program kao ulaz uzima format satnice koji dobijem, i pretvori/provjeri/prilagodi * ga formatu s kojim dalje mozemo raditi i obaviti ucitavanje. * * <p>Primjer poziva: C:/fer/ferko/dvorane_cupic_20080916.txt various-files/room_mappings.txt C:/fer/ferko/gen * * <p>Primjer ulazne datoteke sa satnicom: * <pre> * 17.9.2008;12:00:00;14:00:00;A101;Priprema s demosima iz DIGLOG * 17.9.2008;08:00:00;10:00:00;A111;Osnove elektrotehnike (1.02) * </pre> * @param args */ public static void main(String[] args) throws Exception { if(args.length!=3) { System.out.println("Krivi poziv! Zadajte zauzeca_ulaz, room_mappings_datoteku te zauzeca_izlaz."); System.exit(0); } Map<String,List<String>> roomMap = loadRoomMappings(args[1]); List<String> roomsList = new ArrayList<String>(); Set<String> allRooms = new HashSet<String>(50); List<RoomTermBean> all = new LinkedList<RoomTermBean>(); Set<RoomTermBean> allSet = new HashSet<RoomTermBean>(10000); InputStream is = new BufferedInputStream(new FileInputStream(args[0])); List<String> satnicaLines = TextService.inputStreamToUTF8StringList(is); for(String line : satnicaLines) { String[] elems = TextService.split(line, ';'); for(int i = 0; i < elems.length; i++) { elems[i] = elems[i].trim(); } String wrongDate = elems[0]; String start = elems[1].substring(0,5); String end = elems[2].substring(0,5); String room = elems[3]; String reason = elems[4]; String date = readDate(wrongDate); List<String> eventRooms = roomMap.get(room); if(eventRooms==null) { eventRooms = roomsList; eventRooms.clear(); eventRooms.add(room); } for(String currentRoom : eventRooms) { allRooms.add(currentRoom); } for(String currentRoom : eventRooms) { RoomTermBean bean = new RoomTermBean(); bean.date = date; bean.room = currentRoom; bean.start = start; bean.end = end; bean.reason = reason; if(allSet.add(bean)) { all.add(bean); } } } RoomTermBean bb; bb = new RoomTermBean("2008-09-29","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-09-30","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-01","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-02","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-03","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-04","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-05","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-06","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-07","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-08","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-09","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); bb = new RoomTermBean("2008-10-10","PCLAB3","09:00","17:00","SAP Boot Camp"); if(allSet.add(bb)) all.add(bb); for(File f : new File("C:/fer/ferko/vanjska").listFiles()) { System.out.println("Citam vanjska: "+f); is = new BufferedInputStream(new FileInputStream(f)); List<String> lines = TextService.inputStreamToUTF8StringList(is); for(String line : lines) { String[] elems = TextService.split(line, '\t'); for(int i = 0; i < elems.length; i++) { elems[i] = elems[i].trim(); } String start = elems[2].substring(0,5); String end = elems[3].substring(0,5); String room = elems[6]; String reason = f.getName(); String date = elems[1]; List<String> eventRooms = roomMap.get(room); if(eventRooms==null) { eventRooms = roomsList; eventRooms.clear(); eventRooms.add(room); } for(String currentRoom : eventRooms) { allRooms.add(currentRoom); } for(String currentRoom : eventRooms) { RoomTermBean bean = new RoomTermBean(); bean.date = date; bean.room = currentRoom; bean.start = start; bean.end = end; bean.reason = reason; if(allSet.add(bean)) { all.add(bean); } } } } Set<String> sveDvorane = new HashSet<String>(100); for(RoomTermBean bean : all) { sveDvorane.add(bean.room); } is = new BufferedInputStream(new FileInputStream("c:/usr/eclipse_workspaces/jcms_workspace/jcms/metadata/properties/initial-data/rooms.txt")); List<String> roomLines = TextService.inputStreamToUTF8StringList(is); BufferedWriter w4 = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(args[2],"TDvoraneIliKakoVec.csv"))))); for(String line : roomLines) { String[] elems = TextService.split(line, '\t'); for(int i = 0; i < elems.length; i++) { elems[i] = elems[i].trim(); } sveDvorane.add(elems[1]); w4.write(elems[1]); w4.write(";"); w4.write(elems[5]); w4.write("\r\n"); } w4.flush(); w4.close(); // Mapa<dvorana,Mapa<datum,RoomTermBean>> Map<String,Map<String,List<RoomTermBean>>> map = new HashMap<String, Map<String,List<RoomTermBean>>>(100); for(RoomTermBean rt : all) { Map<String,List<RoomTermBean>> m = map.get(rt.room); if(m==null) { m = new HashMap<String, List<RoomTermBean>>(100); map.put(rt.room, m); } List<RoomTermBean> l = m.get(rt.date); if(l==null) { l = new ArrayList<RoomTermBean>(); m.put(rt.date, l); } l.add(rt); } String fromDate = "2008-09-15"; String toDate = "2009-01-16"; Set<String> ignoredDates = new HashSet<String>(); ignoredDates.add("2008-10-08"); ignoredDates.add("2008-11-21"); ignoredDates.add("2009-01-06"); Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cal.setTime(sdf2.parse(fromDate+" 12:00:00")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); cal.setTime(sdf.parse(fromDate)); LinkedHashSet<String> allDates = new LinkedHashSet<String>(100); while(true) { String d = sdf.format(cal.getTime()); if(d.compareTo(toDate)>0) break; int dow = cal.get(Calendar.DAY_OF_WEEK); if(dow!=Calendar.SATURDAY && dow!=Calendar.SUNDAY) { boolean preskoci = false; if(d.compareTo("2008-10-13")>=0 && d.compareTo("2008-10-24")<=0) preskoci = true; if(d.compareTo("2008-11-24")>=0 && d.compareTo("2008-12-05")<=0) preskoci = true; if(d.compareTo("2008-12-20")>=0 && d.compareTo("2009-01-04")<=0) preskoci = true; if(!preskoci) { allDates.add(d); System.out.println("Dodao sam "+d); } } cal.add(Calendar.HOUR_OF_DAY, 24); } TimeSpanCache timeSpanCache = new TimeSpanCache(); TimeStampCache timeStampCache = new TimeStampCache(); DateStampCache dateStampCache = new DateStampCache(); BufferedWriter w1 = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(args[2],"TKadSuDvoraneZauzete.csv"))))); BufferedWriter w2 = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(args[2],"TKadSuDvoraneSlobodne.csv"))))); BufferedWriter w5 = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(args[2],"zauzece_dvorana_graficki.csv"))))); //List<String> dvorane = new ArrayList<String>(map.keySet()); List<String> dvorane = new ArrayList<String>(sveDvorane); Collections.sort(dvorane); for(String dvorana : dvorane) { Map<String,List<RoomTermBean>> m = map.get(dvorana); for(String datum : allDates) { TemporalList tlist = new TemporalList(timeSpanCache); if(m!=null) { List<RoomTermBean> l = m.get(datum); if(l!=null) { for(RoomTermBean rt : l) { tlist.addInterval( dateStampCache.get(datum), timeSpanCache.get(timeStampCache.get(rt.start), timeStampCache.get(rt.end)), rt.reason ); } } } Set<DateStamp> s = new HashSet<DateStamp>(); s.add(dateStampCache.get(datum)); TemporalList invtl = tlist.createInversionList(s, timeStampCache.get(8,0), timeStampCache.get(20,0)); TL t = tlist.getMap().get(dateStampCache.get(datum)); if(t!=null && t.first!=null) { TemporalNode n = t.first; while(n!=null) { w1.write(dvorana); w1.write(";"); w1.write(datum); w1.write(";"); w1.write(n.getTimeSpan().getStart().toString()); w1.write(";"); w1.write(n.getTimeSpan().getEnd().toString()); w1.write(";"); w1.write(n.getDescriptors().toString()); w1.write("\r\n"); n = n.getNext(); } n = t.first; int currPos = 8*4; int absEndPos = 20*4; w5.write(datum); w5.write(";"); while(n!=null) { int p = n.getTimeSpan().getStart().getHour()*4+(n.getTimeSpan().getStart().getMinute()%15); int e = n.getTimeSpan().getEnd().getHour()*4+(n.getTimeSpan().getEnd().getMinute()%15); while(currPos<p && currPos<absEndPos) { if(currPos%4==0) w5.write("|"); w5.write(" "); currPos++; } while(currPos<e && currPos<absEndPos) { if(currPos%4==0) w5.write("|"); w5.write("*"); currPos++; } n = n.getNext(); } while(currPos<absEndPos) { if(currPos%4==0) w5.write("|"); w5.write(" "); currPos++; } w5.write("; "); w5.write(dvorana); w5.write("\r\n"); } else { int currPos = 8*4; int absEndPos = 20*4; w5.write(datum); w5.write(";"); while(currPos<absEndPos) { if(currPos%4==0) w5.write("|"); w5.write(" "); currPos++; } w5.write("; "); w5.write(dvorana); w5.write("\r\n"); } t = invtl.getMap().get(dateStampCache.get(datum)); if(t!=null && t.first!=null) { TemporalNode n = t.first; while(n!=null) { w2.write(dvorana); w2.write(";"); w2.write(datum); w2.write(";"); w2.write(n.getTimeSpan().getStart().toString()); w2.write(";"); w2.write(n.getTimeSpan().getEnd().toString()); w2.write("\r\n"); n = n.getNext(); } } } } w1.flush(); w1.close(); w2.flush(); w2.close(); w5.flush(); w5.close(); BufferedWriter w3full = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(args[2],"TZauzetostStudenataFull.csv"))))); BufferedWriter w3 = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(args[2],"TZauzetostStudenata.csv"))))); BufferedReader r = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream("C:/fer/ferko/tmpGen/zauzetost.csv")))); while(true) { String line = r.readLine(); if(line==null) break; if(line.trim().length()==0) continue; String[] elems = StringUtil.split(line, ';'); for(int i = 0; i < elems.length; i++) { elems[i] = elems[i].trim(); } w3.write(elems[0]); w3.write(";"); w3.write(elems[1]); w3.write(";"); w3.write(elems[2]); w3.write(";"); w3.write(elems[3]); w3.write("\r\n"); w3full.write(elems[0]); w3full.write(";"); w3full.write(elems[1]); w3full.write(";"); w3full.write(elems[2]); w3full.write(";"); w3full.write(elems[3]); w3full.write(";"); w3full.write(elems[4]); w3full.write("\r\n"); } r.close(); for(File f : new File("C:/fer/ferko/vanjska").listFiles()) { r = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(f)))); while(true) { String line = r.readLine(); if(line==null) break; if(line.trim().length()==0) continue; String[] elems = StringUtil.split(line, '\t'); for(int i = 0; i < elems.length; i++) { elems[i] = elems[i].trim(); } w3.write(elems[0]); w3.write(";"); w3.write(elems[1]); w3.write(";"); w3.write(elems[2]); w3.write(";"); w3.write(elems[3]); w3.write("\r\n"); w3full.write(elems[0]); w3full.write(";"); w3full.write(elems[1]); w3full.write(";"); w3full.write(elems[2]); w3full.write(";"); w3full.write(elems[3]); w3full.write(";"); w3full.write(elems[4]); w3full.write("/"); w3full.write(elems[5]); w3full.write("/"); w3full.write(elems[6]); w3full.write("\r\n"); } r.close(); } w3.flush(); w3.close(); w3full.flush(); w3full.close(); r = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream("C:/fer/ferko/tmpGen/zauzetost.csv")))); Map<String,Map<String,TemporalList>> opterecenja = new HashMap<String, Map<String,TemporalList>>(5000); while(true) { String line = r.readLine(); if(line==null) break; if(line.trim().length()==0) continue; String[] elems = StringUtil.split(line, ';'); for(int i = 0; i < elems.length; i++) { elems[i] = elems[i].trim(); } String jmbag = elems[0]; String datum = elems[1]; String pocetak = elems[2]; String kraj = elems[3]; String razlog = elems[4].substring(elems[4].indexOf('|')+1); Map<String,TemporalList> zaStudenta = opterecenja.get(jmbag); if(zaStudenta==null) { zaStudenta = new HashMap<String, TemporalList>(allDates.size()); opterecenja.put(jmbag, zaStudenta); } TemporalList tl = zaStudenta.get(datum); if(tl==null) { tl = new TemporalList(timeSpanCache); zaStudenta.put(datum, tl); } tl.addInterval(dateStampCache.get(datum), timeSpanCache.get(timeStampCache.get(pocetak), timeStampCache.get(kraj)), razlog); } r.close(); for(File f : new File("C:/fer/ferko/vanjska").listFiles()) { r = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(f)))); while(true) { String line = r.readLine(); if(line==null) break; if(line.trim().length()==0) continue; String[] elems = StringUtil.split(line, '\t'); for(int i = 0; i < elems.length; i++) { elems[i] = elems[i].trim(); } String jmbag = elems[0]; String datum = elems[1]; String pocetak = elems[2]; String kraj = elems[3]; String razlog = elems[4]+" / "+elems[5]+" / "+elems[6]; Map<String,TemporalList> zaStudenta = opterecenja.get(jmbag); if(zaStudenta==null) { zaStudenta = new HashMap<String, TemporalList>(allDates.size()); opterecenja.put(jmbag, zaStudenta); } TemporalList tl = zaStudenta.get(datum); if(tl==null) { tl = new TemporalList(timeSpanCache); zaStudenta.put(datum, tl); } tl.addInterval(dateStampCache.get(datum), timeSpanCache.get(timeStampCache.get(pocetak), timeStampCache.get(kraj)), razlog); } r.close(); } w3full = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(args[2],"TZauzetostStudenataFull2.csv"))))); w3 = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(new File(args[2],"TZauzetostStudenata2.csv"))))); List<String> jmbags = new ArrayList<String>(opterecenja.keySet()); Collections.sort(jmbags); List<String> datumi = new ArrayList<String>(allDates); Collections.sort(datumi); for(String jmbag : jmbags) { Map<String,TemporalList> zaStudenta = opterecenja.get(jmbag); if(zaStudenta==null) continue; for(String datum : datumi) { TemporalList tl = zaStudenta.get(datum); if(tl==null) continue; if(tl.getMap().isEmpty()) continue; // Inace je samo jedan datum unutra... TL t = tl.getMap().entrySet().iterator().next().getValue(); TemporalNode n = t.first; while(n!=null) { TemporalNode last = n; while(last.getNext()!=null && last.getNext().getTimeSpan().getStart().equals(n.getTimeSpan().getEnd())) { last = last.getNext(); } w3.write(jmbag); w3.write(";"); w3.write(datum); w3.write(";"); w3.write(n.getTimeSpan().getStart().toString()); w3.write(";"); w3.write(last.getTimeSpan().getEnd().toString()); w3.write("\r\n"); n = last.getNext(); } } } w3.flush(); w3.close(); w3full.flush(); w3full.close(); } static class RoomTermBean { String date; String start; String end; String room; String reason; public RoomTermBean() { } public RoomTermBean(String date, String room, String start, String end, String reason) { super(); this.date = date; this.room = room; this.start = start; this.end = end; this.reason = reason; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((date == null) ? 0 : date.hashCode()); result = prime * result + ((end == null) ? 0 : end.hashCode()); result = prime * result + ((room == null) ? 0 : room.hashCode()); result = prime * result + ((start == null) ? 0 : start.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RoomTermBean other = (RoomTermBean) obj; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; if (end == null) { if (other.end != null) return false; } else if (!end.equals(other.end)) return false; if (room == null) { if (other.room != null) return false; } else if (!room.equals(other.room)) return false; if (start == null) { if (other.start != null) return false; } else if (!start.equals(other.start)) return false; return true; } } private static String readDate(String wrongDate) { String[] elems = wrongDate.split("\\."); StringBuilder sb = new StringBuilder(10); sb.append(elems[2]); sb.append('-'); if(elems[1].length()<2) sb.append('0'); sb.append(elems[1]); sb.append('-'); if(elems[0].length()<2) sb.append('0'); sb.append(elems[0]); if(sb.length()!=10) { System.out.println("Pogresan datum: "+wrongDate); } return sb.toString(); } private static Map<String, List<String>> loadRoomMappings(String fileName) throws IOException { Map<String,List<String>> roomMap = new HashMap<String, List<String>>(); InputStream is = new BufferedInputStream(new FileInputStream(fileName)); List<String> mappingLines = TextService.inputStreamToUTF8StringList(is); for(String line : mappingLines) { String[] elems = TextService.split(line, '\t'); List<String> l = new ArrayList<String>(); for(int i = 1; i < elems.length; i++) { l.add(elems[i]); } roomMap.put(elems[0], l); } return roomMap; } }
33.119672
166
0.640895
92328de19865e85cca2aa3af43eeb530c76f65f7
1,362
/* * Copyright 2020 ThoughtWorks, 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.thoughtworks.go.apiv2.rolesconfig.representers; import com.thoughtworks.go.api.base.OutputWriter; import com.thoughtworks.go.config.Role; import com.thoughtworks.go.spark.Routes; import java.util.List; public class RolesRepresenter { public static void toJSON(OutputWriter writer, List<Role> roles) { writer.addLinks( outputLinkWriter -> outputLinkWriter.addAbsoluteLink("doc", Routes.Roles.DOC) .addLink("find", Routes.Roles.find()) .addLink("self", Routes.Roles.BASE)) .addChild("_embedded", embeddedWriter -> embeddedWriter.addChildList("roles", rolesWriter -> roles.forEach(role -> rolesWriter.addChild(roleWriter -> RoleRepresenter.toJSON(roleWriter, role))))); } }
38.914286
207
0.723935
bbc7798c5d8cf0bfd29599226b2ad8623a0a0953
21,083
package org.drools.examples; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumnModel; import org.drools.FactException; import org.drools.RuleBase; import org.drools.RuleBaseFactory; import org.drools.WorkingMemory; import org.drools.compiler.PackageBuilder; public class PetStore { public static void main(String[] args) { try { // RuleSetLoader ruleSetLoader = new RuleSetLoader(); // ruleSetLoader.addFromUrl( PetStore.class.getResource( args[0] ) ); // // RuleBaseLoader ruleBaseLoader = new RuleBaseLoader(); // ruleBaseLoader.addFromRuleSetLoader( ruleSetLoader ); // RuleBase ruleBase = ruleBaseLoader.buildRuleBase(); PackageBuilder builder = new PackageBuilder(); builder.addPackageFromDrl( new InputStreamReader( PetStore.class.getResourceAsStream( "PetStore.drl" ) ) ); RuleBase ruleBase = RuleBaseFactory.newRuleBase(); ruleBase.addPackage( builder.getPackage() ); //RuleB Vector stock = new Vector(); stock.add( new Product( "Gold Fish", 5 ) ); stock.add( new Product( "Fish Tank", 25 ) ); stock.add( new Product( "Fish Food", 2 ) ); //The callback is responsible for populating working memory and // fireing all rules PetStoreUI ui = new PetStoreUI( stock, new CheckoutCallback( ruleBase ) ); ui.createAndShowGUI(); } catch ( Exception e ) { e.printStackTrace(); } } /** * This swing UI is used to create a simple shopping cart to allow a user to add * and remove items from a shopping cart before doign a checkout upon doing a * checkout a callback is used to allow drools interaction with the shopping * cart ui. */ public static class PetStoreUI extends JPanel { private JTextArea output; private TableModel tableModel; private CheckoutCallback callback; /** * Build UI using specified items and using the given callback to pass the * items and jframe reference to the drools application * * @param listData * @param callback */ public PetStoreUI(Vector items, CheckoutCallback callback) { super( new BorderLayout() ); this.callback = callback; //Create main vertical split panel JSplitPane splitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT ); add( splitPane, BorderLayout.CENTER ); //create top half of split panel and add to parent JPanel topHalf = new JPanel(); topHalf.setLayout( new BoxLayout( topHalf, BoxLayout.X_AXIS ) ); topHalf.setBorder( BorderFactory.createEmptyBorder( 5, 5, 0, 5 ) ); topHalf.setMinimumSize( new Dimension( 400, 50 ) ); topHalf.setPreferredSize( new Dimension( 450, 250 ) ); splitPane.add( topHalf ); //create bottom top half of split panel and add to parent JPanel bottomHalf = new JPanel( new BorderLayout() ); bottomHalf.setMinimumSize( new Dimension( 400, 50 ) ); bottomHalf.setPreferredSize( new Dimension( 450, 300 ) ); splitPane.add( bottomHalf ); //Container that list container that shows available store items JPanel listContainer = new JPanel( new GridLayout( 1, 1 ) ); listContainer.setBorder( BorderFactory.createTitledBorder( "List" ) ); topHalf.add( listContainer ); //Create JList for items, add to scroll pane and then add to parent // container JList list = new JList( items ); ListSelectionModel listSelectionModel = list.getSelectionModel(); listSelectionModel.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); //handler adds item to shopping cart list.addMouseListener( new ListSelectionHandler() ); JScrollPane listPane = new JScrollPane( list ); listContainer.add( listPane ); JPanel tableContainer = new JPanel( new GridLayout( 1, 1 ) ); tableContainer.setBorder( BorderFactory.createTitledBorder( "Table" ) ); topHalf.add( tableContainer ); //Container that displays table showing items in cart tableModel = new TableModel(); JTable table = new JTable( tableModel ); //handler removes item to shopping cart table.addMouseListener( new TableSelectionHandler() ); ListSelectionModel tableSelectionModel = table.getSelectionModel(); tableSelectionModel.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); TableColumnModel tableColumnModel = table.getColumnModel(); //notice we have a custom renderer for each column as both columns // point to the same underlying object tableColumnModel.getColumn( 0 ).setCellRenderer( new NameRenderer() ); tableColumnModel.getColumn( 1 ).setCellRenderer( new PriceRenderer() ); tableColumnModel.getColumn( 1 ).setMaxWidth( 50 ); JScrollPane tablePane = new JScrollPane( table ); tablePane.setPreferredSize( new Dimension( 150, 100 ) ); tableContainer.add( tablePane ); //Create panel for checkout button and add to bottomHalf parent JPanel checkoutPane = new JPanel(); JButton button = new JButton( "Checkout" ); button.setVerticalTextPosition( AbstractButton.CENTER ); button.setHorizontalTextPosition( AbstractButton.LEADING ); //attach handler to assert items into working memory button.addMouseListener( new CheckoutButtonHandler() ); button.setActionCommand( "checkout" ); checkoutPane.add( button ); bottomHalf.add( checkoutPane, BorderLayout.NORTH ); button = new JButton( "Reset" ); button.setVerticalTextPosition( AbstractButton.CENTER ); button.setHorizontalTextPosition( AbstractButton.TRAILING ); //attach handler to assert items into working memory button.addMouseListener( new ResetButtonHandler() ); button.setActionCommand( "reset" ); checkoutPane.add( button ); bottomHalf.add( checkoutPane, BorderLayout.NORTH ); //Create output area, imbed in scroll area an add to bottomHalf parent //Scope is at instance level so it can be easily referenced from other // methods output = new JTextArea( 1, 10 ); output.setEditable( false ); JScrollPane outputPane = new JScrollPane( output, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ); bottomHalf.add( outputPane, BorderLayout.CENTER ); this.callback.setOutput( this.output ); } /** * Create and show the GUI * */ public void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame( "Pet Store Demo" ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setOpaque( true ); frame.setContentPane( this ); //Display the window. frame.pack(); frame.setVisible( true ); } /** * Adds the selected item to the table */ private class ListSelectionHandler extends MouseAdapter { public void mouseReleased(MouseEvent e) { JList jlist = (JList) e.getSource(); tableModel.addItem( (Product) jlist.getSelectedValue() ); } } /** * Removes the selected item from the table */ private class TableSelectionHandler extends MouseAdapter { public void mouseReleased(MouseEvent e) { JTable jtable = (JTable) e.getSource(); TableModel tableModel = (TableModel) jtable.getModel(); tableModel.removeItem( jtable.getSelectedRow() ); } } /** * Calls the referenced callback, passing a the jrame and selected items. * */ private class CheckoutButtonHandler extends MouseAdapter { public void mouseReleased(MouseEvent e) { JButton button = (JButton) e.getComponent(); try { // output.append( callback.checkout( (JFrame) button.getTopLevelAncestor(), // tableModel.getItems() ) ); callback.checkout( (JFrame) button.getTopLevelAncestor(), tableModel.getItems() ); } catch ( org.drools.FactException fe ) { fe.printStackTrace(); } } } /** * Resets the shopping cart, allowing the user to begin again. * */ private class ResetButtonHandler extends MouseAdapter { public void mouseReleased(MouseEvent e) { JButton button = (JButton) e.getComponent(); output.setText( null ); tableModel.clear(); System.out.println( "------ Reset ------" ); } } /** * Used to render the name column in the table */ private class NameRenderer extends DefaultTableCellRenderer { public NameRenderer() { super(); } public void setValue(Object object) { Product item = (Product) object; setText( item.getName() ); } } /** * Used to render the price column in the table */ private class PriceRenderer extends DefaultTableCellRenderer { public PriceRenderer() { super(); } public void setValue(Object object) { Product item = (Product) object; setText( Double.toString( item.getPrice() ) ); } } } /** * This is the table model used to represent the users shopping cart While * we have two colums, both columns point to the same object. We user a * different renderer to display the different information abou the object - * name and price. */ private static class TableModel extends AbstractTableModel { private String[] columnNames = {"Name", "Price"}; private ArrayList items; public TableModel() { super(); items = new ArrayList(); } public int getColumnCount() { return columnNames.length; } public int getRowCount() { return items.size(); } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return items.get( row ); } public Class getColumnClass(int c) { return Product.class; } public void addItem(Product item) { items.add( item ); fireTableRowsInserted( items.size(), items.size() ); } public void removeItem(int row) { items.remove( row ); fireTableRowsDeleted( row, row ); } public List getItems() { return items; } public void clear() { int lastRow = items.size(); items.clear(); fireTableRowsDeleted( 0, lastRow ); } } /** * * This callback is called when the user pressed the checkout button. It is * responsible for adding the items to the shopping cart, asserting the shopping * cart and then firing all rules. * * A reference to the JFrame is also passed so the rules can launch dialog boxes * for user interaction. It uses the ApplicationData feature for this. * */ public static class CheckoutCallback { RuleBase ruleBase; JTextArea output; public CheckoutCallback(RuleBase ruleBase) { this.ruleBase = ruleBase; } public void setOutput(JTextArea output) { this.output = output; } /** * Populate the cart and assert into working memory Pass Jframe reference * for user interaction * * @param frame * @param items * @return cart.toString(); */ public String checkout(JFrame frame, List items) throws FactException { Order order = new Order(); //Iterate through list and add to cart for ( int i = 0; i < items.size(); i++ ) { order.addItem( new Purchase( order, (Product) items.get( i ) ) ); } //add the JFrame to the ApplicationData to allow for user interaction WorkingMemory workingMemory = ruleBase.newStatefulSession(); workingMemory.setGlobal( "frame", frame ); workingMemory.setGlobal( "textArea", this.output ); workingMemory.insert( new Product( "Gold Fish", 5 ) ); workingMemory.insert( new Product( "Fish Tank", 25 ) ); workingMemory.insert( new Product( "Fish Food", 2 ) ); workingMemory.insert( new Product( "Fish Food Sample", 0 ) ); workingMemory.insert( order ); workingMemory.fireAllRules(); //returns the state of the cart return order.toString(); } } public static class Order { private List items; private double grossTotal = -1; private double discountedTotal = -1; private static String newline = System.getProperty( "line.separator" ); public Order() { this.items = new ArrayList(); } public void addItem(Purchase item) { this.items.add( item ); } public List getItems() { return this.items; } public void setGrossTotal(double grossCost) { this.grossTotal = grossCost; } public double getGrossTotal() { return this.grossTotal; } public void setDiscountedTotal(double discountedCost) { this.discountedTotal = discountedCost; } public double getDiscountedTotal() { return this.discountedTotal; } public String toString() { StringBuffer buf = new StringBuffer(); buf.append( "ShoppingCart:" + newline ); Iterator itemIter = getItems().iterator(); while ( itemIter.hasNext() ) { buf.append( "\t" + itemIter.next() + newline ); } // buf.append( "gross total=" + getGrossCost() + newline ); // buf.append( "discounted total=" + getDiscountedCost() + newline ); return buf.toString(); } } public static class Purchase { private Order order; private Product product; public Purchase(Order order, Product product) { super(); this.order = order; this.product = product; } public Order getOrder() { return order; } public Product getProduct() { return product; } public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((order == null) ? 0 : order.hashCode()); result = PRIME * result + ((product == null) ? 0 : product.hashCode()); return result; } public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; final Purchase other = (Purchase) obj; if ( order == null ) { if ( other.order != null ) return false; } else if ( !order.equals( other.order ) ) return false; if ( product == null ) { if ( other.product != null ) return false; } else if ( !product.equals( other.product ) ) return false; return true; } } public static class Product { private String name; private double price; public Product(String name, double cost) { this.name = name; this.price = cost; } public String getName() { return this.name; } public double getPrice() { return this.price; } public String toString() { return name + " " + this.price; } public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((name == null) ? 0 : name.hashCode()); long temp; temp = Double.doubleToLongBits( price ); result = PRIME * result + (int) (temp ^ (temp >>> 32)); return result; } public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; final Product other = (Product) obj; if ( name == null ) { if ( other.name != null ) return false; } else if ( !name.equals( other.name ) ) return false; if ( Double.doubleToLongBits( price ) != Double.doubleToLongBits( other.price ) ) return false; return true; } } }
36.729965
120
0.51136
ff95ac58d3d0e35e26a1f07f771549e33971b11f
312
package org.yserver.utils.log4j; import org.apache.log4j.Priority; public class DailyRollingFileAppender extends org.apache.log4j.DailyRollingFileAppender { public boolean isAsSevereAsThreshold(Priority priority) { //只判断是否相等,而不判断优先级 return this.getThreshold().equals(priority); } }
24
87
0.753205
9f5e92b7b6c11352e4b7cba403334c8b5dfb2af5
1,078
package com.google.android.cameraview.demo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; /** * Created by kaelma on 2018/7/25. */ public class SplashActivity extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_activity); findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SplashActivity.this, Camera1Activity.class); startActivity(intent); } }); findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SplashActivity.this, Camera2Activity.class); startActivity(intent); } }); } }
29.944444
87
0.648423
df7b4b09307d62b1d922b70841c972444fda25e8
1,853
package com.valhallagame.ymer.controller; import com.fasterxml.jackson.databind.JsonNode; import com.valhallagame.common.JS; import com.valhallagame.currencyserviceclient.CurrencyServiceClient; import com.valhallagame.currencyserviceclient.message.AddCurrencyParameter; import com.valhallagame.currencyserviceclient.message.SubtractCurrencyParameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; @Controller @RequestMapping("/v1/server-currency") public class ServerCurrencyController { private static final Logger logger = LoggerFactory.getLogger(ServerCurrencyController.class); @Autowired private CurrencyServiceClient currencyServiceClient; @PostMapping("/add-currency") @ResponseBody public ResponseEntity<JsonNode> addCurrency(@RequestBody AddCurrencyParameter input) throws IOException { logger.info("Add Currency called with {}", input); return JS.message(currencyServiceClient.addCurrency(input.getCharacterName(), input.getCurrencyType(), input.getAmount())); } @PostMapping("/subtract-currency") @ResponseBody public ResponseEntity<JsonNode> subtractCurrency(@RequestBody SubtractCurrencyParameter input) throws IOException { logger.info("Subtract Currency called with {}", input); return JS.message(currencyServiceClient.subtractCurrency(input.getCharacterName(), input.getCurrencyType(), input.getAmount())); } }
44.119048
136
0.810577
e815e60844c718abf320b10edca545b6b19a63db
2,314
package bepler.lrpage.parser; import java.util.Arrays; import bepler.lrpage.grammar.Rule; public class Item { private final Rule rule; private final String lookahead; private final int index; public Item(Rule rule, String lookahead){ this(0, rule, lookahead); } public Item(int index, Rule rule, String lookahead){ this.rule = rule; this.lookahead = lookahead; this.index = index; } public Rule getRule(){ return rule; } public Item increment(){ return new Item(index+1, rule, lookahead); } public String[] alpha(){ String[] alpha = new String[index]; for( int i = 0 ; i < index ; ++i ){ alpha[i] = rule.rightHandSide()[i]; } return alpha; } public String[] beta(){ String[] rhs = rule.rightHandSide(); String[] beta = new String[rhs.length - index - 1]; for( int i = index + 1 ; i < rhs.length ; ++i ){ beta[i-index-1] = rhs[i]; } return beta; } public boolean hasNextSymbol(){ return index < rule.rightHandSide().length; } public String nextSymbol(){ return rule.rightHandSide()[index]; } public boolean hasPrevSymbol(){ return index > 0; } public String prevSymbol(){ return rule.rightHandSide()[index-1]; } public String lookahead(){ return lookahead; } @Override public String toString(){ return rule.leftHandSide() + " -> (" + this.rhsToString() + "), ["+lookahead+"]"; } private String rhsToString(){ String[] rhs = rule.rightHandSide(); StringBuilder builder = new StringBuilder(); for( int i = 0; i < rhs.length ; ++i ){ if(i != 0){ builder.append(" "); } if(i == index){ builder.append(". "); } builder.append(rhs[i]); } if(index == rhs.length){ builder.append(" ."); } return builder.toString(); } @Override public int hashCode(){ return Arrays.deepHashCode(new Object[]{rule, lookahead, index}); } @Override public boolean equals(Object o){ if(o == null) return false; if(o == this) return true; if(o instanceof Item){ Item that = (Item) o; return equals(this.rule, that.rule) && this.index == that.index && equals(this.lookahead, that.lookahead); } return false; } private static boolean equals(Object o1, Object o2){ if(o1 == o2) return true; if(o1 == null || o2 == null) return false; return o1.equals(o2); } }
20.477876
109
0.63656
166a1e6bdd8a160e9b6ead04e1d322d9ec4e43d2
589
package com.sinoyd.demo.repository; import com.sinoyd.demo.entity.Employee; import org.springframework.data.repository.CrudRepository; import java.util.Collection; import java.util.List; /** * @Description * @auther 李忠杰 * @create 2019-01-28 16:50 */ public interface EmployeeRepository extends CrudRepository<Employee,Integer>{ Integer deleteByEmployeeIdIn(Collection<Integer> ids); Employee findByEmployeeCode(String employeeCode); List<Employee> findByEmployeeIdIn(Collection<Integer> employeeIds); List<Employee> findByEmployeeNameLike(String employeeName); }
25.608696
77
0.789474
eab65b1345393605c719789579c4138e96ee0054
812
package com.fireflysource.net.http.common.v2.frame; import java.util.HashMap; import java.util.Map; public enum FrameType { DATA(0), HEADERS(1), PRIORITY(2), RST_STREAM(3), SETTINGS(4), PUSH_PROMISE(5), PING(6), GO_AWAY(7), WINDOW_UPDATE(8), CONTINUATION(9), // Synthetic frames only needed by the implementation. PREFACE(10), DISCONNECT(11), FAILURE(12); private final int type; private FrameType(int type) { this.type = type; Types.types.put(type, this); } public static FrameType from(int type) { return Types.types.get(type); } public int getType() { return type; } private static class Types { private static final Map<Integer, FrameType> types = new HashMap<>(); } }
19.804878
77
0.615764
40155014c1cd9073f2d6ff7a7b3b466a0ade176e
344
package com.apachetune.core.ui.feedbacksystem; import com.apachetune.core.ui.NView; /** * FIXDOC */ public interface UserFeedbackView extends NView { enum Result {USER_ACCEPTED_SENDING, USER_REJECTED_SENDING} Result getResult(); String getUserMessage(); void setUserEmail(String userEmail); String getUserEmail(); }
18.105263
62
0.741279
26272b1056f771791d73b10c7f00e50e5497bd62
638
package com.readlearncode.priority; import com.readlearncode.async.AuditEvent; import javax.annotation.PostConstruct; import javax.ejb.Startup; import javax.ejb.Singleton; import javax.enterprise.event.Event; import javax.inject.Inject; import static com.readlearncode.async.AuditEvent.Priority.HIGH; /** * Source code github.com/readlearncode * * @author Alex Theedom www.readlearncode.com * @version 1.0 */ @Singleton @Startup public class AuditEventSender { @Inject private Event<AuditEvent> event; @PostConstruct public void send() { event.fire(new AuditEvent("Security Violation", HIGH)); } }
19.9375
63
0.749216
fde99cee369ea2d69bb75359ff1be54b1de37fe5
922
package obscurum.creatures.ai; import java.awt.Point; import java.util.ArrayList; import obscurum.creatures.Creature; import obscurum.creatures.ai.CreatureAI; import obscurum.environment.Level; import obscurum.environment.foreground.ForegroundTile; /** * This models the behaviour of dead creatures. * @author Alex Ghita */ public class CorpseAI extends CreatureAI { private int turnsLeft; public CorpseAI(Creature creature) { super("Corpse", creature, CreatureAI.SIMPLE, new ArrayList<ForegroundTile>()); turnsLeft = 50; } public int getTurnsLeft() { return turnsLeft; } @Override public void onEnter(Point p) {} @Override public void onUpdate() { while (creature.getCombatCooldown() > 0) { creature.decrementCombatCooldown(); } if (creature.getInventory().countFilledSlots() == 0) { turnsLeft = Math.min(10, turnsLeft); } turnsLeft--; } }
22.487805
58
0.706074
a0a941a17ae9f4ae631d544004a12a2e9b109d2a
1,109
package opg.softuni.fdmc.beans; import opg.softuni.fdmc.domain.dto.CatViewDto; import opg.softuni.fdmc.services.CatService; import opg.softuni.fdmc.util.ApplicationUtils; import opg.softuni.fdmc.util.GenericComparator; import javax.inject.Inject; import javax.inject.Named; import java.beans.IntrospectionException; import java.util.List; @Named(value = "allCats") public class AllCatsBean { private final CatService employeeService; @Inject public AllCatsBean(CatService employeeService) { this.employeeService = employeeService; } public List<CatViewDto> getListOfCats() { List<CatViewDto> allCats = this.employeeService.listAllCats(); String field = ApplicationUtils.getRequest().getParameter("sort"); if(field == null){ return allCats; }else{ try { return GenericComparator.compare(allCats,field, CatViewDto.class); } catch (ReflectiveOperationException | IntrospectionException e) { // e.printStackTrace(); return allCats; } } } }
26.404762
82
0.678088
98f82165f3417117d06bc541ac1d8f4869559292
5,748
/* * Consumer Data Standards * Sample client library to Demonstrate the Consumer Data Right APIs * * NOTE: This class is auto generated by the codegen artefact * https://github.com/ConsumerDataStandardsAustralia/java-artefacts/codegen */ package au.org.consumerdatastandards.client.model; import java.math.BigDecimal; import java.util.Objects; /** * Defines the sub-tier criteria and conditions for which a rate applies */ public class BankingProductRateTierSubTier { public enum UnitOfMeasure { DOLLAR, PERCENT, MONTH, DAY } public enum RateApplicationMethod { WHOLE_BALANCE, PER_TIER } private String name; private UnitOfMeasure unitOfMeasure; private BigDecimal minimumValue; private BigDecimal maximumValue; private RateApplicationMethod rateApplicationMethod; private BankingProductRateCondition applicabilityConditions; /** * A display name for the tier * @return name */ public String getName() { return name; } public void setName(String name) { this.name = name; } /** * The unit of measure that applies to the tierValueMinimum and tierValueMaximum values e.g. a **DOLLAR** amount. **PERCENT** (in the case of loan-to-value ratio or LVR). Tier term period representing a discrete number of **MONTH**&#39;s or **DAY**&#39;s (in the case of term deposit tiers) * @return unitOfMeasure */ public UnitOfMeasure getUnitOfMeasure() { return unitOfMeasure; } public void setUnitOfMeasure(UnitOfMeasure unitOfMeasure) { this.unitOfMeasure = unitOfMeasure; } /** * The number of tierUnitOfMeasure units that form the lower bound of the tier. The tier should be inclusive of this value * @return minimumValue */ public BigDecimal getMinimumValue() { return minimumValue; } public void setMinimumValue(BigDecimal minimumValue) { this.minimumValue = minimumValue; } /** * The number of tierUnitOfMeasure units that form the upper bound of the tier or band. For a tier with a discrete value (as opposed to a range of values e.g. 1 month) this must be the same as tierValueMinimum. Where this is the same as the tierValueMinimum value of the next-higher tier the referenced tier should be exclusive of this value. For example a term deposit of 2 months falls into the upper tier of the following tiers: (1 – 2 months, 2 – 3 months) * @return maximumValue */ public BigDecimal getMaximumValue() { return maximumValue; } public void setMaximumValue(BigDecimal maximumValue) { this.maximumValue = maximumValue; } /** * The method used to calculate the amount to be applied using one or more tiers. A single rate may be applied to the entire balance or each applicable tier rate is applied to the portion of the balance that falls into that tier (referred to as &#39;bands&#39; or &#39;steps&#39;) * @return rateApplicationMethod */ public RateApplicationMethod getRateApplicationMethod() { return rateApplicationMethod; } public void setRateApplicationMethod(RateApplicationMethod rateApplicationMethod) { this.rateApplicationMethod = rateApplicationMethod; } /** * Get applicabilityConditions * @return applicabilityConditions */ public BankingProductRateCondition getApplicabilityConditions() { return applicabilityConditions; } public void setApplicabilityConditions(BankingProductRateCondition applicabilityConditions) { this.applicabilityConditions = applicabilityConditions; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BankingProductRateTierSubTier bankingProductRateTierSubTier = (BankingProductRateTierSubTier) o; return Objects.equals(this.name, bankingProductRateTierSubTier.name) && Objects.equals(this.unitOfMeasure, bankingProductRateTierSubTier.unitOfMeasure) && Objects.equals(this.minimumValue, bankingProductRateTierSubTier.minimumValue) && Objects.equals(this.maximumValue, bankingProductRateTierSubTier.maximumValue) && Objects.equals(this.rateApplicationMethod, bankingProductRateTierSubTier.rateApplicationMethod) && Objects.equals(this.applicabilityConditions, bankingProductRateTierSubTier.applicabilityConditions); } @Override public int hashCode() { return Objects.hash( name, unitOfMeasure, minimumValue, maximumValue, rateApplicationMethod, applicabilityConditions); } @Override public String toString() { return "class BankingProductRateTierSubTier {\n" + " name: " + toIndentedString(name) + "\n" + " unitOfMeasure: " + toIndentedString(unitOfMeasure) + "\n" + " minimumValue: " + toIndentedString(minimumValue) + "\n" + " maximumValue: " + toIndentedString(maximumValue) + "\n" + " rateApplicationMethod: " + toIndentedString(rateApplicationMethod) + "\n" + " applicabilityConditions: " + toIndentedString(applicabilityConditions) + "\n" + "}"; } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
35.04878
464
0.671712
cc43671843d856343872d9ce5485a0e12e4aebab
2,550
/* * Copyright (C) 2017-2018 Dremio Corporation * * 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.dremio.exec.planner.logical; import java.util.Set; import org.apache.calcite.rel.RelNode; import com.dremio.common.logical.LogicalPlan; import com.dremio.common.logical.LogicalPlanBuilder; import com.dremio.common.logical.PlanProperties.Generator.ResultMode; import com.dremio.common.logical.PlanProperties.PlanType; import com.dremio.common.logical.data.LogicalOperator; import com.dremio.common.logical.data.visitors.AbstractLogicalVisitor; import com.google.common.collect.Sets; /** * Context for converting a tree of {@link Rel} nodes into a Dremio logical plan. */ public class LogicalPlanImplementor { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LogicalPlanImplementor.class); private Set<String> storageEngineNames = Sets.newHashSet(); private LogicalPlanBuilder planBuilder = new LogicalPlanBuilder(); private LogicalPlan plan; private final ParseContext context; public LogicalPlanImplementor(ParseContext context, ResultMode mode) { planBuilder.planProperties(PlanType.LOGICAL, 1, LogicalPlanImplementor.class.getName(), "", mode); this.context = context; } public ParseContext getContext(){ return context; } public void go(Rel root) { LogicalOperator rootLOP = root.implement(this); rootLOP.accept(new AddOpsVisitor(), null); } public LogicalPlan getPlan(){ if(plan == null){ plan = planBuilder.build(); planBuilder = null; } return plan; } public LogicalOperator visitChild(Rel parent, int ordinal, RelNode child) { return ((Rel) child).implement(this); } private class AddOpsVisitor extends AbstractLogicalVisitor<Void, Void, RuntimeException> { @Override public Void visitOp(LogicalOperator op, Void value) throws RuntimeException { planBuilder.addLogicalOperator(op); for(LogicalOperator o : op){ o.accept(this, null); } return null; } } }
31.481481
105
0.743922
36abd6aa92fa6f8eab8d46915d920a06c6efea6a
603
package br.com.thiago.robotPi.model; import javax.persistence.Entity; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity public class Empresa { @Id @GenericGenerator(name = "id", strategy = "uuid2") private String id; private String nome; private String cep; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } }
16.75
51
0.699834
a48256fcedc09ae640064ce5baa50a8bacb264df
1,012
package com.paperplay.myformbuilder.model; /** * Created by Ahmed Yusuf on 22/08/19. */ public class CheckboxData { private int id; private String secondaryId; private String value; private boolean checked; public CheckboxData(int id, String secondaryId, String value, boolean checked) { this.id = id; this.secondaryId = secondaryId; this.value = value; this.checked = checked; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSecondaryId() { return secondaryId; } public void setSecondaryId(String secondaryId) { this.secondaryId = secondaryId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } }
19.461538
84
0.606719
07d6f023b5cc2c287d69767b77c0606bfbbbaa39
385
package com.chen.gulimall.ware.dao; import com.chen.gulimall.ware.entity.WareOrderTaskEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 库存工作单 * * @author chenZhibin * @email [email protected] * @date 2021-07-09 11:02:57 */ @Mapper public interface WareOrderTaskDao extends BaseMapper<WareOrderTaskEntity> { }
21.388889
75
0.771429
531e9a4032f628606597a6b918a419a2f9a5a706
3,925
package isamrs.tim21.klinika.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import isamrs.tim21.klinika.domain.Korisnik; import isamrs.tim21.klinika.domain.Pacijent; import isamrs.tim21.klinika.dto.KorisnikTokenState; import isamrs.tim21.klinika.dto.PacijentDTO; import isamrs.tim21.klinika.security.TokenUtils; import isamrs.tim21.klinika.security.auth.JwtAuthenticationRequest; import isamrs.tim21.klinika.services.CustomUserDetailsService; import isamrs.tim21.klinika.services.PacijentService; @RestController @RequestMapping(path="/api/auth") public class AutentifikacijaController { @Autowired private PacijentService pacijentService; @Autowired private TokenUtils tokenUtils; @Autowired private AuthenticationManager authenticationManager; @Autowired private CustomUserDetailsService userDetailsService; // Prvi endpoint koji pogadja korisnik kada se loguje. // Tada zna samo svoje korisnicko ime i lozinku i to prosledjuje na backend. @PostMapping("/login") public ResponseEntity<KorisnikTokenState> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, HttpServletResponse response) { Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())); // Ubaci korisnika u trenutni security kontekst SecurityContextHolder.getContext().setAuthentication(authentication); // Kreiraj token za tog korisnika Korisnik user = (Korisnik) authentication.getPrincipal(); if (!user.isEnabled()) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } String jwt = tokenUtils.generateToken(user.getUsername()); int expiresIn = tokenUtils.getExpiredIn(); String role = user.getAuthorities().get(0).getName(); // Vrati token kao odgovor na uspesnu autentifikaciju return ResponseEntity.ok(new KorisnikTokenState(jwt, expiresIn, role)); } @PostMapping(path = "/registracija", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> registracija(@RequestBody PacijentDTO noviPacijentDTO) { Pacijent p = pacijentService.save(noviPacijentDTO); return new ResponseEntity<Pacijent>(p, HttpStatus.OK); } // U slucaju isteka vazenja JWT tokena, endpoint koji se poziva da se token osvezi @PostMapping(value = "/refresh") public ResponseEntity<KorisnikTokenState> refreshAuthenticationToken(HttpServletRequest request) { String token = tokenUtils.getToken(request); String username = this.tokenUtils.getUsernameFromToken(token); Korisnik user = (Korisnik) this.userDetailsService.loadUserByUsername(username); if (this.tokenUtils.canTokenBeRefreshed(token, user.getPoslednjaPromenaSifre())) { String refreshedToken = tokenUtils.refreshToken(token); int expiresIn = tokenUtils.getExpiredIn(); String role = user.getAuthorities().get(0).getName(); return ResponseEntity.ok(new KorisnikTokenState(refreshedToken, expiresIn, role)); } else { KorisnikTokenState userTokenState = new KorisnikTokenState(); return ResponseEntity.badRequest().body(userTokenState); } } }
41.315789
129
0.816306
ee41387e38a5918bd08598f1e1ab38f9666fc84d
1,574
/* * Copyright 2012 Greg Milette and Adam Stroud * * 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 root.gast.speech.activation; import android.content.Context; import android.util.Log; /** * @author Greg Milette &#60;<a href="mailto:[email protected]">[email protected]</a>&#62; * */ public class ClapperActivator implements SpeechActivator { private static final String TAG = "ClapperActivator"; private ClapperSpeechActivationTask activeTask; private SpeechActivationListener listener; private Context context; public ClapperActivator(Context context, SpeechActivationListener listener) { this.context = context; this.listener = listener; } @Override public void detectActivation() { Log.d(TAG, "started clapper activation"); activeTask = new ClapperSpeechActivationTask(context, listener); activeTask.execute(); } @Override public void stop() { if (activeTask != null) { activeTask.cancel(true); } } }
28.107143
92
0.696315
fd52cb12ef093f682aee46bb0b409eefeb9d0812
7,841
package com.leidos.glidepath.filter; import com.leidos.glidepath.ead.Trajectory; import com.leidos.glidepath.logger.Logger; import com.leidos.glidepath.logger.LoggerManager; /** * Fits a polynomial of order 2 to smooth the raw data, using 15 historical data points. * Uses Holoborodko filters for first and second derivatives, the first derivative using * 15 historical points, and the second derivative using 11 historical points. The * Holoborodko method is used courtesy of Pavel Holoborodko (http://www.holoborodko.com/pavel). * * @author starkj * */ public class PolyHoloA implements IDataFilter { public PolyHoloA() { polyPoints_ = 15; //treat this like a constant, but can be revised if done prior to calling initialize() timeStep_ = 0.8888888; } @Override public void initialize(double timeStep) { timeStep_ = timeStep; arraySize_ = Math.max(polyPoints_, HOLO_MAX_PTS); raw_ = new double[arraySize_]; coefA_ = 0.0; coefB_ = 0.0; coefC_ = 0.0; //since the X values are are time since the beginning of the historical buffer, we can pre-compute these sums sumX_ = 0.0; sumX2_ = 0.0; sumX3_ = 0.0; sumX4_ = 0.0; double time; double time2; for (int i = 0; i < polyPoints_; ++i) { time = timeStep * (double)i; time2 = time*time; sumX_ += time; sumX2_ += time2; sumX3_ += time*time2; sumX4_ += time2*time2; } failedPoint_ = false; } @Override public void addRawDataPoint(double rawValue) { //add the new value to the array updateArray(rawValue); ++numPoints_; failedPoint_ = false; //Note: we are using the polynomial notation that y = a + b*x + c*x^2 //if the array of historical data is full then if (numPoints_ >= polyPoints_) { //initialize the coefficients in case we can't solve the matrix (divide by zero) coefA_ = 0.0; coefB_ = 0.0; coefC_ = 0.0; //compute the sums necessary for the matrix elements; X represents time since the beginning of the array // at a constant time step separation, Y (the array values) represents the raw speed value at that time. // Our convention for time will be that 0 equates to the oldest data point and increments SIZE times to // the most recent data point. Since our look-back distance is always the same number of points, all of // the sums involving only X will always be the same, so they are pre-calculated. We only need // to compute the sums involving Y. double sumY = 0.0; double sumXY = 0.0; double sumX2Y = 0.0; int offset = arraySize_ - polyPoints_; //polyPoints_ may be less than array size; we only want the most recent points for (int i = 0; i < polyPoints_; ++i) { sumY += raw_[i + offset]; double time = timeStep_ * (double)i; sumXY += time * raw_[i + offset]; sumX2Y += time*time * raw_[i + offset]; } //set up the matrix equation and solve it MatrixSolver m = new MatrixSolver(); m.setAElement(0, 0, polyPoints_); m.setAElement(0, 1, sumX_); m.setAElement(0, 2, sumX2_); m.setAElement(1, 0, sumX_); m.setAElement(1, 1, sumX2_); m.setAElement(1, 2, sumX3_); m.setAElement(2, 0, sumX2_); m.setAElement(2, 1, sumX3_); m.setAElement(2, 2, sumX4_); m.setBElement(0, sumY); m.setBElement(1, sumXY); m.setBElement(2, sumX2Y); double[] coef = new double[3]; try { coef = m.getResult(); } catch (Exception e) { //indicate this data point can't be analyzed failedPoint_ = true; } coefA_ = coef[0]; coefB_ = coef[1]; coefC_ = coef[2]; } //endif have a full array } @Override public double getSmoothedValue() { double x = 0.0; double y = 0.0; //if we are dealing with a failed data point solution then if (failedPoint_) { //extrapolate from the 1st and 3rd raw points double slope = (raw_[arraySize_-1] - raw_[arraySize_-3]) / (2.0*timeStep_); y = raw_[polyPoints_-1] + timeStep_*slope; log_.debug("FILT", "Failed smoothing point. Interpolating."); //else }else { //solve the polynomial at the current value x = timeStep_ * (double)(polyPoints_-1); y = coefA_ + x*(coefB_ + x*coefC_); } double noise = raw_[arraySize_ - 1] - y; log_.infof("FILN", "getSmoothedValue noise =\t%.4f", noise); return y; } @Override public double getSmoothedDerivative() { double sum = 0.0; final int i = 15; //for ease of reading since we are storing newest data at highest index int offset = arraySize_ - i - 1; sum += 322.0*raw_[i-0 + offset]; sum += 217.0*raw_[i-1 + offset]; sum += 110.0*raw_[i-2 + offset]; sum += 35.0*raw_[i-3 + offset]; sum -= 42.0*raw_[i-4 + offset]; sum -= 87.0*raw_[i-5 + offset]; sum -= 134.0*raw_[i-6 + offset]; sum -= 149.0*raw_[i-7 + offset]; sum -= 166.0*raw_[i-8 + offset]; sum -= 151.0*raw_[i-9 + offset]; sum -= 138.0*raw_[i-10 + offset]; sum -= 93.0*raw_[i-11 + offset]; sum -= 50.0*raw_[i-12 + offset]; sum += 25.0*raw_[i-13 + offset]; sum += 98.0*raw_[i-14 + offset]; sum += 203.0*raw_[i-15 + offset]; double result = sum/2856.0/timeStep_; return result; } @Override public double getSmoothedSecondDerivative() { double sum = 0.0; final int n = 11; //for ease of reading since we are storing newest data at highest index final int m = 5; int offset = arraySize_ - n - 1; sum -= 28.0*raw_[n-m + offset]; sum -= 14.0*(raw_[n-m-1 + offset] + raw_[n-m+1 + offset]); sum += 8.0*(raw_[n-m-2 + offset] + raw_[n-m+2 + offset]); sum += 13.0*(raw_[n-m-3 + offset] + raw_[n-m+3 + offset]); sum += 6.0*(raw_[n-m-4 + offset] + raw_[n-m+4 + offset]); sum += (raw_[n-m-5 + offset] + raw_[n-m+5 + offset]); double result = sum / (256.0*timeStep_*timeStep_); return result; } /** * newSize >= 3 && initialize() has not yet been called : resets the number of historical points used for polynomial * else : no action * * CAUTION: this method is intended for unit testing - use it only if you are very familiar with the consequences! */ public void setAlternatePolyPoints(int newSize) { //if input is reasonable and we have not already initialized the object then if (newSize >= 3 && Math.abs(timeStep_ - 0.8888) < 0.0002) { //specify an alternate size polyPoints_ = newSize; log_.warnf("FILT", "///// CAUTION: Filter is now using an alternate number of polynomial points: %d", newSize); } } ////////////////// // member elements ////////////////// /** * always : shifts array contents to the left by one cell (toward lower indexes) and overwrites the highest index * with the input value (data is newer as index increases) */ private void updateArray(double value) { for (int i = 0; i < arraySize_-1; ++i) { raw_[i] = raw_[i+1]; } raw_[arraySize_-1] = value; } private double timeStep_; private double[] raw_; //array of raw data, most recent is at [SIZE-1], oldest is at [0] private int numPoints_; //number of data points stored so far private double coefA_; //constant coefficient private double coefB_; //coefficient for x private double coefC_; //coefficient for x^2 private double sumX_; //sum of X values private double sumX2_; //sum of X^2 values private double sumX3_; //sum of X^3 values private double sumX4_; //sum of X^4 values private boolean failedPoint_; //did the most recent data point fail a solution (e.g. matrix divide by zero)? private int polyPoints_; //total number of historical data points we will look at for the polynomial curve fit private int arraySize_; //number of historical points stored private static final int HOLO_MAX_PTS = 16; //max number of data points needed for Holoborodko filters private static Logger log_ = (Logger)LoggerManager.getLogger(PolyHoloA.class); }
32.945378
120
0.656932
90936d483f029ad5e0b6fc694aa51488b2126ca2
667
package cn.mrian22.validate.entity; import java.awt.image.BufferedImage; import java.time.LocalDateTime; /** * @author 22 * 多了一个BufferedImage属性,存放图片 */ public class ImageCode extends Code { private BufferedImage image; public ImageCode(BufferedImage image,String code, int expireIn) { super(code, expireIn); this.image = image; } public ImageCode(BufferedImage image,String code, LocalDateTime expireTime) { super(code, expireTime); this.image = image; } public BufferedImage getImage() { return image; } public void setImage(BufferedImage image) { this.image = image; } }
20.84375
81
0.670165
5fb2730719597b0010f778b256336b53ff09c68e
1,847
/** * 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.storm.streams.processors; import org.apache.storm.state.KeyValueState; import org.apache.storm.streams.Pair; import org.apache.storm.streams.operations.StateUpdater; public class UpdateStateByKeyProcessor<K, V, R> extends BaseProcessor<Pair<K, V>> implements StatefulProcessor<K, R> { private final StateUpdater<V, R> stateUpdater; private KeyValueState<K, R> keyValueState; public UpdateStateByKeyProcessor(StateUpdater<V, R> stateUpdater) { this.stateUpdater = stateUpdater; } @Override public void initState(KeyValueState<K, R> keyValueState) { this.keyValueState = keyValueState; } @Override protected void execute(Pair<K, V> input) { K key = input.getFirst(); V val = input.getSecond(); R agg = keyValueState.get(key); if (agg == null) { agg = stateUpdater.init(); } R newAgg = stateUpdater.apply(agg, val); keyValueState.put(key, newAgg); context.forward(Pair.of(key, newAgg)); } }
36.94
118
0.708717
3d149a881931bee507c869309411c07f43ed8cbe
3,781
package br.com.gerencianet.gnsdk; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONObject; import org.json.JSONTokener; /** * This is the mains class of Gerencianet SDK JAVA. It's responsible to instance an APIRequester, * send the right data to a given endpoint, and return a response to SDK client. * @author Filipe Mata * */ public class Endpoints { private APIRequest requester; private Config config; public Endpoints(JSONObject options) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream configFile = classLoader.getResourceAsStream("config.json"); JSONTokener tokener = new JSONTokener(configFile); JSONObject config = new JSONObject(tokener); configFile.close(); this.config = new Config(options, config); } public Endpoints(Config config, APIRequest request) throws Exception { this.config = config; this.requester = request; } public Endpoints(Config config){ this.config = config; } public Endpoints(Map<String, Object> options) throws Exception{ JSONObject credentials = (JSONObject) JSONObject.wrap(options); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream configFile = classLoader.getResourceAsStream("config.json"); JSONTokener tokener = new JSONTokener(configFile); JSONObject config = new JSONObject(tokener); configFile.close(); this.config = new Config(credentials, config); } public APIRequest getRequester() { return requester; } public JSONObject call(String endpoint, Map<String, String> params, JSONObject body) throws Exception{ return kernelCall(endpoint, params, body); } public Map<String, Object> call(String endpoint, Map<String, String> params, Map<String, Object> mapBody) throws Exception{ JSONObject body = (JSONObject) JSONObject.wrap(mapBody); JSONObject response = kernelCall(endpoint, params, body); return response.toMap(); } private JSONObject kernelCall(String endpointName, Map<String, String> params, JSONObject body) throws Exception{ JSONObject endpoints = this.config.getEndpoints(); if(!endpoints.has(endpointName)) throw new Exception("nonexistent endpoint"); JSONObject endpoint = (JSONObject)endpoints.get(endpointName); String route = getRoute(endpoint, params); route += getQueryString(params); if(this.requester == null) requester = new APIRequest(endpoint.get("method").toString(), route, body, this.config); JSONObject response = this.requester.send(); this.requester = null; return response; } private String getQueryString(Map<String, String> params) throws UnsupportedEncodingException { Set<Entry<String, String>> set = params.entrySet(); String query=""; for(Entry<String, String> entry : set){ if(!query.isEmpty())query +="&"; else query +="?"; query += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(),"UTF-8"); } return query; } private String getRoute(JSONObject endpoint, Map<String, String> params) { Pattern pattern = Pattern.compile("/:(\\w+)/"); String route = endpoint.get("route").toString(); route += "/"; Matcher matcher = pattern.matcher(route); while(matcher.find()){ String value = route.substring(matcher.start()+2, matcher.end()-1); if(params.containsKey(value)){ route = route.replace(":"+value, params.get(value)); params.remove(value); matcher = pattern.matcher(route); } } route = route.substring(0, route.length()-1); return route; } }
32.878261
124
0.72018
9a8222cd8a6a2b130a3f53d20b6abee413bfca21
2,116
package ndm.miniwms.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import ndm.miniwms.dao.StockInventoryMapper; import ndm.miniwms.pojo.StockInventory; import ndm.miniwms.service.IStockInventoryService; import ndm.miniwms.vo.Pagination; import ndm.miniwms.vo.TableModel; @Service public class StockInventoryServiceImpl implements IStockInventoryService{ @Resource private StockInventoryMapper stockInventoryMapper; @Override public List<StockInventory> all() { return stockInventoryMapper.all(); } @Override public int update(StockInventory stockInventory) { return stockInventoryMapper.update(stockInventory); } @Override public int add(StockInventory stockInventory) { return stockInventoryMapper.add(stockInventory); } @Override public int delete(Integer id) { return stockInventoryMapper.delById(id); } @Override public StockInventory selectById(Integer id) { return stockInventoryMapper.selectById(id); } @Override public StockInventory selectItem(Integer id) { return stockInventoryMapper.selectById(id); } @Override public Pagination<StockInventory> selectTab(TableModel table) { PageHelper.startPage(table.getStart()/table.getLength() + 1,table.getLength()); List<StockInventory> list = stockInventoryMapper.all(); Pagination<StockInventory> pagination = new Pagination<>(); //��PageInfo�Խ�����а�װ PageInfo<StockInventory> page = new PageInfo<StockInventory>(list); //����PageInfoȫ������ int total = (int)page.getTotal(); pagination.setDraw(table.getDraw()); pagination.setRecordsFiltered(this.all().size()); pagination.setRecordsTotal(total); pagination.setData(list); return pagination; } @Override public int delById(Integer id) { return this.delete(id); } @Override public int updateQuantity(StockInventory stockInventory) { return stockInventoryMapper.updateQuantity(stockInventory); } }
25.804878
81
0.750945
6bccdee7e320b620280209e517f3d2fc15831c02
385
package com.lethalskillzz.baker.presentation.recipestep; import com.lethalskillzz.baker.di.PerActivity; import com.lethalskillzz.baker.presentation.base.MvpPresenter; /** * Created by ibrahimabdulkadir on 21/06/2017. */ @PerActivity public interface RecipeStepMvpPresenter<V extends RecipeStepMvpView> extends MvpPresenter<V> { void fetchStepData(int recipeId, int stepId); }
27.5
94
0.807792
3f3c51dc601ed2e560c457ece138464a770b9fb9
4,012
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.android.designer.propertyTable.editors; import com.android.resources.ResourceType; import com.intellij.android.designer.model.ModelParser; import com.intellij.android.designer.propertyTable.renderers.EventHandlerEditorRenderer; import com.intellij.designer.ModuleProvider; import com.intellij.designer.model.PropertiesContainer; import com.intellij.designer.model.PropertyContext; import com.intellij.designer.model.RadComponent; import com.intellij.designer.model.RadPropertyContext; import com.intellij.designer.propertyTable.InplaceContext; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.util.ArrayUtil; import org.jetbrains.android.dom.attrs.AttributeFormat; import org.jetbrains.android.dom.converters.OnClickConverter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; /** * @author Alexander Lobas */ public class EventHandlerEditor extends ResourceEditor { private static final ResourceType[] TYPES = {ResourceType.STRING}; private static final Set<AttributeFormat> FORMATS = EnumSet.of(AttributeFormat.String, AttributeFormat.Enum); public EventHandlerEditor() { super(TYPES, FORMATS, ArrayUtil.EMPTY_STRING_ARRAY); getCombo().setRenderer(new EventHandlerEditorRenderer()); } @Override public Object getValue() { Object item = getCombo().getSelectedItem(); if (item instanceof PsiMethodWrapper) { return item.toString(); } return super.getValue(); } @NotNull @Override public JComponent getComponent(@Nullable PropertiesContainer container, @Nullable PropertyContext context, Object value, @Nullable InplaceContext inplaceContext) { myComponent = (RadComponent)container; myRootComponent = context instanceof RadPropertyContext ? ((RadPropertyContext)context).getRootComponent() : null; DefaultComboBoxModel model = new DefaultComboBoxModel(); model.addElement(StringsComboEditor.UNSET); JComboBox combo = getCombo(); combo.setModel(model); ModuleProvider moduleProvider = myRootComponent.getClientProperty(ModelParser.MODULE_KEY); Set<String> names = new HashSet<String>(); for (PsiClass psiClass : ChooseClassDialog.findInheritors(moduleProvider.getModule(), "android.app.Activity", true)) { for (PsiMethod method : psiClass.getMethods()) { if (OnClickConverter.checkSignature(method) && names.add(method.getName())) { model.addElement(new PsiMethodWrapper(method)); } } } combo.setSelectedItem(value); return myEditor; } private JComboBox getCombo() { return (JComboBox)myEditor.getChildComponent(); } public static final class PsiMethodWrapper { private final PsiMethod myMethod; public PsiMethodWrapper(PsiMethod method) { myMethod = method; } public PsiMethod getMethod() { return myMethod; } @Override public boolean equals(Object object) { return object == this || myMethod.getName().equals(object); } @Override public int hashCode() { return myMethod.getName().hashCode(); } @Override public String toString() { return myMethod.getName(); } } }
33.157025
122
0.730309
13b3df8df34b63f0ad1e7193ccf21714630ab2d9
695
package com.mid.exporter.data.common; import java.util.HashMap; /** * @author */ public enum StateType { BEGIN(0), PAINT(1), STETUP(2), COMPLETE(3), NONE(4); private final static HashMap<Integer, StateType> STATE_MAP = new HashMap<>(5); static { STATE_MAP.put(BEGIN.getId(), BEGIN); STATE_MAP.put(PAINT.getId(), PAINT); STATE_MAP.put(STETUP.getId(), STETUP); STATE_MAP.put(COMPLETE.getId(), COMPLETE); STATE_MAP.put(NONE.getId(), NONE); } private final int id; private StateType(int id) { this.id = id; } public int getId() { return id; } public static StateType getStateById(int id) { return STATE_MAP.get(id); } }
17.375
82
0.638849
e7904e7418ffead18b3b59e87575d6602e94c87b
736
package cbedoy.cbchatmediacell; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import java.util.List; /** * Created by bedoy on 5/5/16. */ public abstract class AbstractAdapter<T> extends BaseAdapter { private List<T> mDataModel; public AbstractAdapter(List<T> dataModel){ mDataModel = dataModel; } @Override public int getCount() { return mDataModel.size(); } @Override public Object getItem(int position) { return mDataModel.get(position); } @Override public long getItemId(int position) { return position; } public T getElementAtIndex(int index){ return mDataModel.get(index); } }
18.4
60
0.665761
58f7491628e1b09febd8f5c0febf626ea7de38da
96
package io.mateu.erp.model.financials; public enum InvoiceSending { NONE, EMAIL, VOXEL }
12
38
0.729167
a72a7ef57a572c3aded47f9da4849c6621fc81fe
640
package com.commsen.em.demo.vaadin; import javax.servlet.annotation.WebServlet; import org.osgi.service.component.annotations.Component; import com.commsen.em.annotations.Requires; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.server.VaadinServlet; @Component(// service = VaadinServlet.class ) @WebServlet( // urlPatterns = "/main/*", // name = "MainServlet", // asyncSupported = true // ) @VaadinServletConfiguration(// ui = MainUI.class, // productionMode = false // ) @Requires("vaadin") public class MainServlet extends VaadinServlet { private static final long serialVersionUID = 1L; }
22.857143
57
0.757813
692d02227827034aa75246096902391465f8632f
2,612
package co.uk.zopa.challenge.services; import co.uk.zopa.challenge.exceptions.InvalidLoanAmount; import co.uk.zopa.challenge.exceptions.MarketInsufficientFunds; import co.uk.zopa.challenge.interfaces.QuoteCalculationService; import co.uk.zopa.challenge.interfaces.ValidationService; import co.uk.zopa.challenge.model.Lender; import co.uk.zopa.challenge.model.Loan; import co.uk.zopa.challenge.model.LoanQuote; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Slf4j @Component public @Data class LoanQuoteCalculationService implements QuoteCalculationService { @Value("${loan.payments.year}") private int numPaymentsYear; @Value("${loan.duration}") private int loanDuration; @Autowired private MarketCSVService marketCSVService; @Autowired private ValidationService validationService; public LoanQuote processQuote(Loan loanRequest) throws InvalidLoanAmount, MarketInsufficientFunds { validationService.validateLoanAmount(loanRequest); marketCSVService.validateMarketSufficientFunds(loanRequest); return computeQuote(loanRequest); } public LoanQuote computeQuote(Loan loan) { LoanQuote quote = new LoanQuote(); quote.setAmount(loan.getAmount()); quote.setRate(calculateWeightedAverageRate(quote)); quote.setRepayment(calculateRepayment(quote)); quote.setTotalRepayment(calculateTotalRepayment(quote)); return quote; } public double calculateWeightedAverageRate(LoanQuote loan) { int currentAmt = 0; double rate = 0; for (Lender l : getMarketCSVService().getLenders()) { if (currentAmt + l.getAmount() > loan.getAmount()) { double delta = loan.getAmount() - currentAmt; rate += (delta / loan.getAmount()) * l.getRate(); break; } else { currentAmt += l.getAmount(); rate += ((double) l.getAmount() / loan.getAmount()) * l.getRate(); } } return rate; } public double calculateRepayment(LoanQuote loan) { return loan.getRate() * loan.getAmount() / getNumPaymentsYear() / (1 - Math.pow((loan.getRate() / getNumPaymentsYear() + 1), (-getNumPaymentsYear() * getLoanDuration()))); } public double calculateTotalRepayment(LoanQuote loan) { return loan.getRepayment() * getLoanDuration() * getNumPaymentsYear(); } }
34.826667
179
0.699081
738fc26eebbd7e88042556130e03c1d8fc3ed702
2,570
package com.weng.discountinformer; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by Weng Anxiang on 2017/3/11. */ //recycleview的适配器 public class DiscountListTitleAdapter extends RecyclerView.Adapter<DiscountListTitleAdapter.ViewHolder> { private List<DiscountAbstractInfo> mDiscountAbstractList = new ArrayList<>();//储存打折信息的标题和商家logo static class ViewHolder extends RecyclerView.ViewHolder { View sellerView; ImageView sellerLogoImage;//商家logo TextView discountTitle;//打折信息标题 public ViewHolder(View view) { super(view); sellerView = view; //保存最外层布局的实例 sellerLogoImage = (ImageView) view.findViewById(R.id.seller_logo); discountTitle = (TextView) view.findViewById(R.id.discout_title); } } public DiscountListTitleAdapter(List<DiscountAbstractInfo> abstractList) { mDiscountAbstractList = abstractList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //加载打折信息列表的单项信息 View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.discount_item, parent, false); final ViewHolder holder = new ViewHolder(view); holder.sellerView.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { //点击之后,调用相应的打折详细信息 } }); holder.sellerLogoImage.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { //点击之后,调用相应的打折详细信息 //Intent intent = new Intent(, DiscountInfoActivity.class); } }); holder.discountTitle.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { //点击之后,调用相应的打折详细信息 } }); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { DiscountAbstractInfo info = mDiscountAbstractList.get(position); holder.discountTitle.setText(info.getTitle()); holder.sellerLogoImage.setImageResource(info.getImageId()); } @Override public int getItemCount() { return mDiscountAbstractList.size(); } }
31.728395
108
0.664202
fb2606ff74f6a40f4c1e7a3749a98497d687ae87
9,865
/* * Copyright (c) 2003-2011, Simon Brown * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * - Neither the name of Pebble nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package net.sourceforge.pebble.web.security; import net.sourceforge.pebble.Constants; import net.sourceforge.pebble.domain.AbstractBlog; import net.sourceforge.pebble.domain.Blog; import net.sourceforge.pebble.web.action.Action; import org.apache.commons.codec.binary.Base64; import org.springframework.stereotype.Component; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.*; import java.nio.charset.StandardCharsets; /** * Checks requests for a security token * * @author James Roper */ @Component public class SecurityTokenValidatorImpl implements SecurityTokenValidator { /** * the security token name */ public static final String PEBBLE_SECURITY_TOKEN_PARAMETER = "pebbleSecurityToken"; /** * the parameter for the hash, this is used for links that aren't from web pages (eg emails) */ public static final String PEBBLE_SECURITY_SIGNATURE_PARAMETER = "pebbleSecurityHash"; /** * the header for bypassing security token checks */ private static final String PEBBLE_SECURITY_TOKEN_HEADER = "X-Pebble-Token"; /** * the value the header should be for not checking */ private static final String PEBBLE_SECURITY_TOKEN_HEADER_NOCHECK = "nocheck"; /** * For generating secure tokens */ private static final SecureRandom random = new SecureRandom(); /** * Validate the security token for this request, if necessary, setting up the security token cookie if it doesn't * exist * * @param request The request to validate * @param response The response * @param action The action to validate * @return true if the request can proceed, false if not */ public boolean validateSecurityToken(HttpServletRequest request, HttpServletResponse response, Action action) { // First, ensure that there is a security token, for future requests String token = ensureSecurityTokenExists(request, response); if (shouldValidate(action, request)) { // Check for the header is there... XSRF attacks can't set custom headers, so if this header is there, // it must be safe if (PEBBLE_SECURITY_TOKEN_HEADER_NOCHECK.equals(request.getHeader(PEBBLE_SECURITY_TOKEN_HEADER))) { return true; } // We must validate the token String requestToken = request.getParameter(PEBBLE_SECURITY_TOKEN_PARAMETER); // Compare token to cookie if (token.equals(requestToken)) { return true; } // No token, try validating if the request is signed return validateSignedRequest(request); } else { return true; } } private boolean shouldValidate(Action action, HttpServletRequest request) { RequireSecurityToken annotation = action.getClass().getAnnotation(RequireSecurityToken.class); if (annotation != null) { // Check for a condition Class<? extends SecurityTokenValidatorCondition> condition = annotation.value(); if (condition != null && condition != NullSecurityTokenValidatorCondition.class) { // Instantiate condition try { return condition.newInstance().shouldValidate(request); } catch (IllegalAccessException iae) { throw new RuntimeException("Could not instantiate " + condition); } catch (InstantiationException ie) { throw new RuntimeException("Could not instantiate " + condition); } } // Otherwise, with no condition we should return validate return true; } else { // We have no annotation, don't validate return false; } } private String ensureSecurityTokenExists(HttpServletRequest request, HttpServletResponse response) { String token = (String) request.getAttribute(PEBBLE_SECURITY_TOKEN_PARAMETER); if (token != null) { // We've already configured it for this request return token; } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (PEBBLE_SECURITY_TOKEN_PARAMETER.equals(cookie.getName())) { token = cookie.getValue(); } } } // No cookie, generate a token at least 12 characters long if (token == null) { String contextPath = request.getContextPath(); // Ensure context path is not empty if (contextPath == null || contextPath.length() == 0) { contextPath = "/"; } token = ""; while (token.length() < 12) { token += Long.toHexString(random.nextLong()); } // Set the cookie Cookie cookie = new Cookie(PEBBLE_SECURITY_TOKEN_PARAMETER, token); // Non persistent cookie.setMaxAge(-1); cookie.setPath(contextPath); response.addCookie(cookie); } // Set it as a request attribute so the security token tag can find it request.setAttribute(PEBBLE_SECURITY_TOKEN_PARAMETER, token); return token; } private boolean validateSignedRequest(HttpServletRequest request) { String requestHash = request.getParameter(PEBBLE_SECURITY_SIGNATURE_PARAMETER); if (requestHash != null) { AbstractBlog blog = (AbstractBlog) request.getAttribute(Constants.BLOG_KEY); if (blog instanceof Blog) { String salt = ((Blog) blog).getXsrfSigningSalt(); // Convert request parameters to map String servletPath = request.getServletPath(); if (servletPath.startsWith("/")) { servletPath = servletPath.substring(1); } String hash = hashRequest(servletPath, request.getParameterMap(), salt); return hash.equals(requestHash); } } return false; } /** * Hashes the given query parameters by sorting the keys alphabetically and then hashing the & separated query String * that would be generated by having the keys in that order, concatinated with the salt * * @param params The parameters in the query String * @param salt The secret salt * @return The hash in base64 */ public String hashRequest(String servletPath, Map<String, String[]> params, String salt) { List<String> keys = new ArrayList<String>(params.keySet()); Collections.sort(keys); MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } digest.update(servletPath.getBytes()); digest.update((byte) '?'); boolean start = true; for (String key : keys) { if (!key.equals(PEBBLE_SECURITY_SIGNATURE_PARAMETER)) { for (String value : params.get(key)) { if (!start) { digest.update((byte) '&'); } start = false; digest.update(key.getBytes()); digest.update((byte) '='); digest.update(value.getBytes()); } } } digest.update(salt.getBytes()); byte[] hash = digest.digest(); return new String(Base64.encodeBase64(hash, false)); } /** * Generate a signed query string * * @param params The parameters in the query string. This method assumes the parameters are not URL encoded * @param salt The salt to sign it with * @return The HTML escaped signed query string */ public String generateSignedQueryString(String servletPath, Map<String, String[]> params, String salt) { String hash = hashRequest(servletPath, params, salt); StringBuilder url = new StringBuilder(servletPath); String sep = "?"; for (Map.Entry<String, String[]> param : params.entrySet()) { for (String value : param.getValue()) { url.append(sep); sep = "&amp;"; try { url.append(URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8.toString())); url.append("="); url.append(URLEncoder.encode(value, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { } } } url.append(sep).append(PEBBLE_SECURITY_SIGNATURE_PARAMETER).append("=").append(URLEncoder.encode(hash)); return url.toString(); } }
37.796935
119
0.692955
3575bf623878508cdec212662577b1d84ba13370
4,222
/* * Copyright © 2018-2019 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.common.metadata; import io.cdap.cdap.api.metadata.MetadataEntity; import io.cdap.cdap.api.metadata.MetadataScope; import io.cdap.cdap.proto.id.NamespacedEntityId; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Represents the complete metadata of a {@link MetadataEntity} including its properties, tags in a given * {@link MetadataScope} * this class was in cdap-api earlier and has been moved from cdap-common as its used only internally */ public class MetadataRecord { private final MetadataEntity metadataEntity; private final MetadataScope scope; private final Map<String, String> properties; private final Set<String> tags; /** * Returns an empty {@link MetadataRecord} in the specified {@link MetadataScope}. */ public MetadataRecord(NamespacedEntityId entityId, MetadataScope scope) { this(entityId.toMetadataEntity(), scope); } /** * Returns an empty {@link MetadataRecord} in the specified {@link MetadataScope}. */ public MetadataRecord(MetadataEntity metadataEntity, MetadataScope scope) { this(metadataEntity, scope, Collections.emptyMap(), Collections.emptySet()); } /** * Returns a new {@link MetadataRecord} from the specified existing {@link MetadataRecord}. */ public MetadataRecord(MetadataRecord other) { this(other.getMetadataEntity(), other.getScope(), other.getProperties(), other.getTags()); } /** * Returns an empty {@link MetadataRecord} in the specified {@link MetadataScope}. */ public MetadataRecord(NamespacedEntityId entityId, MetadataScope scope, Map<String, String> properties, Set<String> tags) { this(entityId.toMetadataEntity(), scope, properties, tags); } /** * Returns an empty {@link MetadataRecord} in the specified {@link MetadataScope} containing the specified * properties and tags */ public MetadataRecord(MetadataEntity metadataEntity, MetadataScope scope, Map<String, String> properties, Set<String> tags) { this.metadataEntity = metadataEntity; this.scope = scope; this.properties = new HashMap<>(properties); this.tags = new HashSet<>(tags); } /** * @return the {@link MetadataEntity} whose metadata this {@link MetadataRecord} represents */ public MetadataEntity getMetadataEntity() { return metadataEntity; } /** * @return the {@link MetadataScope} of this {@link MetadataRecord} */ public MetadataScope getScope() { return scope; } /** * @return the properties of this {@link MetadataRecord} */ public Map<String, String> getProperties() { return properties; } /** * @return the tags of this {@link MetadataRecord} */ public Set<String> getTags() { return tags; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MetadataRecord that = (MetadataRecord) o; return Objects.equals(metadataEntity, that.metadataEntity) && scope == that.scope && Objects.equals(properties, that.properties) && Objects.equals(tags, that.tags); } @Override public int hashCode() { return Objects.hash(metadataEntity, scope, properties, tags); } @Override public String toString() { return "MetadataRecord{" + "metadataEntity=" + metadataEntity + ", scope=" + scope + ", properties=" + properties + ", tags=" + tags + '}'; } }
29.732394
108
0.691615
1b3b23e953192be1702559f63385f16b0c942b36
11,355
/* * Copyright 2017 Julia Kozhukhovskaya * * 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.julia.android.worderly.ui.game.view; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.julia.android.worderly.App; import com.julia.android.worderly.R; import com.julia.android.worderly.StringPreference; import com.julia.android.worderly.model.Move; import com.julia.android.worderly.model.Player; import com.julia.android.worderly.model.Round; import com.julia.android.worderly.model.User; import com.julia.android.worderly.ui.game.dialog.DialogListener; import com.julia.android.worderly.ui.game.dialog.GameRoundDialogFragment; import com.julia.android.worderly.ui.game.dragdrop.Listener; import com.julia.android.worderly.ui.game.dragdrop.TilesList; import com.julia.android.worderly.ui.game.dragdrop.TilesListAdapter; import com.julia.android.worderly.ui.game.presenter.GamePresenter; import com.julia.android.worderly.ui.main.MainActivity; import com.julia.android.worderly.utils.Constants; import com.julia.android.worderly.utils.WordUtility; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import timber.log.Timber; import static com.julia.android.worderly.utils.Constants.EXTRA_OPPONENT; import static com.julia.android.worderly.utils.Constants.NUMBER_OF_LETTERS; public class GameFragment extends Fragment implements GamePresenter.View, Listener, DialogListener { @BindView(R.id.progressBar) ProgressBar mProgressBar; @BindView(R.id.text_progress) TextView mTextProgressView; @BindView(R.id.text_username_opponent) TextView mOpponentUsernameTextView; @BindView(R.id.text_user_score) TextView mUserScoreTextView; @BindView(R.id.text_opponent_score) TextView mOpponentScoreTextView; @BindView(R.id.recycler_view_top) RecyclerView mRecyclerViewTop; @BindView(R.id.recycler_view_bottom) RecyclerView mRecyclerViewBottom; @BindView(R.id.frame_top) FrameLayout mFrameTop; @BindView(R.id.frame_bottom) FrameLayout mFrameBottom; @BindView(R.id.image_holder) ImageView mImageHolder; @Inject StringPreference mPrefs; TilesListAdapter mTopListAdapter; TilesListAdapter mBottomListAdapter; String shuffledWord = ""; private List<TilesList> mTilesListTop; private List<TilesList> mTilesListBottom; private Unbinder mUnbinder; private GamePresenter mPresenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); App.get(getContext()).component().inject(this); mPresenter = new GamePresenter(this); mPresenter.setOpponentFromBundle(getOpponentBundleExtras()); mPresenter.setWord(shuffledWord); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_game, container, false); mUnbinder = ButterKnife.bind(this, view); mTilesListTop = new ArrayList<>(); mTopListAdapter = new TilesListAdapter(mTilesListTop, this); mRecyclerViewTop.setAdapter(mTopListAdapter); mRecyclerViewTop.setOnDragListener(mTopListAdapter.getDragInstance()); mFrameTop.setOnDragListener(mTopListAdapter.getDragInstance()); shuffleLetters(); mBottomListAdapter = new TilesListAdapter(mTilesListBottom, this); mRecyclerViewBottom.setAdapter(mBottomListAdapter); mRecyclerViewBottom.setOnDragListener(mBottomListAdapter.getDragInstance()); mRecyclerViewTop.addItemDecoration( new DividerItemDecoration(getContext(), DividerItemDecoration.HORIZONTAL)); mRecyclerViewBottom.addItemDecoration( new DividerItemDecoration(getContext(), DividerItemDecoration.HORIZONTAL)); mFrameBottom.setOnDragListener(mBottomListAdapter.getDragInstance()); mImageHolder.setOnDragListener(mTopListAdapter.getDragInstance()); mPresenter.setOpponentUserView(); mUserScoreTextView.setText("0"); return view; } @Override public void onStart() { super.onStart(); new GameCountDownTimer((mProgressBar.getMax() - mProgressBar.getProgress())*1000, 1, mProgressBar, mTextProgressView, this).start(); } @Override public void onDestroyView() { super.onDestroyView(); mUnbinder.unbind(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("progress", mProgressBar.getProgress()); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { int progress = savedInstanceState.getInt("progress"); mProgressBar.setProgress(progress); mTextProgressView.setText(String.valueOf(mProgressBar.getMax() - progress)); } } @Override public void showOpponentUsernameView(String username) { mOpponentUsernameTextView.setText(username); } /** * If the user sends a wrong word, then show him a toast, and empty edit text */ @Override public void showWrongWordToast() { Toast.makeText( getActivity(), getString(R.string.msg_wrong_word), Toast.LENGTH_SHORT).show(); } @Override public void showOpponentScore(String score) { mOpponentScoreTextView.setText(score); } @Override public String getUserScoreText() { return mUserScoreTextView.getText().toString(); } @Override public User getUserPrefs() { String json = mPrefs.get(); if (!Objects.equals(json, Constants.PREF_USER_DEFAULT_VALUE)) { return new Gson().fromJson(json, User.class); } return null; } public void setUserScoreTextView(String score) { mUserScoreTextView.setText(score); } @Override public void setEmptyListTop(boolean visibility) { mImageHolder.setVisibility(visibility ? View.VISIBLE : View.GONE); mFrameTop.setVisibility(visibility ? View.GONE : View.VISIBLE); mRecyclerViewTop.setVisibility(visibility ? View.GONE : View.VISIBLE); } private void shuffleLetters() { char[] c = WordUtility.scrambleWord(shuffledWord).toCharArray(); Timber.d(Arrays.toString(c)); mTilesListBottom = new ArrayList<>(); for (int i = 0; i < Constants.NUMBER_OF_LETTERS; i++) { int color = getResources().getIdentifier( "tile" + i, "color", getContext().getPackageName()); mTilesListBottom.add(i, new TilesList(c[i], color, WordUtility.getTileValue(c[i]))); } } @OnClick(R.id.button_clear) public void onClearClick() { if (mTilesListTop.size() != 0) { mTilesListTop.clear(); mTopListAdapter = new TilesListAdapter(mTilesListTop, this); mRecyclerViewTop.setAdapter(mTopListAdapter); mTilesListBottom.clear(); shuffleLetters(); mBottomListAdapter = new TilesListAdapter(mTilesListBottom, this); mRecyclerViewBottom.setAdapter(mBottomListAdapter); } } @OnClick(R.id.button_send) public void onSendClick() { // Check if length of tiles is not empty if (mTilesListTop.size() != 0) { String word = ""; for (int i = 0; i < mTilesListTop.size(); i++) { TilesList q = mTilesListTop.get(i); word += q.letter; } // check if that word equals to fetched word, if yes - no need to do the request if (mTilesListTop.size() == NUMBER_OF_LETTERS && mPresenter.isWordsEquals(word)) { Toast.makeText(getContext(), "YOU GUESSED THE WHOLE WORD RIGHT!", Toast.LENGTH_SHORT).show(); String score = String.valueOf(WordUtility.getWordValue(word)); setUserScoreTextView(String.valueOf(score)); mPresenter.sendUserScoreAndWord(new Move(word, score)); } else { mPresenter.getVolleyRequest(getContext(), word); } } else { Toast.makeText(getContext(), "Nothing to send!", Toast.LENGTH_SHORT).show(); } } @OnClick(R.id.button_shuffle) public void onShuffleClick() { if (mTilesListBottom.size() != 0) { mTilesListTop.clear(); mTopListAdapter = new TilesListAdapter(mTilesListTop, this); mRecyclerViewTop.setAdapter(mTopListAdapter); mTilesListBottom.clear(); shuffleLetters(); mBottomListAdapter = new TilesListAdapter(mTilesListBottom, this); mRecyclerViewBottom.setAdapter(mBottomListAdapter); } } public void resign() { mPresenter.notifyOpponentAboutResign(); mPresenter.deleteGameRoom(); //mPresenter.showLoseDialog(); } private void navigateToMainActivity() { Intent i = new Intent(getActivity(), MainActivity.class); startActivity(i); getActivity().finish(); } private User getOpponentBundleExtras() { Bundle extras = getActivity().getIntent().getExtras(); if (extras != null) { shuffledWord = extras.getString("EXTRA_WORD"); return extras.getParcelable(EXTRA_OPPONENT); } return null; } @Override public void showRoundFinishedDialog() { if (getActivity() != null) { FragmentManager fm = getActivity().getSupportFragmentManager(); Round round = new Round(1, "LETTERS", "definition", 10); Player user = new Player("You", "LET", 5, 10); Player opponent = new Player("Guest123", "LTR", 6, 11); GameRoundDialogFragment alertDialog = GameRoundDialogFragment .newInstance(round, user, opponent); alertDialog.show(fm, "fragment_dialog_round_finished"); } } }
35.373832
109
0.689828
cce3d35fa247720317fff212fd2af2949e7f92dc
743
package com.len.service.impl; import com.len.base.BaseMapper; import com.len.base.impl.BaseServiceImpl; import com.len.entity.WanganUserLeave; import com.len.mapper.WanganUserLeaveMapper; import com.len.service.WanganUserLeaveService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author zhuxiaomeng * @date 2018/1/21. * @email [email protected] */ @Service public class WanganUserLeaveServiceImpl extends BaseServiceImpl<WanganUserLeave, String> implements WanganUserLeaveService { @Autowired WanganUserLeaveMapper userLeaveMapper; @Override public BaseMapper<WanganUserLeave, String> getMappser() { return userLeaveMapper; } }
26.535714
99
0.781965
e3d03bacbf784153c821098dec4a16144466ead8
1,631
package com.phycctv.easysum.model; import java.util.Date; import java.util.List; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; @Entity public class Transaction { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private Date date; private double amount; private String comment; @ManyToOne private Category cat; @ManyToOne private Account account; @ManyToMany private List<AppUser> users; public Transaction() { } public Transaction(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Category getCat() { return cat; } public void setCat(Category cat) { this.cat = cat; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } public List<AppUser> getUsers() { return users; } public void setUsers(List<AppUser> users) { this.users = users; } }
15.242991
48
0.709381
508802be2e8dce92cf0bb1e36d539062ff67f7d1
2,295
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nebulae2us.stardust.expr.domain; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import static org.nebulae2us.stardust.internal.util.BaseAssert.*; /** * @author Trung Phan * */ public class ExpressionIterator implements Iterator<Expression> { private int index = -1; private Iterator<? extends Expression> currentChildExpressionIterator; private final Expression parent; private final List<? extends Expression> childExpressions; public ExpressionIterator(Expression parent, List<? extends Expression> childExpressions) { Assert.notNull(parent, "parent cannot be null"); Assert.notNull(childExpressions, "childExpressions cannot be null"); this.parent = parent; this.childExpressions = childExpressions; } public boolean hasNext() { if (index == -1 || (currentChildExpressionIterator != null && currentChildExpressionIterator.hasNext())) { return true; } if (index < childExpressions.size() - 1) { return true; } return false; } public Expression next() { if (index == -1) { index ++; if (index < childExpressions.size()) { currentChildExpressionIterator = childExpressions.get(index).expressionIterator(); } return parent; } if (currentChildExpressionIterator.hasNext()) { return currentChildExpressionIterator.next(); } else if (index < childExpressions.size() - 1) { index++; currentChildExpressionIterator = childExpressions.get(index).expressionIterator(); return currentChildExpressionIterator.next(); } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } }
28.333333
108
0.735076
043b3040b84d85d6723c94a6f4518b1dfda9c0ac
1,166
package com.urgoo.plan.biz; import android.content.Context; import com.urgoo.common.ZWConfig; import com.urgoo.data.SPManager; import com.urgoo.net.EventCode; import com.urgoo.net.HttpEngine; import com.urgoo.net.StringRequestCallBack; import java.util.HashMap; /** * Created by bb on 2016/8/9. */ public class PlanManager { private static PlanManager sInstance; private Context mContext; private PlanManager(Context context) { this.mContext = context; } public static PlanManager getInstance(Context context) { if (null == sInstance) { sInstance = new PlanManager(context); } return sInstance; } /** * 任务列表 * * @param callback */ public void getStudentTaskListNewest(StringRequestCallBack callback, String termType) { HashMap<String, String> params = new HashMap<>(); params.put("termType", termType); params.put("token", SPManager.getInstance(mContext).getToken()); HttpEngine.getInstance(mContext).sendPostRequest(EventCode.EventCodeGetStudentTaskListNewest, ZWConfig.URL_getStudentTaskListNewest, params, callback); } }
26.5
159
0.69554
f7520e2f1dd599c14119b0c1ef601a9eca526c82
3,141
package id.co.ardata.megatrik.megatrikdriver.utils; import android.content.Context; import android.content.SharedPreferences; public class SessionManager { SharedPreferences pref; SharedPreferences.Editor editor; Context _context; int PRIVATE_MODE = 0; private static final String PREF_NAME = "MegatrikDriverSession"; private static final String KEY_IS_LOGGED_IN = "isLoggedIn"; private static final String KEY_ACCESS_TOKEN = "user_access_token"; private static final String KEY_USER_ID = "user_id"; private static final String KEY_USER_NAME = "user_name"; private static final String KEY_USER_EMAIL = "user_email"; private static final String KEY_USER_PHONE = "user_phone"; private static final String KEY_USER_OS_PLAYER_ID = "user_os_player_id"; private static final String KEY_USER_IMG_PROFILE = "user_img"; public SessionManager(Context context){ this._context = context; pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); editor = pref.edit(); } public void setIsLogin(boolean isLogin){ editor.putBoolean(KEY_IS_LOGGED_IN, isLogin); editor.commit(); } public boolean isLoggedIn(){ return pref.getBoolean(KEY_IS_LOGGED_IN, false); } public void setAccessToken(String accessToken){ editor.putString(KEY_ACCESS_TOKEN, accessToken); editor.commit(); } public String getAccessToken(){ return pref.getString(KEY_ACCESS_TOKEN, null); } public void setUserId(String userId){ editor.putString(KEY_USER_ID, userId); editor.commit(); } public String getUserId(){ return pref.getString(KEY_USER_ID, null); } public void setUserEmail(String userEmail){ editor.putString(KEY_USER_EMAIL, userEmail); editor.commit(); } public String getUserEmail(){ return pref.getString(KEY_USER_EMAIL, null); } public void setUserName(String userName){ editor.putString(KEY_USER_NAME, userName); editor.commit(); } public String getUserName(){ return pref.getString(KEY_USER_NAME, null); } public void setUserOsPlayerId(String userOsPlayerId){ editor.putString(KEY_USER_OS_PLAYER_ID, userOsPlayerId); editor.commit(); } public String getUserOsPlayerId(){ return pref.getString(KEY_USER_OS_PLAYER_ID, null); } public void setUserImgProfile(String userImg){ editor.putString(KEY_USER_IMG_PROFILE, userImg); editor.commit(); } public String getUserImgProfile(){ return pref.getString(KEY_USER_IMG_PROFILE, null); } public void setUserPhone(String phone){ editor.putString(KEY_USER_PHONE, phone); editor.commit(); } public String getUserPhone(){ return pref.getString(KEY_USER_PHONE, null); } public void resetProfile(){ setIsLogin(false); setAccessToken(null); setUserEmail(null); setUserName(null); setUserId(null); setUserImgProfile(null); setUserPhone(null); } }
28.044643
76
0.683222
834a5718b37fcb89d41026cac6e12265075d2f2c
517
package frc.robot.simulator.network.services; import frc.robot.simulator.network.proto.PingProto; import frc.robot.simulator.network.proto.PingServiceGrpc; import io.grpc.stub.StreamObserver; public class PingService extends PingServiceGrpc.PingServiceImplBase { @Override public void ping(PingProto.PingMessage request, StreamObserver<PingProto.PongResponse> responseObserver) { responseObserver.onNext(PingProto.PongResponse.getDefaultInstance()); responseObserver.onCompleted(); } }
34.466667
110
0.800774
1c062836c9c0283811c7ce299f4f910cea973771
956
package com.packt.j11intro.porcus; import java.util.Scanner; public class Main { public static void main(String[] args) { // Initializes main engine. PigLatinTranslator t = new PigLatinTranslator(); System.out.println("Pig Latin Converter, type in anything, we will convert it into pig latin. Press <ENTER> to submit for conversion. Ctrl-D to end."); Scanner scanner = new Scanner(System.in); String line = null; do { if (line != null) { System.out.println("The pig latin for [" + line + "] is [" + t.convert(line) + "]."); System.out.println("Please type in something else to convert."); } if (scanner.hasNext()) { line = scanner.nextLine(); } else { line = null; } } while (line != null); System.out.println("Thanks for using PigLatinTranslator."); } }
32.965517
159
0.559623
8618800b5300b8753be2f13c9b78f740773cd5c4
848
package com.nfdw.util; import javax.servlet.http.HttpServletRequest; /** * @author zhuxiaomeng * @date 2017/12/28. * @email [email protected] */ public class IpUtil { public static String getIp(HttpServletRequest request){ String ip=request.getHeader("x-forwarded-for"); if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){ ip=request.getHeader("Proxy-Client-IP"); } if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){ ip=request.getHeader("WL-Proxy-Client-IP"); } if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){ ip=request.getHeader("X-Real-IP"); } if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){ ip=request.getRemoteAddr(); } return ip; } }
29.241379
73
0.583726
300eb2b2454cd44cd6b1db38a5978b7ceb370fee
561
package cn.liuyiyou.springboot.autoconfigure; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * @author: liuyiyou.cn * @date: 2019/11/28 * @version: V1.0 */ @ConfigurationProperties(value = "lyy", ignoreUnknownFields = true) @Data @Configuration public class LyyProperties { /** * 年龄 */ private int age = 18; /** * 姓名 */ private String name = "lyy"; /** * 性别 */ private int sex = 0; }
17.53125
75
0.652406
18493b6d0f71b69154c2925460b968827233ec33
3,247
package games.dominoes; import games.common.model.board.Coordinate; import games.common.model.enums.Color; import games.common.model.enums.Direction; import games.dominoes.lineardominos.LinearDominoPiece; import games.dominoes.stickersdominoes.DominoStickerPiece; import games.dominoes.stickersdominoes.Shape; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class DominoesBoardTest { @Test public void testPutTileAtDominoStickers() { DominoesBoard b = new DominoesBoard(10, 10, new Coordinate(3, 4), new DominoStickerPiece(Shape.HEART, Color.RED, Shape.CRESCENT, Color.GREEN, Direction.BOTTOM)); System.out.println(b); assertFalse( b.putTileAt(new Coordinate(2, 5), new DominoStickerPiece(Shape.HEART, Color.RED, Shape.STAR, Color.BLUE, Direction.RIGHT))); assertFalse( b.putTileAt(new Coordinate(5, 4), new DominoStickerPiece(Shape.DISK, Color.YELLOW, Shape.HEART, Color.BLUE, Direction.LEFT)) ); assertTrue( b.putTileAt(new Coordinate(6, 4), new DominoStickerPiece(Shape.DISK, Color.GREEN, Shape.CRESCENT, Color.GREEN, Direction.TOP)) ); System.out.println(b); assertFalse( b.putTileAt(new Coordinate(1, 0), new DominoStickerPiece(Shape.STAR, Color.YELLOW, Shape.DISK, Color.RED, Direction.TOP)) ); assertFalse( b.putTileAt(new Coordinate(-1, 3), new DominoStickerPiece(Shape.STAR, Color.YELLOW, Shape.DISK, Color.RED, Direction.BOTTOM)) ); } @Test public void testPutTileAtLinearDomino() { DominoesBoard b = new DominoesBoard(10, 10, new Coordinate(3, 4), new LinearDominoPiece(5, 4, Direction.BOTTOM)); System.out.println(b); assertFalse( b.putTileAt(new Coordinate(2, 5), new LinearDominoPiece(4, 6, Direction.RIGHT))); /**assertFalse( b.putTileAt(new Coordinate(5, 4), new DominoStickerPiece(Shape.DISK, Color.YELLOW, Shape.HEART, Color.BLUE, Direction.LEFT)) ); assertTrue( b.putTileAt(new Coordinate(6, 4), new DominoStickerPiece(Shape.DISK, Color.GREEN, Shape.CRESCENT, Color.GREEN, Direction.TOP)) ); System.out.println(b); assertFalse( b.putTileAt(new Coordinate(1, 0), new DominoStickerPiece(Shape.STAR, Color.YELLOW, Shape.DISK, Color.RED, Direction.TOP)) ); assertFalse( b.putTileAt(new Coordinate(-1, 3), new DominoStickerPiece(Shape.STAR, Color.YELLOW, Shape.DISK, Color.RED, Direction.BOTTOM)) );*/ assertTrue( b.putTileAt(new Coordinate(5, 4), new LinearDominoPiece(4, 6, Direction.RIGHT))); System.out.println(b); } }
38.654762
113
0.579304
f4d5ad88e44b33124dcf74d34971b7b3b68dbc9c
1,842
package fr.reivon.formation.spring10; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class StudentController { @Autowired StudentValidator studentValidator; @RequestMapping(value = "/student", method = RequestMethod.GET) public ModelAndView student() { return new ModelAndView("student", "studentForm", new Student()); } @RequestMapping(value = "/addStudent", method = RequestMethod.POST) public String addStudent(@ModelAttribute("studentForm") @Validated Student student, BindingResult result, ModelMap model) { // Appel manuel // studentValidator.validate(student, result); if (result.hasErrors()) { return "student"; } else { model.addAttribute("name", student.getName()); model.addAttribute("age", student.getAge()); model.addAttribute("email", student.getEmail()); model.addAttribute("id", student.getId()); return "result"; } } /** * Associer les validators au controller local. * @param binder */ @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(studentValidator); } }
35.423077
127
0.722041
b5358f5e8229cfd4c5ea76ad23df2a5798027680
4,904
/* Foilen Login https://github.com/foilen/foilen-login Copyright (c) 2017-2021 Foilen (http://foilen.com) The MIT License http://opensource.org/licenses/MIT */ package com.foilen.login.controller; import org.apache.commons.validator.routines.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.foilen.login.api.to.FoilenLoginToken; import com.foilen.login.api.to.FoilenLoginUser; import com.foilen.login.db.domain.LoginToken; import com.foilen.login.db.domain.User; import com.foilen.login.db.service.LoginService; import com.foilen.login.db.service.UserService; import com.foilen.login.exception.ResourceNotFoundException; @Controller @RequestMapping("/api") public class LoginApiController { private final static Logger logger = LoggerFactory.getLogger(LoginApiController.class); @Value("${login.applicationId}") private String applicationId; @Autowired private LoginService loginService; @Autowired private UserService userService; private EmailValidator emailValidator = EmailValidator.getInstance(); @RequestMapping("createOrFindByEmail/{email}") @ResponseBody FoilenLoginUser createOrFindByEmail(@PathVariable("email") String email, @RequestParam(value = "appId", required = false) String appId) { // Make sure the app id is there if (!applicationId.equals(appId)) { logger.error("createOrFindByEmail() email: {} by unauthorized user", email); throw new ResourceNotFoundException(); } logger.info("createOrFindByEmail() email: {}", email); // Check email if (!emailValidator.isValid(email)) { return null; } // Get the user details User user = userService.createOrGetUser(email); FoilenLoginUser result = new FoilenLoginUser(); if (user == null) { return null; } else { BeanUtils.copyProperties(user, result); } return result; }; @RequestMapping("createToken") @ResponseBody FoilenLoginToken createToken(@RequestParam("redirectUrl") String redirectUrl) { logger.info("createToken() redirectUrl: {}", redirectUrl); LoginToken loginToken = loginService.createToken(redirectUrl); FoilenLoginToken result = new FoilenLoginToken(); result.setToken(loginToken.getLoginToken()); result.setExpiration(loginToken.getExpire()); return result; }; @RequestMapping("findByEmail/{email}") @ResponseBody FoilenLoginUser findByEmail(@PathVariable("email") String email, @RequestParam(value = "appId", required = false) String appId) { // Make sure the app id is there if (!applicationId.equals(appId)) { logger.error("findByEmail() email: {} by unauthorized user", email); throw new ResourceNotFoundException(); } logger.info("findByEmail() email: {}", email); // Get the user details User user = userService.findByEmail(email); FoilenLoginUser result = new FoilenLoginUser(); if (user == null) { return null; } else { BeanUtils.copyProperties(user, result); } return result; }; @RequestMapping("findByUserId/{userId}") @ResponseBody FoilenLoginUser findByUserId(@PathVariable("userId") String userId, @RequestParam(value = "appId", required = false) String appId) { // Make sure the app id is there if (!applicationId.equals(appId)) { logger.error("findByUserId() userId: {} by unauthorized user", userId); throw new ResourceNotFoundException(); } logger.info("findByUserId() userId: {}", userId); // Get the user details User user = userService.findByUserId(userId); FoilenLoginUser result = new FoilenLoginUser(); if (user == null) { return null; } else { BeanUtils.copyProperties(user, result); } return result; }; @RequestMapping("findUserIdByToken/{token}") @ResponseBody String findUserIdByToken(@PathVariable("token") String token) { logger.info("findUserIdByToken() userId: {}", token); User user = loginService.retrieveLoggedUser(token); if (user != null) { return user.getUserId(); } return null; }; };
32.912752
141
0.672308
70376d17bc6336e3294533aa340e58a44939f453
5,577
/* * Copyright 2017-2018 Adobe. * * 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.adobe.platform.ecosystem.examples.authentication; import com.adobe.platform.ecosystem.examples.constants.SDKConstants; import com.adobe.platform.ecosystem.examples.util.ConnectorSDKException; import com.adobe.platform.ecosystem.examples.util.ConnectorSDKUtil; import com.adobe.platform.ecosystem.ut.BaseTest; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Created by nidhi on 25/9/17. */ public class TokenProcessorTest extends BaseTest { String accessToken = "eyJ4NXUiOiJpbXNfbmExLXN0ZzEta2V5LTEuY2VyIiwiYWxnIjoiUlMyNTYifQ.eyJpZCI6IjE1MDk3MDExMDM0MDlfZjRlZWQwMDYtYjY5Ni00YjQ5LTliOGYtMTAyNzY4YjhlYTczX3VlMSIsImNsaWVudF9pZCI6Ik1DRFBfSEFSVkVTVEVSIiwidXNlcl9pZCI6Ik1DRFBfSEFSVkVTVEVSQEFkb2JlSUQiLCJ0eXBlIjoiYWNjZXNzX3Rva2VuIiwiYXMiOiJpbXMtbmExLXN0ZzEiLCJwYWMiOiJNQ0RQX0hBUlZFU1RFUl9zdGciLCJydGlkIjoiMTUwOTcwMTEwMzQwOV81NmQxNWY3ZS0yYjcwLTQ3MjYtOGQ5Ni1hNDdkNDg4N2VhYWRfdWUxIiwicnRlYSI6IjE1MTA5MTA3MDM0MDkiLCJtb2kiOiI2ZDk0M2UwMCIsImMiOiI0dVFzWVFzL0Z5VHhUekErWE1pa2pnPT0iLCJleHBpcmVzX2luIjoiODY0MDAwMDAiLCJzY29wZSI6InN5c3RlbSIsImNyZWF0ZWRfYXQiOiIxNTA5NzAxMTAzNDA5In0.exiCb1l9HNLjQgwhz_XFatzvUvhHWe7u4QBau8UiegiB-iOlOJvFds5QwaUj1fX2N3Ki8FZWQ0uCqCKJRKCFvFxitnElrmsNIS3lkQz1NWlfq2KK-qQS5pORyd05ZK95ep11Tokz-S_bUvjK-tE-HkZeFzpHLLL2ab9cDwBGSVdeofCUSm8LYnaC7YAlAYbC3kwSAFm6XewD9BHrOx6luYlEr7oPdZxIM-eBJ-Xe95eC6Dnm-UUbLVOyHUeQhYPO51CPUmTY6uaok7Ic3osP4038SrVtKRYijQtmEWsCPg4otlqN5NNkeJqP8jrLHv5n193jtDHdH_8V0GP-YZS8Dg"; String jwtToken = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIzMThERURDNzU5QzM4QUU5MEE0OTVFQ0VAdGVjaGFjY3QuYWRvYmUuY29tIiwiYXVkIjoiaHR0cHM6Ly9pbXMtbmExLmFkb2JlbG9naW4uY29tL2MvMTA0NzVhMDE5NTliNDY3Nzg3YjhkNDNkZTgxZDY2YjkiLCJodHRwczovL2ltcy1uYTEuYWRvYmVsb2dpbi5jb20vcy9lbnRfZGF0YWNhdGFsb2dfc2RrIjp0cnVlLCJpc3MiOiI3Q0JFNzA0MDUxQjBGNzU5MEE0OTBENENAQWRvYmVPcmciLCJleHAiOjE1MTAyMDI3Mzl9.rkgIUanAefJxWgT5KFo5Xtyuz5wbH3W9bErKpipbZpQLKeMG4zhbKnBLg6muLz5HUOdX5PT_zasWiqdzv9IqV-f3yv_0RZ1N5pLR1C2tEkL7p5nGj89EQqGlSppf_mDurXS3R8K6CmL4nC8HaV6TB7e76iIkofqMGUORdSnt0jOzUFyy0REmX0C5c_pdHlXlpQYJ1xOXa-oAQsoWmPLtiXBPBM_AY8ma_heuyvhpreWvXoX_-uGcVUblr1Fbicy39T1R6HdummRGhL3vk-70RaVLOAokS7MoDBzekngza1_GersPLOPHd1R3oAkldCfDj419o_JxI-LnwupcL0i4cA"; @Before public void before() throws Exception { setUp(); setUpHttpForJwtResponse(); } @Test public void testTokenType() throws Exception { ConnectorSDKUtil.TOKEN_TYPE token_type = AccessTokenProcessor.getTokenType(jwtToken); assertFalse(token_type.equals(ConnectorSDKUtil.TOKEN_TYPE.ACCESS_TOKEN)); token_type = AccessTokenProcessor.getTokenType(accessToken); assertTrue(token_type.equals(ConnectorSDKUtil.TOKEN_TYPE.ACCESS_TOKEN)); } @Test public void testValidityOfToken() throws Exception { boolean isTokenValid = AccessTokenProcessor.isTokenValid(ConnectorSDKUtil.TOKEN_TYPE.ACCESS_TOKEN, accessToken); assertFalse(isTokenValid); isTokenValid = AccessTokenProcessor.isTokenValid(ConnectorSDKUtil.TOKEN_TYPE.JWT_TOKEN, jwtToken); assertFalse(isTokenValid); } @Test public void getAccessTokenFromJWT() throws Exception { String accessToken = AccessTokenProcessor.generateAccessToken("sampleJWT", "sampleClientId", "sampleSecretKey", httpClient); assertTrue(accessToken != null); } @Test public void testNullClientAndSecret() { try { AccessTokenProcessor.generateAccessToken("sampleJWT", null, "sampleSecretKey"); assertTrue(false); } catch (Exception ex) { assertTrue(ex instanceof ConnectorSDKException); } } @Test public void TestJWTCreation() throws Exception { File file = new File("src/test/resources/secret.key"); Map<String, String> credentials = new HashMap<>(); credentials.put(SDKConstants.CREDENTIAL_CLIENT_KEY, ""); credentials.put(SDKConstants.CREDENTIAL_PRIVATE_KEY_PATH, file.getAbsolutePath()); credentials.put(SDKConstants.CREDENTIAL_IMS_ORG_KEY, ""); credentials.put(SDKConstants.CREDENTIAL_TECHNICAL_ACCOUNT_KEY, ""); String jwtToken = AccessTokenProcessor.generateJWTToken(credentials); assertTrue(jwtToken != null); } @Test public void testInValidToken() throws Exception { try { AccessTokenProcessor.isTokenValid(ConnectorSDKUtil.TOKEN_TYPE.ACCESS_TOKEN, "sampleAccessToken"); assertFalse(true); }catch (Exception ex){ assertTrue(ex instanceof ConnectorSDKException); } } @Test public void testInValidToken_1() throws Exception { try { AccessTokenProcessor.getTokenType("sampleAccessToken"); assertFalse(true); }catch (Exception ex){ assertTrue(ex instanceof ConnectorSDKException); } } }
49.794643
969
0.790389
f4e672da2df25fa510fcbd3820e09c3fb708dcd9
6,806
package com.example.login; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.androidapp.MainActivity; import com.example.androidapp.R; import com.example.constant.Constant; import com.example.util.AlertDialogUtil; import com.example.util.AsyncTAskUtil; import com.example.util.MyCountDownTimer; import com.example.util.ValidateUtil; import com.jaeger.library.StatusBarUtil; import java.util.concurrent.ExecutionException; public class SignUpAccountActivity extends AppCompatActivity implements View.OnClickListener { private EditText telephoneNumber; private EditText name; private EditText email; private EditText password; private EditText checkCode; private Button sendCheckCodeBtn; private MyCountDownTimer myCountDownTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up_account); StatusBarUtil.setColor(SignUpAccountActivity.this, getResources().getColor(R.color.smallBlue)); //透明状态栏(最顶层) // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明导航栏 //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); Toolbar toolbar = (Toolbar) findViewById(R.id.signUpToolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); actionBar.setTitle(R.string.userSignUp); } telephoneNumber = (EditText) findViewById(R.id.signUpPhone); name = (EditText) findViewById(R.id.realName); email = (EditText) findViewById(R.id.email); password = (EditText) findViewById(R.id.userPassword); checkCode = (EditText) findViewById(R.id.checkMessage); sendCheckCodeBtn = (Button) findViewById(R.id.sendCheckCode); Button userSignUpBtn = (Button) findViewById(R.id.userSignUp); //new倒计时对象,总共的时间,每隔多少秒更新一次时间 myCountDownTimer = new MyCountDownTimer(60000,1000, sendCheckCodeBtn); sendCheckCodeBtn.setOnClickListener(this); userSignUpBtn.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sendCheckCode: String telephone = telephoneNumber.getText().toString(); if (ValidateUtil.isMobileNO(telephone)) { myCountDownTimer.start(); sendMessage(telephone); //发送短信验证码 } else { Toast.makeText(SignUpAccountActivity.this, R.string.validPhone, Toast.LENGTH_SHORT).show(); } break; //用户注册 case R.id.userSignUp: String userPhone = telephoneNumber.getText().toString(); //手机号码 String userEmail = email.getText().toString(); //邮箱 String userName = name.getText().toString(); //姓名 String userPassword = password.getText().toString(); //密码 String userCheckCode = checkCode.getText().toString(); //验证码 //进行简单格式验证,有效的手机号和邮箱,至少两种字符6-20位的密码 //名字为1-12个字符,2-6个中文字,验证码为六位数 if (ValidateUtil.isMobileNO(userPhone) && ValidateUtil.isEmail(userEmail) && ValidateUtil.isUserName(userName) && ValidateUtil.isNameLength(userName) && ValidateUtil.isPassword(userPassword) && userCheckCode.length() == 6) { //通过初步验证,进行网络请求验证 signUp(userName, userPhone, userEmail, userPassword, userCheckCode); } else { Toast.makeText(SignUpAccountActivity.this, R.string.signUpInvalidInfo, Toast.LENGTH_SHORT).show(); } break; default: break; } } private void sendMessage(String tele) { String[] sendCodeUrl = {Constant.URL_SEND_CHECK_CODE, "telephoneNumber", tele}; String message = ""; try { message = new AsyncTAskUtil(){}.execute(sendCodeUrl).get(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } if ("200".equals(message)) { Log.d("Messages", "发送成功"); } else { Log.d("Messages", "发送失败"); } } private void signUp(String name, String phone, String email, String password, String checkCode) { String[] signUpUrl = {Constant.URL_SIGN_UP_USER, "name", name, "phone", phone, "email", email, "password", password, "checkCode", checkCode}; String status = ""; //接受注册结果 try { status = new AsyncTAskUtil(){}.execute(signUpUrl).get(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } if(!"".equals(status)) { //注册成功,跳转到登陆页面 AlertDialog.Builder dialog = new AlertDialog.Builder(SignUpAccountActivity.this); dialog.setMessage(R.string.signUpSuccess); dialog.setCancelable(false); dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(SignUpAccountActivity.this,LoginActivity.class); startActivity(intent); finish(); } }); dialog.show(); } else { new AlertDialogUtil(this.getString(R.string.signUpFailedTitle), this.getString(R.string.signUpFailed),this).alertDialogWithOk(); } } //返回按钮监听事件 @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub if(item.getItemId() == android.R.id.home) { //返回到登录页面 Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } }
37.191257
118
0.626065
04a07f6f32fd34fe3cba112d62e782b6f3c6980d
2,204
package org.asperen.processors.couchdb; import java.util.List; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.util.StandardValidators; import org.lightcouch.View; @Tags({"couchdb", "ingres", "get", "nosql"}) @CapabilityDescription("Retrieves all documents from a CouchDB database list. View and list names are a property " + "as well as the mime-type that is expected. " + "The response from CouchDB is passed through as a single FlowFile.") public class GetCouchDBList extends GetCouchDBView { public static final PropertyDescriptor COUCHDB_LISTNAME = new PropertyDescriptor .Builder().name("COUCHDB_LISTNAME") .displayName("List name") .description("The name of the list.") .required(true) .addValidator(StandardValidators.NON_BLANK_VALIDATOR) .build(); public static final PropertyDescriptor COUCHDB_MIMETYPE = new PropertyDescriptor .Builder().name("COUCHDB_MIMETYPE") .displayName("Mime-type") .description("The mime-type that is requested.") .required(true) .addValidator(StandardValidators.NON_BLANK_VALIDATOR) .build(); @Override protected void initDescriptors(List<PropertyDescriptor> descriptors) { descriptors.add(COUCHDB_LISTNAME); descriptors.add(COUCHDB_MIMETYPE); super.initDescriptors(descriptors); } @Override public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { createDbClient(context); String viewName = context.getProperty(COUCHDB_VIEWNAME).getValue(); String listName = context.getProperty(COUCHDB_LISTNAME).getValue(); String mimeType = context.getProperty(COUCHDB_MIMETYPE).getValue(); View view = this.dbClient.list(viewName, listName, mimeType); retrieveView(context, session, listName.concat("@").concat(viewName), view); } }
40.814815
114
0.747731
60d5c2d25c6b608c0f56442e2cb4e24d323fbe66
24,353
package com.docusign.esign.model; import java.util.Objects; import java.util.Arrays; import com.docusign.esign.model.SettingsMetadata; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * UserAccountManagementGranularInformation. * */ public class UserAccountManagementGranularInformation { @JsonProperty("canManageAccountSecuritySettings") private String canManageAccountSecuritySettings = null; @JsonProperty("canManageAccountSecuritySettingsMetadata") private SettingsMetadata canManageAccountSecuritySettingsMetadata = null; @JsonProperty("canManageAccountSettings") private String canManageAccountSettings = null; @JsonProperty("canManageAccountSettingsMetadata") private SettingsMetadata canManageAccountSettingsMetadata = null; @JsonProperty("canManageAdmins") private String canManageAdmins = null; @JsonProperty("canManageAdminsMetadata") private SettingsMetadata canManageAdminsMetadata = null; @JsonProperty("canManageDocumentRetention") private String canManageDocumentRetention = null; @JsonProperty("canManageDocumentRetentionMetadata") private SettingsMetadata canManageDocumentRetentionMetadata = null; @JsonProperty("canManageEnvelopeTransfer") private String canManageEnvelopeTransfer = null; @JsonProperty("canManageEnvelopeTransferMetadata") private SettingsMetadata canManageEnvelopeTransferMetadata = null; @JsonProperty("canManageGroupsButNotUsers") private String canManageGroupsButNotUsers = null; @JsonProperty("canManageGroupsButNotUsersMetadata") private SettingsMetadata canManageGroupsButNotUsersMetadata = null; @JsonProperty("canManageReporting") private String canManageReporting = null; @JsonProperty("canManageReportingMetadata") private SettingsMetadata canManageReportingMetadata = null; @JsonProperty("canManageSharing") private String canManageSharing = null; @JsonProperty("canManageSharingMetadata") private SettingsMetadata canManageSharingMetadata = null; @JsonProperty("canManageSigningGroups") private String canManageSigningGroups = null; @JsonProperty("canManageSigningGroupsMetadata") private SettingsMetadata canManageSigningGroupsMetadata = null; @JsonProperty("canManageUsers") private String canManageUsers = null; @JsonProperty("canManageUsersMetadata") private SettingsMetadata canManageUsersMetadata = null; @JsonProperty("canViewUsers") private String canViewUsers = null; /** * canManageAccountSecuritySettings. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageAccountSecuritySettings(String canManageAccountSecuritySettings) { this.canManageAccountSecuritySettings = canManageAccountSecuritySettings; return this; } /** * . * @return canManageAccountSecuritySettings **/ @ApiModelProperty(value = "") public String getCanManageAccountSecuritySettings() { return canManageAccountSecuritySettings; } /** * setCanManageAccountSecuritySettings. **/ public void setCanManageAccountSecuritySettings(String canManageAccountSecuritySettings) { this.canManageAccountSecuritySettings = canManageAccountSecuritySettings; } /** * canManageAccountSecuritySettingsMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageAccountSecuritySettingsMetadata(SettingsMetadata canManageAccountSecuritySettingsMetadata) { this.canManageAccountSecuritySettingsMetadata = canManageAccountSecuritySettingsMetadata; return this; } /** * Get canManageAccountSecuritySettingsMetadata. * @return canManageAccountSecuritySettingsMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageAccountSecuritySettingsMetadata() { return canManageAccountSecuritySettingsMetadata; } /** * setCanManageAccountSecuritySettingsMetadata. **/ public void setCanManageAccountSecuritySettingsMetadata(SettingsMetadata canManageAccountSecuritySettingsMetadata) { this.canManageAccountSecuritySettingsMetadata = canManageAccountSecuritySettingsMetadata; } /** * canManageAccountSettings. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageAccountSettings(String canManageAccountSettings) { this.canManageAccountSettings = canManageAccountSettings; return this; } /** * . * @return canManageAccountSettings **/ @ApiModelProperty(value = "") public String getCanManageAccountSettings() { return canManageAccountSettings; } /** * setCanManageAccountSettings. **/ public void setCanManageAccountSettings(String canManageAccountSettings) { this.canManageAccountSettings = canManageAccountSettings; } /** * canManageAccountSettingsMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageAccountSettingsMetadata(SettingsMetadata canManageAccountSettingsMetadata) { this.canManageAccountSettingsMetadata = canManageAccountSettingsMetadata; return this; } /** * Get canManageAccountSettingsMetadata. * @return canManageAccountSettingsMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageAccountSettingsMetadata() { return canManageAccountSettingsMetadata; } /** * setCanManageAccountSettingsMetadata. **/ public void setCanManageAccountSettingsMetadata(SettingsMetadata canManageAccountSettingsMetadata) { this.canManageAccountSettingsMetadata = canManageAccountSettingsMetadata; } /** * canManageAdmins. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageAdmins(String canManageAdmins) { this.canManageAdmins = canManageAdmins; return this; } /** * . * @return canManageAdmins **/ @ApiModelProperty(value = "") public String getCanManageAdmins() { return canManageAdmins; } /** * setCanManageAdmins. **/ public void setCanManageAdmins(String canManageAdmins) { this.canManageAdmins = canManageAdmins; } /** * canManageAdminsMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageAdminsMetadata(SettingsMetadata canManageAdminsMetadata) { this.canManageAdminsMetadata = canManageAdminsMetadata; return this; } /** * Get canManageAdminsMetadata. * @return canManageAdminsMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageAdminsMetadata() { return canManageAdminsMetadata; } /** * setCanManageAdminsMetadata. **/ public void setCanManageAdminsMetadata(SettingsMetadata canManageAdminsMetadata) { this.canManageAdminsMetadata = canManageAdminsMetadata; } /** * canManageDocumentRetention. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageDocumentRetention(String canManageDocumentRetention) { this.canManageDocumentRetention = canManageDocumentRetention; return this; } /** * . * @return canManageDocumentRetention **/ @ApiModelProperty(value = "") public String getCanManageDocumentRetention() { return canManageDocumentRetention; } /** * setCanManageDocumentRetention. **/ public void setCanManageDocumentRetention(String canManageDocumentRetention) { this.canManageDocumentRetention = canManageDocumentRetention; } /** * canManageDocumentRetentionMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageDocumentRetentionMetadata(SettingsMetadata canManageDocumentRetentionMetadata) { this.canManageDocumentRetentionMetadata = canManageDocumentRetentionMetadata; return this; } /** * Get canManageDocumentRetentionMetadata. * @return canManageDocumentRetentionMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageDocumentRetentionMetadata() { return canManageDocumentRetentionMetadata; } /** * setCanManageDocumentRetentionMetadata. **/ public void setCanManageDocumentRetentionMetadata(SettingsMetadata canManageDocumentRetentionMetadata) { this.canManageDocumentRetentionMetadata = canManageDocumentRetentionMetadata; } /** * canManageEnvelopeTransfer. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageEnvelopeTransfer(String canManageEnvelopeTransfer) { this.canManageEnvelopeTransfer = canManageEnvelopeTransfer; return this; } /** * . * @return canManageEnvelopeTransfer **/ @ApiModelProperty(value = "") public String getCanManageEnvelopeTransfer() { return canManageEnvelopeTransfer; } /** * setCanManageEnvelopeTransfer. **/ public void setCanManageEnvelopeTransfer(String canManageEnvelopeTransfer) { this.canManageEnvelopeTransfer = canManageEnvelopeTransfer; } /** * canManageEnvelopeTransferMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageEnvelopeTransferMetadata(SettingsMetadata canManageEnvelopeTransferMetadata) { this.canManageEnvelopeTransferMetadata = canManageEnvelopeTransferMetadata; return this; } /** * Get canManageEnvelopeTransferMetadata. * @return canManageEnvelopeTransferMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageEnvelopeTransferMetadata() { return canManageEnvelopeTransferMetadata; } /** * setCanManageEnvelopeTransferMetadata. **/ public void setCanManageEnvelopeTransferMetadata(SettingsMetadata canManageEnvelopeTransferMetadata) { this.canManageEnvelopeTransferMetadata = canManageEnvelopeTransferMetadata; } /** * canManageGroupsButNotUsers. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageGroupsButNotUsers(String canManageGroupsButNotUsers) { this.canManageGroupsButNotUsers = canManageGroupsButNotUsers; return this; } /** * . * @return canManageGroupsButNotUsers **/ @ApiModelProperty(value = "") public String getCanManageGroupsButNotUsers() { return canManageGroupsButNotUsers; } /** * setCanManageGroupsButNotUsers. **/ public void setCanManageGroupsButNotUsers(String canManageGroupsButNotUsers) { this.canManageGroupsButNotUsers = canManageGroupsButNotUsers; } /** * canManageGroupsButNotUsersMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageGroupsButNotUsersMetadata(SettingsMetadata canManageGroupsButNotUsersMetadata) { this.canManageGroupsButNotUsersMetadata = canManageGroupsButNotUsersMetadata; return this; } /** * Get canManageGroupsButNotUsersMetadata. * @return canManageGroupsButNotUsersMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageGroupsButNotUsersMetadata() { return canManageGroupsButNotUsersMetadata; } /** * setCanManageGroupsButNotUsersMetadata. **/ public void setCanManageGroupsButNotUsersMetadata(SettingsMetadata canManageGroupsButNotUsersMetadata) { this.canManageGroupsButNotUsersMetadata = canManageGroupsButNotUsersMetadata; } /** * canManageReporting. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageReporting(String canManageReporting) { this.canManageReporting = canManageReporting; return this; } /** * . * @return canManageReporting **/ @ApiModelProperty(value = "") public String getCanManageReporting() { return canManageReporting; } /** * setCanManageReporting. **/ public void setCanManageReporting(String canManageReporting) { this.canManageReporting = canManageReporting; } /** * canManageReportingMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageReportingMetadata(SettingsMetadata canManageReportingMetadata) { this.canManageReportingMetadata = canManageReportingMetadata; return this; } /** * Get canManageReportingMetadata. * @return canManageReportingMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageReportingMetadata() { return canManageReportingMetadata; } /** * setCanManageReportingMetadata. **/ public void setCanManageReportingMetadata(SettingsMetadata canManageReportingMetadata) { this.canManageReportingMetadata = canManageReportingMetadata; } /** * canManageSharing. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageSharing(String canManageSharing) { this.canManageSharing = canManageSharing; return this; } /** * . * @return canManageSharing **/ @ApiModelProperty(value = "") public String getCanManageSharing() { return canManageSharing; } /** * setCanManageSharing. **/ public void setCanManageSharing(String canManageSharing) { this.canManageSharing = canManageSharing; } /** * canManageSharingMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageSharingMetadata(SettingsMetadata canManageSharingMetadata) { this.canManageSharingMetadata = canManageSharingMetadata; return this; } /** * Get canManageSharingMetadata. * @return canManageSharingMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageSharingMetadata() { return canManageSharingMetadata; } /** * setCanManageSharingMetadata. **/ public void setCanManageSharingMetadata(SettingsMetadata canManageSharingMetadata) { this.canManageSharingMetadata = canManageSharingMetadata; } /** * canManageSigningGroups. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageSigningGroups(String canManageSigningGroups) { this.canManageSigningGroups = canManageSigningGroups; return this; } /** * . * @return canManageSigningGroups **/ @ApiModelProperty(value = "") public String getCanManageSigningGroups() { return canManageSigningGroups; } /** * setCanManageSigningGroups. **/ public void setCanManageSigningGroups(String canManageSigningGroups) { this.canManageSigningGroups = canManageSigningGroups; } /** * canManageSigningGroupsMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageSigningGroupsMetadata(SettingsMetadata canManageSigningGroupsMetadata) { this.canManageSigningGroupsMetadata = canManageSigningGroupsMetadata; return this; } /** * Get canManageSigningGroupsMetadata. * @return canManageSigningGroupsMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageSigningGroupsMetadata() { return canManageSigningGroupsMetadata; } /** * setCanManageSigningGroupsMetadata. **/ public void setCanManageSigningGroupsMetadata(SettingsMetadata canManageSigningGroupsMetadata) { this.canManageSigningGroupsMetadata = canManageSigningGroupsMetadata; } /** * canManageUsers. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageUsers(String canManageUsers) { this.canManageUsers = canManageUsers; return this; } /** * . * @return canManageUsers **/ @ApiModelProperty(value = "") public String getCanManageUsers() { return canManageUsers; } /** * setCanManageUsers. **/ public void setCanManageUsers(String canManageUsers) { this.canManageUsers = canManageUsers; } /** * canManageUsersMetadata. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canManageUsersMetadata(SettingsMetadata canManageUsersMetadata) { this.canManageUsersMetadata = canManageUsersMetadata; return this; } /** * Get canManageUsersMetadata. * @return canManageUsersMetadata **/ @ApiModelProperty(value = "") public SettingsMetadata getCanManageUsersMetadata() { return canManageUsersMetadata; } /** * setCanManageUsersMetadata. **/ public void setCanManageUsersMetadata(SettingsMetadata canManageUsersMetadata) { this.canManageUsersMetadata = canManageUsersMetadata; } /** * canViewUsers. * * @return UserAccountManagementGranularInformation **/ public UserAccountManagementGranularInformation canViewUsers(String canViewUsers) { this.canViewUsers = canViewUsers; return this; } /** * . * @return canViewUsers **/ @ApiModelProperty(value = "") public String getCanViewUsers() { return canViewUsers; } /** * setCanViewUsers. **/ public void setCanViewUsers(String canViewUsers) { this.canViewUsers = canViewUsers; } /** * Compares objects. * * @return true or false depending on comparison result. */ @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserAccountManagementGranularInformation userAccountManagementGranularInformation = (UserAccountManagementGranularInformation) o; return Objects.equals(this.canManageAccountSecuritySettings, userAccountManagementGranularInformation.canManageAccountSecuritySettings) && Objects.equals(this.canManageAccountSecuritySettingsMetadata, userAccountManagementGranularInformation.canManageAccountSecuritySettingsMetadata) && Objects.equals(this.canManageAccountSettings, userAccountManagementGranularInformation.canManageAccountSettings) && Objects.equals(this.canManageAccountSettingsMetadata, userAccountManagementGranularInformation.canManageAccountSettingsMetadata) && Objects.equals(this.canManageAdmins, userAccountManagementGranularInformation.canManageAdmins) && Objects.equals(this.canManageAdminsMetadata, userAccountManagementGranularInformation.canManageAdminsMetadata) && Objects.equals(this.canManageDocumentRetention, userAccountManagementGranularInformation.canManageDocumentRetention) && Objects.equals(this.canManageDocumentRetentionMetadata, userAccountManagementGranularInformation.canManageDocumentRetentionMetadata) && Objects.equals(this.canManageEnvelopeTransfer, userAccountManagementGranularInformation.canManageEnvelopeTransfer) && Objects.equals(this.canManageEnvelopeTransferMetadata, userAccountManagementGranularInformation.canManageEnvelopeTransferMetadata) && Objects.equals(this.canManageGroupsButNotUsers, userAccountManagementGranularInformation.canManageGroupsButNotUsers) && Objects.equals(this.canManageGroupsButNotUsersMetadata, userAccountManagementGranularInformation.canManageGroupsButNotUsersMetadata) && Objects.equals(this.canManageReporting, userAccountManagementGranularInformation.canManageReporting) && Objects.equals(this.canManageReportingMetadata, userAccountManagementGranularInformation.canManageReportingMetadata) && Objects.equals(this.canManageSharing, userAccountManagementGranularInformation.canManageSharing) && Objects.equals(this.canManageSharingMetadata, userAccountManagementGranularInformation.canManageSharingMetadata) && Objects.equals(this.canManageSigningGroups, userAccountManagementGranularInformation.canManageSigningGroups) && Objects.equals(this.canManageSigningGroupsMetadata, userAccountManagementGranularInformation.canManageSigningGroupsMetadata) && Objects.equals(this.canManageUsers, userAccountManagementGranularInformation.canManageUsers) && Objects.equals(this.canManageUsersMetadata, userAccountManagementGranularInformation.canManageUsersMetadata) && Objects.equals(this.canViewUsers, userAccountManagementGranularInformation.canViewUsers); } /** * Returns the HashCode. */ @Override public int hashCode() { return Objects.hash(canManageAccountSecuritySettings, canManageAccountSecuritySettingsMetadata, canManageAccountSettings, canManageAccountSettingsMetadata, canManageAdmins, canManageAdminsMetadata, canManageDocumentRetention, canManageDocumentRetentionMetadata, canManageEnvelopeTransfer, canManageEnvelopeTransferMetadata, canManageGroupsButNotUsers, canManageGroupsButNotUsersMetadata, canManageReporting, canManageReportingMetadata, canManageSharing, canManageSharingMetadata, canManageSigningGroups, canManageSigningGroupsMetadata, canManageUsers, canManageUsersMetadata, canViewUsers); } /** * Converts the given object to string. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UserAccountManagementGranularInformation {\n"); sb.append(" canManageAccountSecuritySettings: ").append(toIndentedString(canManageAccountSecuritySettings)).append("\n"); sb.append(" canManageAccountSecuritySettingsMetadata: ").append(toIndentedString(canManageAccountSecuritySettingsMetadata)).append("\n"); sb.append(" canManageAccountSettings: ").append(toIndentedString(canManageAccountSettings)).append("\n"); sb.append(" canManageAccountSettingsMetadata: ").append(toIndentedString(canManageAccountSettingsMetadata)).append("\n"); sb.append(" canManageAdmins: ").append(toIndentedString(canManageAdmins)).append("\n"); sb.append(" canManageAdminsMetadata: ").append(toIndentedString(canManageAdminsMetadata)).append("\n"); sb.append(" canManageDocumentRetention: ").append(toIndentedString(canManageDocumentRetention)).append("\n"); sb.append(" canManageDocumentRetentionMetadata: ").append(toIndentedString(canManageDocumentRetentionMetadata)).append("\n"); sb.append(" canManageEnvelopeTransfer: ").append(toIndentedString(canManageEnvelopeTransfer)).append("\n"); sb.append(" canManageEnvelopeTransferMetadata: ").append(toIndentedString(canManageEnvelopeTransferMetadata)).append("\n"); sb.append(" canManageGroupsButNotUsers: ").append(toIndentedString(canManageGroupsButNotUsers)).append("\n"); sb.append(" canManageGroupsButNotUsersMetadata: ").append(toIndentedString(canManageGroupsButNotUsersMetadata)).append("\n"); sb.append(" canManageReporting: ").append(toIndentedString(canManageReporting)).append("\n"); sb.append(" canManageReportingMetadata: ").append(toIndentedString(canManageReportingMetadata)).append("\n"); sb.append(" canManageSharing: ").append(toIndentedString(canManageSharing)).append("\n"); sb.append(" canManageSharingMetadata: ").append(toIndentedString(canManageSharingMetadata)).append("\n"); sb.append(" canManageSigningGroups: ").append(toIndentedString(canManageSigningGroups)).append("\n"); sb.append(" canManageSigningGroupsMetadata: ").append(toIndentedString(canManageSigningGroupsMetadata)).append("\n"); sb.append(" canManageUsers: ").append(toIndentedString(canManageUsers)).append("\n"); sb.append(" canManageUsersMetadata: ").append(toIndentedString(canManageUsersMetadata)).append("\n"); sb.append(" canViewUsers: ").append(toIndentedString(canViewUsers)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
32.865047
594
0.774484
5d36fdc793cdf60bbfce98e3d80a2e63ce4154ce
3,743
package com.trevorgowing.tasklist.task; import static com.spotify.hamcrest.optional.OptionalMatchers.emptyOptional; import static com.spotify.hamcrest.optional.OptionalMatchers.optionalWithValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import com.trevorgowing.tasklist.test.type.AbstractRepositoryTests; import com.trevorgowing.tasklist.user.User; import java.time.LocalDateTime; import java.util.Collection; import java.util.Optional; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; public class TaskRepositoryTests extends AbstractRepositoryTests { @Autowired private TaskRepository taskRepository; @Test public void testFindDTOsByUserIdWithNotExistingTasks_shouldReturnEmptyCollection() { LocalDateTime date = LocalDateTime.now(); User user = User.builder().username("user").build(); entityManager.persist(user); User anotherUser = User.builder().username("anotherUser").build(); entityManager.persist(anotherUser); entityManager.persist( Task.builder().user(anotherUser).name("anotherTask").dateTime(date).build()); Collection<TaskDTO> actual = taskRepository.findDTOsByUserId(user.getId()); assertThat(actual, is(empty())); } @Test public void testFindDTOsBYUserIdWithExistingTasks_shouldReturnTasks() { LocalDateTime date = LocalDateTime.now(); User user = User.builder().username("user").build(); entityManager.persist(user); Task taskOne = Task.builder().user(user).name("one").dateTime(date).build(); entityManager.persist(taskOne); TaskDTO taskOneDTO = TaskDTO.builder().id(taskOne.getId()).name("one").dateTime(date).build(); Task taskTwo = Task.builder().user(user).name("two").dateTime(date).build(); entityManager.persist(taskTwo); TaskDTO taskTwoDTO = TaskDTO.builder().id(taskTwo.getId()).name("two").dateTime(date).build(); User anotherUser = User.builder().username("anotherUser").build(); entityManager.persist(anotherUser); entityManager.persist(Task.builder().user(user).name("anotherTask").dateTime(date).build()); Collection<TaskDTO> actual = taskRepository.findDTOsByUserId(user.getId()); assertThat(actual, hasItems(taskOneDTO, taskTwoDTO)); } @Test public void testFindDTOByUserIdAndTaskIdWithNoMatchingTask_shouldReturnEmptyOptional() { User user = User.builder().username("user").build(); entityManager.persist(user); User anotherUser = User.builder().username("anotherUser").build(); entityManager.persist(anotherUser); Task task = Task.builder().user(anotherUser).name("task").dateTime(LocalDateTime.now()).build(); entityManager.persist(task); Optional<TaskDTO> actual = taskRepository.findDTOByUserIdAndTaskId(user.getId(), 1000L); assertThat(actual, is(emptyOptional())); } @Test public void testFindDTOByUserIdAndTaskIdWithMatchingTask_shouldReturnTaskDTO() { LocalDateTime date = LocalDateTime.now(); User user = User.builder().username("user").build(); entityManager.persist(user); Task task = Task.builder().user(user).name("task").dateTime(date).build(); entityManager.persist(task); TaskDTO expected = TaskDTO.builder().id(task.getId()).name("task").dateTime(date).build(); Task anotherTask = Task.builder().user(user).name("anotherTask").dateTime(date).build(); entityManager.persist(anotherTask); Optional<TaskDTO> actual = taskRepository.findDTOByUserIdAndTaskId(user.getId(), task.getId()); assertThat(actual, is(optionalWithValue(equalTo(expected)))); } }
38.989583
100
0.751269
766b2c0f076faecf53656981fa7f4c217ebe053e
430
package functional; public final class TestObjectUnMutable { public final int value; public TestObjectUnMutable(int value) { this.value = value; } public TestObjectUnMutable updateValue(int value) { return new TestObjectUnMutable(value); } @Override public String toString() { return "TestObjectUnMutable{" + "value=" + value + '}'; } }
19.545455
55
0.6
e395d8679abb9fa5d88bf3643b03f25c3d549227
2,489
package tane.mahuta.buildtools.version.storage; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import tane.mahuta.buildtools.version.VersionStorage; import javax.annotation.Nonnull; import java.io.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * {@link VersionStorage} for property files. * * @author [email protected] * Created on 28.05.17. */ @Slf4j public class PropertyVersionStorage implements VersionStorage { private final File file; private final Pattern pattern; private final String propertyName; public PropertyVersionStorage(@Nonnull final File file, @Nonnull final String propertyName) { if (!file.isFile()) { throw new IllegalArgumentException("File " + String.valueOf(file) + " is not a file."); } this.file = file; this.propertyName = propertyName; this.pattern = Pattern.compile("^(\\s*" + Pattern.quote(propertyName) + "\\s*[=\\s:]\\s*).+$"); } @Override @SneakyThrows public void store(final String version) { final File temporaryFile = createTemporaryCopy(file); try (BufferedReader reader = new BufferedReader(new FileReader(temporaryFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { String line; boolean replaced = false; while ((line = reader.readLine()) != null) { final Matcher m = pattern.matcher(line); if (m.matches()) { skipMultiLines(reader, line); line = m.replaceAll("$1" + version); replaced = true; } writer.write(line); writer.newLine(); } if (!replaced) { writer.write(propertyName); writer.write("="); writer.write(version); writer.newLine(); } } } private static void skipMultiLines(@Nonnull final BufferedReader reader, @Nonnull String line) throws IOException { while (line != null && line.endsWith("\\")) { line = reader.readLine(); } } @SneakyThrows private final File createTemporaryCopy(@Nonnull final File file) { final File result = File.createTempFile("temporary", "storage"); FileUtils.copyFile(file, result); return result; } }
31.910256
120
0.602652
56d012e09fc3e4bd126f52db2bf18192344130e3
3,866
/* * Copyright 2013 University of Chicago and Argonne National Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package exm.stc.frontend; import org.apache.log4j.Level; import org.apache.log4j.Logger; import exm.stc.ast.SwiftAST; import exm.stc.ast.antlr.ExMParser; import exm.stc.common.Logging; /** * Helper functions to augment log messages with contextual information about * the current line. * */ public class LogHelper { static final Logger logger = Logging.getSTCLogger(); public static void logChildren(int indent, SwiftAST tree) { for (SwiftAST child: tree.children()) { trace(indent+2, child.getText()); } } /** * @param tokenNum token number from AST * @return descriptive string containing token name, or token number if * unknown token type */ public static String tokName(int tokenNum) { if (tokenNum < 0 || tokenNum > ExMParser.tokenNames.length - 1) { return "Invalid token number (" + tokenNum + ")"; } else { return ExMParser.tokenNames[tokenNum]; } } public static void info(Context context, String msg) { log(context.getLevel(), Level.INFO, context.getLocation(), msg); } public static void debug(Context context, String msg) { log(context.getLevel(), Level.DEBUG, context.getLocation(), msg); } public static void trace(Context context, String msg) { log(context.getLevel(), Level.TRACE, context.getLocation(), msg); } /** INFO-level with indentation for nice output */ public static void info(int indent, String msg) { log(indent, Level.INFO, msg); } /** WARN-level with indentation for nice output */ public static void warn(Context context, String msg) { log(context.getLevel(), Level.WARN, context.getLocation(), msg); } public static void uniqueWarn(Context context, String message) { Logging.uniqueWarn(logMsg(0, context.getLocation(), message)); } /** ERROR-level with indentation for nice output */ public static void error(Context context, String msg) { log(context.getLevel(), Level.ERROR, context.getLocation(), msg); } /** DEBUG-level with indentation for nice output */ public static void debug(int indent, String msg) { log(indent, Level.DEBUG, msg); } /** TRACE-level with indentation for nice output */ public static void trace(int indent, String msg) { log(indent, Level.TRACE, msg); } public static void log(int indent, Level level, String location, String msg) { logger.log(level, logMsg(indent, location, msg)); } private static String logMsg(int indent, String location, String msg) { StringBuilder sb = new StringBuilder(256); sb.append(location); for (int i = 0; i < indent; i++) sb.append(' '); sb.append(msg); String s = sb.toString(); return s; } public static void log(int indent, Level level, String msg) { logger.log(level, logMsg(indent, msg)); } private static String logMsg(int indent, String msg) { StringBuilder sb = new StringBuilder(256); for (int i = 0; i < indent; i++) sb.append(' '); sb.append(msg); return sb.toString(); } public static boolean isDebugEnabled() { return logger.isDebugEnabled(); } public static boolean isTraceEnabled() { return logger.isTraceEnabled(); } }
28.426471
80
0.682359