blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
5785c3bdc158a4e227ec9a832568855c199966e6
6b495e45de41200afc76fc5d5df0f2e47cbd8b6e
/Top_300+_Freq_by_Tag/Two Pointers/medium/287. Find the Duplicate Number.java
aca4e0c74e6126c441f2890bc34462f486996a3a
[]
no_license
desperatecat/leetcode_practice_set
96e4139239b01fbde66b1e75510b1250e3fade72
785a947b0ad338e17eecceae8dc1e659b6fb3221
refs/heads/master
2020-12-27T08:31:18.974520
2020-09-13T23:23:55
2020-09-13T23:23:55
237,832,998
0
0
null
null
null
null
UTF-8
Java
false
false
523
java
//https://leetcode.com/problems/find-the-duplicate-number/discuss/72846/My-easy-understood-solution-with-O(n)-time-and-O(1)-space-without-modifying-the-array.-With-clear-explanation. class Solution { public int findDuplicate(int[] nums) { if (nums.length > 1){ int slow = nums[0]; int fast = nums[nums[0]]; while (slow != fast){ slow = nums[slow]; fast = nums[nums[fast]]; } fast = 0; while (fast != slow){ fast = nums[fast]; slow = nums[slow]; } return slow; } return -1; } }
1f25640806deeb5251aee98c11b41ee8dc369048
696b0c72aa79bcb4db1a5ee003059fc69d2364ff
/tests/tests/calllog/src/android/calllog/cts/TestUtils.java
d2c57a5ead4216f38e024d25f101e196da1e1c74
[]
no_license
jpxiong/platform_cts
720ba8f0f2ce56aba4643d27df5516f9720df2d8
dd40d693dfc3030cf8e9b0bf9f450f2276feb9ca
refs/heads/master
2021-01-10T09:26:31.419082
2015-10-02T19:27:59
2015-10-02T19:27:59
43,866,634
8
2
null
null
null
null
UTF-8
Java
false
false
2,663
java
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.calllog.cts; import android.app.Instrumentation; import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.ParcelFileDescriptor; import android.telecom.PhoneAccountHandle; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class TestUtils { /** * Executes the given shell command and returns the output in a string. Note that even * if we don't care about the output, we have to read the stream completely to make the * command execute. */ public static String executeShellCommand(Instrumentation instrumentation, String command) throws Exception { BufferedReader br = null; try (InputStream in = executeStreamedShellCommand(instrumentation, command)) { br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); String str = null; StringBuilder out = new StringBuilder(); while ((str = br.readLine()) != null) { out.append(str); } return out.toString(); } finally { if (br != null) { closeQuietly(br); } } } public static FileInputStream executeStreamedShellCommand(Instrumentation instrumentation, String command) throws Exception { final ParcelFileDescriptor pfd = instrumentation.getUiAutomation().executeShellCommand(command); return new FileInputStream(pfd.getFileDescriptor()); } private static void closeQuietly(AutoCloseable closeable) { if (closeable != null) { try { closeable.close(); } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } } }
434cb9d0bc5ceb3bf1f774b105e877d89ebd5505
f0a5adeedb54a061c8e7bdfcec8d039ce15666d6
/src/com/example/tipcalculator/CalculateTipActivity.java
5a226d711a200ed977b90cc4ba0e8cba9c52acdc
[]
no_license
sumitusc/AndroidTipCalculator
2a1c2a06408e11fb1eee349b33a571ed8b85825f
44e24993d78e99d4f8189963cf4d9fa5dc4ff514
refs/heads/master
2020-04-20T10:59:47.017965
2014-01-14T06:48:11
2014-01-14T06:48:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,628
java
package com.example.tipcalculator; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Toast; import android.widget.EditText; import android.widget.TextView; public class CalculateTipActivity extends Activity { public EditText etBillAmount; public TextView tvTip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calculate_tip); etBillAmount = (EditText) findViewById(R.id.etBillAmount); tvTip = (TextView) findViewById(R.id.tvTip); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.calculate_tip, menu); return true; } public void onSubmitTenPercent(View v){ String strBillValue = etBillAmount.getText().toString(); if(strBillValue == null || strBillValue.isEmpty()){ Toast.makeText(this, "Enter a valid bill amount", Toast.LENGTH_SHORT).show(); }else{ try{ double billAmount = Double.parseDouble(strBillValue); double tip = billAmount * 0.1; tip = roundToTwoDecimals(tip); tvTip.setText("$"+Double.toString(tip)); }catch(Exception ex){ Toast.makeText(this, "Invalid bill amount: "+strBillValue, Toast.LENGTH_SHORT).show(); } } } public void onSubmitFifteenPercent(View v){ String strBillValue = etBillAmount.getText().toString(); if(strBillValue == null || strBillValue.isEmpty()){ Toast.makeText(this, "Enter a valid bill amount", Toast.LENGTH_SHORT).show(); }else{ try{ double billAmount = Double.parseDouble(strBillValue); double tip = billAmount * 0.15; tip = roundToTwoDecimals(tip); tvTip.setText("$"+Double.toString(tip)); }catch(Exception ex){ Toast.makeText(this, "Invalid bill amount: "+strBillValue, Toast.LENGTH_SHORT).show(); } } } public void onSubmitTwentyPercent(View v){ String strBillValue = etBillAmount.getText().toString(); if(strBillValue == null || strBillValue.isEmpty()){ Toast.makeText(this, "Enter a valid bill amount", Toast.LENGTH_SHORT).show(); }else{ try{ double billAmount = Double.parseDouble(strBillValue); double tip = billAmount * 0.2; tip = roundToTwoDecimals(tip); tvTip.setText("$"+Double.toString(tip)); }catch(Exception ex){ Toast.makeText(this, "Invalid bill amount: "+strBillValue, Toast.LENGTH_SHORT).show(); } } } private double roundToTwoDecimals(double d){ return ((double) Math.round(d * 100)/100); } }
[ "gupsumit@futurespoke-lm.(none)" ]
gupsumit@futurespoke-lm.(none)
3ec48e5a3c7e7168e133a33519f1e3ca48201fbb
8a09cbb8026c6f435a713cf62baba721e8327453
/realmtester/src/main/java/info/juanmendez/realmtester/demo/models/Query.java
ee6e321807f29520a1bddc241512826077d5f53b
[]
no_license
juanmendez/realm-tester
1c37780417fbdca3e4f9adbdafd791795e258303
2a25585c98b66d1db3dbe6804f47fa7051efb157
refs/heads/master
2018-12-08T20:02:50.376678
2018-09-23T18:57:56
2018-09-23T18:57:56
82,135,476
4
1
null
2018-09-12T01:00:41
2017-02-16T03:36:58
Java
UTF-8
Java
false
false
951
java
package info.juanmendez.realmtester.demo.models; public class Query { private String field; private String condition; private Object[] args; private Boolean asTrue = true; public static Query build() { return new Query(); } private Query() { } public Query setField(String field) { this.field = field; return this; } public Query setCondition(String condition) { this.condition = condition; return this; } public Query setArgs(Object[] args) { this.args = args; return this; } public Query setAsTrue(Boolean asTrue) { this.asTrue = asTrue; return this; } public String getField() { return field; } public String getCondition() { return condition; } public Object[] getArgs() { return args; } public Boolean getAsTrue() { return asTrue; } }
83254284d036e88d7faf795f1b38a8a97bdcaf50
27b91623fdc42621ee25cd2731e48e683b42a2b0
/app/src/main/java/co/com/android_dev/gdgcali/gdgcali/model/AttachmentsAnswer.java
a4a4b88b52679a02e14ac7012ca837dcd635e2c9
[]
no_license
gdgcali/GDGCaliApp
6809d67ddd8c3169ed8ded5c83963b7feed31bbd
f34384919c05b9e87a4a38872d48abcd708eedfb
refs/heads/master
2021-01-10T20:07:44.882179
2015-07-29T03:53:50
2015-07-29T03:53:50
38,412,114
5
0
null
null
null
null
UTF-8
Java
false
false
2,448
java
package co.com.android_dev.gdgcali.gdgcali.model; import com.google.gson.annotations.SerializedName; /** * Created by user on 25/06/2015. */ public class AttachmentsAnswer { @SerializedName("id") private Integer id; @SerializedName("url") private String url; @SerializedName("slug") private String slug; @SerializedName("title") private String title; @SerializedName("description") private String description; @SerializedName("caption") private String caption; @SerializedName("parent") private Integer parent; @SerializedName("mime_type") private String mime_type; @SerializedName("images") private ImageAnswer images; public AttachmentsAnswer(Integer id, String url, String slug, String title, String description, String caption, Integer parent, String mime_type, ImageAnswer images) { this.id = id; this.url = url; this.slug = slug; this.title = title; this.description = description; this.caption = caption; this.parent = parent; this.mime_type = mime_type; this.images = images; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public Integer getParent() { return parent; } public void setParent(Integer parent) { this.parent = parent; } public String getMime_type() { return mime_type; } public void setMime_type(String mime_type) { this.mime_type = mime_type; } public ImageAnswer getImages() { return images; } public void setImages(ImageAnswer images) { this.images = images; } }
0b2612cacdad71124a80f5f8b0d855e26bf46540
0cc6bc0a0c92b9903b163a7aeb4f013c1a9fd795
/google-speech-protobuf/src/main/java/nlp_fst/Path.java
7bc10c09ae16766abb930366ab2f7d178623f309
[]
no_license
jackz314/SpeechRecognizer
fe34254727ae44ee3ddd83daad873257df1ac078
07ba8ec2a158830b37000bb3750a4f7c622b12d0
refs/heads/master
2023-04-08T09:24:19.079178
2021-04-12T23:55:33
2021-04-12T23:55:33
320,767,241
3
2
null
null
null
null
UTF-8
Java
false
true
56,321
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: speech/fst/path.proto package nlp_fst; public final class Path { private Path() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface SymbolicPathOrBuilder extends // @@protoc_insertion_point(interface_extends:nlp_fst.SymbolicPath) com.google.protobuf.MessageOrBuilder { /** * <code>repeated int64 ilabel = 1;</code> * @return A list containing the ilabel. */ java.util.List<java.lang.Long> getIlabelList(); /** * <code>repeated int64 ilabel = 1;</code> * @return The count of ilabel. */ int getIlabelCount(); /** * <code>repeated int64 ilabel = 1;</code> * @param index The index of the element to return. * @return The ilabel at the given index. */ long getIlabel(int index); /** * <code>repeated int64 olabel = 2;</code> * @return A list containing the olabel. */ java.util.List<java.lang.Long> getOlabelList(); /** * <code>repeated int64 olabel = 2;</code> * @return The count of olabel. */ int getOlabelCount(); /** * <code>repeated int64 olabel = 2;</code> * @param index The index of the element to return. * @return The olabel at the given index. */ long getOlabel(int index); /** * <code>repeated string isymbol = 4;</code> * @return A list containing the isymbol. */ java.util.List<java.lang.String> getIsymbolList(); /** * <code>repeated string isymbol = 4;</code> * @return The count of isymbol. */ int getIsymbolCount(); /** * <code>repeated string isymbol = 4;</code> * @param index The index of the element to return. * @return The isymbol at the given index. */ java.lang.String getIsymbol(int index); /** * <code>repeated string isymbol = 4;</code> * @param index The index of the value to return. * @return The bytes of the isymbol at the given index. */ com.google.protobuf.ByteString getIsymbolBytes(int index); /** * <code>repeated string osymbol = 5;</code> * @return A list containing the osymbol. */ java.util.List<java.lang.String> getOsymbolList(); /** * <code>repeated string osymbol = 5;</code> * @return The count of osymbol. */ int getOsymbolCount(); /** * <code>repeated string osymbol = 5;</code> * @param index The index of the element to return. * @return The osymbol at the given index. */ java.lang.String getOsymbol(int index); /** * <code>repeated string osymbol = 5;</code> * @param index The index of the value to return. * @return The bytes of the osymbol at the given index. */ com.google.protobuf.ByteString getOsymbolBytes(int index); /** * <code>required float weight = 3;</code> * @return Whether the weight field is set. */ boolean hasWeight(); /** * <code>required float weight = 3;</code> * @return The weight. */ float getWeight(); } /** * Protobuf type {@code nlp_fst.SymbolicPath} */ public static final class SymbolicPath extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:nlp_fst.SymbolicPath) SymbolicPathOrBuilder { private static final long serialVersionUID = 0L; // Use SymbolicPath.newBuilder() to construct. private SymbolicPath(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SymbolicPath() { ilabel_ = emptyLongList(); olabel_ = emptyLongList(); isymbol_ = com.google.protobuf.LazyStringArrayList.EMPTY; osymbol_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new SymbolicPath(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPath_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPath_fieldAccessorTable .ensureFieldAccessorsInitialized( nlp_fst.Path.SymbolicPath.class, nlp_fst.Path.SymbolicPath.Builder.class); } private int bitField0_; public static final int ILABEL_FIELD_NUMBER = 1; private com.google.protobuf.Internal.LongList ilabel_; /** * <code>repeated int64 ilabel = 1;</code> * @return A list containing the ilabel. */ @java.lang.Override public java.util.List<java.lang.Long> getIlabelList() { return ilabel_; } /** * <code>repeated int64 ilabel = 1;</code> * @return The count of ilabel. */ public int getIlabelCount() { return ilabel_.size(); } /** * <code>repeated int64 ilabel = 1;</code> * @param index The index of the element to return. * @return The ilabel at the given index. */ public long getIlabel(int index) { return ilabel_.getLong(index); } public static final int OLABEL_FIELD_NUMBER = 2; private com.google.protobuf.Internal.LongList olabel_; /** * <code>repeated int64 olabel = 2;</code> * @return A list containing the olabel. */ @java.lang.Override public java.util.List<java.lang.Long> getOlabelList() { return olabel_; } /** * <code>repeated int64 olabel = 2;</code> * @return The count of olabel. */ public int getOlabelCount() { return olabel_.size(); } /** * <code>repeated int64 olabel = 2;</code> * @param index The index of the element to return. * @return The olabel at the given index. */ public long getOlabel(int index) { return olabel_.getLong(index); } public static final int ISYMBOL_FIELD_NUMBER = 4; private com.google.protobuf.LazyStringList isymbol_; /** * <code>repeated string isymbol = 4;</code> * @return A list containing the isymbol. */ public com.google.protobuf.ProtocolStringList getIsymbolList() { return isymbol_; } /** * <code>repeated string isymbol = 4;</code> * @return The count of isymbol. */ public int getIsymbolCount() { return isymbol_.size(); } /** * <code>repeated string isymbol = 4;</code> * @param index The index of the element to return. * @return The isymbol at the given index. */ public java.lang.String getIsymbol(int index) { return isymbol_.get(index); } /** * <code>repeated string isymbol = 4;</code> * @param index The index of the value to return. * @return The bytes of the isymbol at the given index. */ public com.google.protobuf.ByteString getIsymbolBytes(int index) { return isymbol_.getByteString(index); } public static final int OSYMBOL_FIELD_NUMBER = 5; private com.google.protobuf.LazyStringList osymbol_; /** * <code>repeated string osymbol = 5;</code> * @return A list containing the osymbol. */ public com.google.protobuf.ProtocolStringList getOsymbolList() { return osymbol_; } /** * <code>repeated string osymbol = 5;</code> * @return The count of osymbol. */ public int getOsymbolCount() { return osymbol_.size(); } /** * <code>repeated string osymbol = 5;</code> * @param index The index of the element to return. * @return The osymbol at the given index. */ public java.lang.String getOsymbol(int index) { return osymbol_.get(index); } /** * <code>repeated string osymbol = 5;</code> * @param index The index of the value to return. * @return The bytes of the osymbol at the given index. */ public com.google.protobuf.ByteString getOsymbolBytes(int index) { return osymbol_.getByteString(index); } public static final int WEIGHT_FIELD_NUMBER = 3; private float weight_; /** * <code>required float weight = 3;</code> * @return Whether the weight field is set. */ @java.lang.Override public boolean hasWeight() { return ((bitField0_ & 0x00000001) != 0); } /** * <code>required float weight = 3;</code> * @return The weight. */ @java.lang.Override public float getWeight() { return weight_; } public static nlp_fst.Path.SymbolicPath parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static nlp_fst.Path.SymbolicPath parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static nlp_fst.Path.SymbolicPath parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static nlp_fst.Path.SymbolicPath parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static nlp_fst.Path.SymbolicPath parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static nlp_fst.Path.SymbolicPath parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static nlp_fst.Path.SymbolicPath parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static nlp_fst.Path.SymbolicPath parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static nlp_fst.Path.SymbolicPath parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static nlp_fst.Path.SymbolicPath parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static nlp_fst.Path.SymbolicPath parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static nlp_fst.Path.SymbolicPath parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(nlp_fst.Path.SymbolicPath prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code nlp_fst.SymbolicPath} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:nlp_fst.SymbolicPath) nlp_fst.Path.SymbolicPathOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPath_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPath_fieldAccessorTable .ensureFieldAccessorsInitialized( nlp_fst.Path.SymbolicPath.class, nlp_fst.Path.SymbolicPath.Builder.class); } // Construct using nlp_fst.Path.SymbolicPath.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); ilabel_ = emptyLongList(); bitField0_ = (bitField0_ & ~0x00000001); olabel_ = emptyLongList(); bitField0_ = (bitField0_ & ~0x00000002); isymbol_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); osymbol_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); weight_ = 0F; bitField0_ = (bitField0_ & ~0x00000010); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPath_descriptor; } @java.lang.Override public nlp_fst.Path.SymbolicPath getDefaultInstanceForType() { return nlp_fst.Path.SymbolicPath.getDefaultInstance(); } @java.lang.Override public nlp_fst.Path.SymbolicPath build() { nlp_fst.Path.SymbolicPath result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public nlp_fst.Path.SymbolicPath buildPartial() { nlp_fst.Path.SymbolicPath result = new nlp_fst.Path.SymbolicPath(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((bitField0_ & 0x00000001) != 0)) { ilabel_.makeImmutable(); bitField0_ = (bitField0_ & ~0x00000001); } result.ilabel_ = ilabel_; if (((bitField0_ & 0x00000002) != 0)) { olabel_.makeImmutable(); bitField0_ = (bitField0_ & ~0x00000002); } result.olabel_ = olabel_; if (((bitField0_ & 0x00000004) != 0)) { isymbol_ = isymbol_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000004); } result.isymbol_ = isymbol_; if (((bitField0_ & 0x00000008) != 0)) { osymbol_ = osymbol_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000008); } result.osymbol_ = osymbol_; if (((from_bitField0_ & 0x00000010) != 0)) { result.weight_ = weight_; to_bitField0_ |= 0x00000001; } result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } private int bitField0_; private com.google.protobuf.Internal.LongList ilabel_ = emptyLongList(); private void ensureIlabelIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { ilabel_ = mutableCopy(ilabel_); bitField0_ |= 0x00000001; } } /** * <code>repeated int64 ilabel = 1;</code> * @return A list containing the ilabel. */ public java.util.List<java.lang.Long> getIlabelList() { return ((bitField0_ & 0x00000001) != 0) ? java.util.Collections.unmodifiableList(ilabel_) : ilabel_; } /** * <code>repeated int64 ilabel = 1;</code> * @return The count of ilabel. */ public int getIlabelCount() { return ilabel_.size(); } /** * <code>repeated int64 ilabel = 1;</code> * @param index The index of the element to return. * @return The ilabel at the given index. */ public long getIlabel(int index) { return ilabel_.getLong(index); } /** * <code>repeated int64 ilabel = 1;</code> * @param index The index to set the value at. * @param value The ilabel to set. * @return This builder for chaining. */ public Builder setIlabel( int index, long value) { ensureIlabelIsMutable(); ilabel_.setLong(index, value); onChanged(); return this; } /** * <code>repeated int64 ilabel = 1;</code> * @param value The ilabel to add. * @return This builder for chaining. */ public Builder addIlabel(long value) { ensureIlabelIsMutable(); ilabel_.addLong(value); onChanged(); return this; } /** * <code>repeated int64 ilabel = 1;</code> * @param values The ilabel to add. * @return This builder for chaining. */ public Builder addAllIlabel( java.lang.Iterable<? extends java.lang.Long> values) { ensureIlabelIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, ilabel_); onChanged(); return this; } /** * <code>repeated int64 ilabel = 1;</code> * @return This builder for chaining. */ public Builder clearIlabel() { ilabel_ = emptyLongList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } private com.google.protobuf.Internal.LongList olabel_ = emptyLongList(); private void ensureOlabelIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { olabel_ = mutableCopy(olabel_); bitField0_ |= 0x00000002; } } /** * <code>repeated int64 olabel = 2;</code> * @return A list containing the olabel. */ public java.util.List<java.lang.Long> getOlabelList() { return ((bitField0_ & 0x00000002) != 0) ? java.util.Collections.unmodifiableList(olabel_) : olabel_; } /** * <code>repeated int64 olabel = 2;</code> * @return The count of olabel. */ public int getOlabelCount() { return olabel_.size(); } /** * <code>repeated int64 olabel = 2;</code> * @param index The index of the element to return. * @return The olabel at the given index. */ public long getOlabel(int index) { return olabel_.getLong(index); } /** * <code>repeated int64 olabel = 2;</code> * @param index The index to set the value at. * @param value The olabel to set. * @return This builder for chaining. */ public Builder setOlabel( int index, long value) { ensureOlabelIsMutable(); olabel_.setLong(index, value); onChanged(); return this; } /** * <code>repeated int64 olabel = 2;</code> * @param value The olabel to add. * @return This builder for chaining. */ public Builder addOlabel(long value) { ensureOlabelIsMutable(); olabel_.addLong(value); onChanged(); return this; } /** * <code>repeated int64 olabel = 2;</code> * @param values The olabel to add. * @return This builder for chaining. */ public Builder addAllOlabel( java.lang.Iterable<? extends java.lang.Long> values) { ensureOlabelIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, olabel_); onChanged(); return this; } /** * <code>repeated int64 olabel = 2;</code> * @return This builder for chaining. */ public Builder clearOlabel() { olabel_ = emptyLongList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } private com.google.protobuf.LazyStringList isymbol_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureIsymbolIsMutable() { if (!((bitField0_ & 0x00000004) != 0)) { isymbol_ = new com.google.protobuf.LazyStringArrayList(isymbol_); bitField0_ |= 0x00000004; } } /** * <code>repeated string isymbol = 4;</code> * @return A list containing the isymbol. */ public com.google.protobuf.ProtocolStringList getIsymbolList() { return isymbol_.getUnmodifiableView(); } /** * <code>repeated string isymbol = 4;</code> * @return The count of isymbol. */ public int getIsymbolCount() { return isymbol_.size(); } /** * <code>repeated string isymbol = 4;</code> * @param index The index of the element to return. * @return The isymbol at the given index. */ public java.lang.String getIsymbol(int index) { return isymbol_.get(index); } /** * <code>repeated string isymbol = 4;</code> * @param index The index of the value to return. * @return The bytes of the isymbol at the given index. */ public com.google.protobuf.ByteString getIsymbolBytes(int index) { return isymbol_.getByteString(index); } /** * <code>repeated string isymbol = 4;</code> * @param index The index to set the value at. * @param value The isymbol to set. * @return This builder for chaining. */ public Builder setIsymbol( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureIsymbolIsMutable(); isymbol_.set(index, value); onChanged(); return this; } /** * <code>repeated string isymbol = 4;</code> * @param value The isymbol to add. * @return This builder for chaining. */ public Builder addIsymbol( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureIsymbolIsMutable(); isymbol_.add(value); onChanged(); return this; } /** * <code>repeated string isymbol = 4;</code> * @param values The isymbol to add. * @return This builder for chaining. */ public Builder addAllIsymbol( java.lang.Iterable<java.lang.String> values) { ensureIsymbolIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, isymbol_); onChanged(); return this; } /** * <code>repeated string isymbol = 4;</code> * @return This builder for chaining. */ public Builder clearIsymbol() { isymbol_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <code>repeated string isymbol = 4;</code> * @param value The bytes of the isymbol to add. * @return This builder for chaining. */ public Builder addIsymbolBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureIsymbolIsMutable(); isymbol_.add(value); onChanged(); return this; } private com.google.protobuf.LazyStringList osymbol_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureOsymbolIsMutable() { if (!((bitField0_ & 0x00000008) != 0)) { osymbol_ = new com.google.protobuf.LazyStringArrayList(osymbol_); bitField0_ |= 0x00000008; } } /** * <code>repeated string osymbol = 5;</code> * @return A list containing the osymbol. */ public com.google.protobuf.ProtocolStringList getOsymbolList() { return osymbol_.getUnmodifiableView(); } /** * <code>repeated string osymbol = 5;</code> * @return The count of osymbol. */ public int getOsymbolCount() { return osymbol_.size(); } /** * <code>repeated string osymbol = 5;</code> * @param index The index of the element to return. * @return The osymbol at the given index. */ public java.lang.String getOsymbol(int index) { return osymbol_.get(index); } /** * <code>repeated string osymbol = 5;</code> * @param index The index of the value to return. * @return The bytes of the osymbol at the given index. */ public com.google.protobuf.ByteString getOsymbolBytes(int index) { return osymbol_.getByteString(index); } /** * <code>repeated string osymbol = 5;</code> * @param index The index to set the value at. * @param value The osymbol to set. * @return This builder for chaining. */ public Builder setOsymbol( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureOsymbolIsMutable(); osymbol_.set(index, value); onChanged(); return this; } /** * <code>repeated string osymbol = 5;</code> * @param value The osymbol to add. * @return This builder for chaining. */ public Builder addOsymbol( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureOsymbolIsMutable(); osymbol_.add(value); onChanged(); return this; } /** * <code>repeated string osymbol = 5;</code> * @param values The osymbol to add. * @return This builder for chaining. */ public Builder addAllOsymbol( java.lang.Iterable<java.lang.String> values) { ensureOsymbolIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, osymbol_); onChanged(); return this; } /** * <code>repeated string osymbol = 5;</code> * @return This builder for chaining. */ public Builder clearOsymbol() { osymbol_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * <code>repeated string osymbol = 5;</code> * @param value The bytes of the osymbol to add. * @return This builder for chaining. */ public Builder addOsymbolBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureOsymbolIsMutable(); osymbol_.add(value); onChanged(); return this; } private float weight_ ; /** * <code>required float weight = 3;</code> * @return Whether the weight field is set. */ @java.lang.Override public boolean hasWeight() { return ((bitField0_ & 0x00000010) != 0); } /** * <code>required float weight = 3;</code> * @return The weight. */ @java.lang.Override public float getWeight() { return weight_; } /** * <code>required float weight = 3;</code> * @param value The weight to set. * @return This builder for chaining. */ public Builder setWeight(float value) { bitField0_ |= 0x00000010; weight_ = value; onChanged(); return this; } /** * <code>required float weight = 3;</code> * @return This builder for chaining. */ public Builder clearWeight() { bitField0_ = (bitField0_ & ~0x00000010); weight_ = 0F; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:nlp_fst.SymbolicPath) } // @@protoc_insertion_point(class_scope:nlp_fst.SymbolicPath) private static final nlp_fst.Path.SymbolicPath DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new nlp_fst.Path.SymbolicPath(); } public static nlp_fst.Path.SymbolicPath getDefaultInstance() { return DEFAULT_INSTANCE; } @java.lang.Deprecated public static final com.google.protobuf.Parser<SymbolicPath> PARSER = new com.google.protobuf.AbstractParser<SymbolicPath>() { @java.lang.Override public SymbolicPath parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage( builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<SymbolicPath> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SymbolicPath> getParserForType() { return PARSER; } @java.lang.Override public nlp_fst.Path.SymbolicPath getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface SymbolicPathsOrBuilder extends // @@protoc_insertion_point(interface_extends:nlp_fst.SymbolicPaths) com.google.protobuf.MessageOrBuilder { /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ java.util.List<nlp_fst.Path.SymbolicPath> getPathList(); /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ nlp_fst.Path.SymbolicPath getPath(int index); /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ int getPathCount(); /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ java.util.List<? extends nlp_fst.Path.SymbolicPathOrBuilder> getPathOrBuilderList(); /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ nlp_fst.Path.SymbolicPathOrBuilder getPathOrBuilder( int index); } /** * Protobuf type {@code nlp_fst.SymbolicPaths} */ public static final class SymbolicPaths extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:nlp_fst.SymbolicPaths) SymbolicPathsOrBuilder { private static final long serialVersionUID = 0L; // Use SymbolicPaths.newBuilder() to construct. private SymbolicPaths(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SymbolicPaths() { path_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new SymbolicPaths(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPaths_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPaths_fieldAccessorTable .ensureFieldAccessorsInitialized( nlp_fst.Path.SymbolicPaths.class, nlp_fst.Path.SymbolicPaths.Builder.class); } public static final int PATH_FIELD_NUMBER = 1; private java.util.List<nlp_fst.Path.SymbolicPath> path_; /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ @java.lang.Override public java.util.List<nlp_fst.Path.SymbolicPath> getPathList() { return path_; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ @java.lang.Override public java.util.List<? extends nlp_fst.Path.SymbolicPathOrBuilder> getPathOrBuilderList() { return path_; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ @java.lang.Override public int getPathCount() { return path_.size(); } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ @java.lang.Override public nlp_fst.Path.SymbolicPath getPath(int index) { return path_.get(index); } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ @java.lang.Override public nlp_fst.Path.SymbolicPathOrBuilder getPathOrBuilder( int index) { return path_.get(index); } public static nlp_fst.Path.SymbolicPaths parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static nlp_fst.Path.SymbolicPaths parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static nlp_fst.Path.SymbolicPaths parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static nlp_fst.Path.SymbolicPaths parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static nlp_fst.Path.SymbolicPaths parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static nlp_fst.Path.SymbolicPaths parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static nlp_fst.Path.SymbolicPaths parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static nlp_fst.Path.SymbolicPaths parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static nlp_fst.Path.SymbolicPaths parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static nlp_fst.Path.SymbolicPaths parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static nlp_fst.Path.SymbolicPaths parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static nlp_fst.Path.SymbolicPaths parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(nlp_fst.Path.SymbolicPaths prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code nlp_fst.SymbolicPaths} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:nlp_fst.SymbolicPaths) nlp_fst.Path.SymbolicPathsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPaths_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPaths_fieldAccessorTable .ensureFieldAccessorsInitialized( nlp_fst.Path.SymbolicPaths.class, nlp_fst.Path.SymbolicPaths.Builder.class); } // Construct using nlp_fst.Path.SymbolicPaths.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getPathFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (pathBuilder_ == null) { path_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { pathBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return nlp_fst.Path.internal_static_nlp_fst_SymbolicPaths_descriptor; } @java.lang.Override public nlp_fst.Path.SymbolicPaths getDefaultInstanceForType() { return nlp_fst.Path.SymbolicPaths.getDefaultInstance(); } @java.lang.Override public nlp_fst.Path.SymbolicPaths build() { nlp_fst.Path.SymbolicPaths result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public nlp_fst.Path.SymbolicPaths buildPartial() { nlp_fst.Path.SymbolicPaths result = new nlp_fst.Path.SymbolicPaths(this); int from_bitField0_ = bitField0_; if (pathBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { path_ = java.util.Collections.unmodifiableList(path_); bitField0_ = (bitField0_ & ~0x00000001); } result.path_ = path_; } else { result.path_ = pathBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } private int bitField0_; private java.util.List<nlp_fst.Path.SymbolicPath> path_ = java.util.Collections.emptyList(); private void ensurePathIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { path_ = new java.util.ArrayList<nlp_fst.Path.SymbolicPath>(path_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< nlp_fst.Path.SymbolicPath, nlp_fst.Path.SymbolicPath.Builder, nlp_fst.Path.SymbolicPathOrBuilder> pathBuilder_; /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public java.util.List<nlp_fst.Path.SymbolicPath> getPathList() { if (pathBuilder_ == null) { return java.util.Collections.unmodifiableList(path_); } else { return pathBuilder_.getMessageList(); } } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public int getPathCount() { if (pathBuilder_ == null) { return path_.size(); } else { return pathBuilder_.getCount(); } } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public nlp_fst.Path.SymbolicPath getPath(int index) { if (pathBuilder_ == null) { return path_.get(index); } else { return pathBuilder_.getMessage(index); } } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder setPath( int index, nlp_fst.Path.SymbolicPath value) { if (pathBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePathIsMutable(); path_.set(index, value); onChanged(); } else { pathBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder setPath( int index, nlp_fst.Path.SymbolicPath.Builder builderForValue) { if (pathBuilder_ == null) { ensurePathIsMutable(); path_.set(index, builderForValue.build()); onChanged(); } else { pathBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder addPath(nlp_fst.Path.SymbolicPath value) { if (pathBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePathIsMutable(); path_.add(value); onChanged(); } else { pathBuilder_.addMessage(value); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder addPath( int index, nlp_fst.Path.SymbolicPath value) { if (pathBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePathIsMutable(); path_.add(index, value); onChanged(); } else { pathBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder addPath( nlp_fst.Path.SymbolicPath.Builder builderForValue) { if (pathBuilder_ == null) { ensurePathIsMutable(); path_.add(builderForValue.build()); onChanged(); } else { pathBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder addPath( int index, nlp_fst.Path.SymbolicPath.Builder builderForValue) { if (pathBuilder_ == null) { ensurePathIsMutable(); path_.add(index, builderForValue.build()); onChanged(); } else { pathBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder addAllPath( java.lang.Iterable<? extends nlp_fst.Path.SymbolicPath> values) { if (pathBuilder_ == null) { ensurePathIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, path_); onChanged(); } else { pathBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder clearPath() { if (pathBuilder_ == null) { path_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { pathBuilder_.clear(); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public Builder removePath(int index) { if (pathBuilder_ == null) { ensurePathIsMutable(); path_.remove(index); onChanged(); } else { pathBuilder_.remove(index); } return this; } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public nlp_fst.Path.SymbolicPath.Builder getPathBuilder( int index) { return getPathFieldBuilder().getBuilder(index); } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public nlp_fst.Path.SymbolicPathOrBuilder getPathOrBuilder( int index) { if (pathBuilder_ == null) { return path_.get(index); } else { return pathBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public java.util.List<? extends nlp_fst.Path.SymbolicPathOrBuilder> getPathOrBuilderList() { if (pathBuilder_ != null) { return pathBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(path_); } } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public nlp_fst.Path.SymbolicPath.Builder addPathBuilder() { return getPathFieldBuilder().addBuilder( nlp_fst.Path.SymbolicPath.getDefaultInstance()); } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public nlp_fst.Path.SymbolicPath.Builder addPathBuilder( int index) { return getPathFieldBuilder().addBuilder( index, nlp_fst.Path.SymbolicPath.getDefaultInstance()); } /** * <code>repeated .nlp_fst.SymbolicPath path = 1;</code> */ public java.util.List<nlp_fst.Path.SymbolicPath.Builder> getPathBuilderList() { return getPathFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< nlp_fst.Path.SymbolicPath, nlp_fst.Path.SymbolicPath.Builder, nlp_fst.Path.SymbolicPathOrBuilder> getPathFieldBuilder() { if (pathBuilder_ == null) { pathBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< nlp_fst.Path.SymbolicPath, nlp_fst.Path.SymbolicPath.Builder, nlp_fst.Path.SymbolicPathOrBuilder>( path_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); path_ = null; } return pathBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:nlp_fst.SymbolicPaths) } // @@protoc_insertion_point(class_scope:nlp_fst.SymbolicPaths) private static final nlp_fst.Path.SymbolicPaths DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new nlp_fst.Path.SymbolicPaths(); } public static nlp_fst.Path.SymbolicPaths getDefaultInstance() { return DEFAULT_INSTANCE; } @java.lang.Deprecated public static final com.google.protobuf.Parser<SymbolicPaths> PARSER = new com.google.protobuf.AbstractParser<SymbolicPaths>() { @java.lang.Override public SymbolicPaths parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage( builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<SymbolicPaths> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SymbolicPaths> getParserForType() { return PARSER; } @java.lang.Override public nlp_fst.Path.SymbolicPaths getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_nlp_fst_SymbolicPath_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_nlp_fst_SymbolicPath_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_nlp_fst_SymbolicPaths_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_nlp_fst_SymbolicPaths_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\025speech/fst/path.proto\022\007nlp_fst\"`\n\014Symb" + "olicPath\022\016\n\006ilabel\030\001 \003(\003\022\016\n\006olabel\030\002 \003(\003" + "\022\017\n\007isymbol\030\004 \003(\t\022\017\n\007osymbol\030\005 \003(\t\022\016\n\006we" + "ight\030\003 \002(\002\"4\n\rSymbolicPaths\022#\n\004path\030\001 \003(" + "\0132\025.nlp_fst.SymbolicPathB\002H\002" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_nlp_fst_SymbolicPath_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_nlp_fst_SymbolicPath_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_nlp_fst_SymbolicPath_descriptor, new java.lang.String[] { "Ilabel", "Olabel", "Isymbol", "Osymbol", "Weight", }); internal_static_nlp_fst_SymbolicPaths_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_nlp_fst_SymbolicPaths_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_nlp_fst_SymbolicPaths_descriptor, new java.lang.String[] { "Path", }); } // @@protoc_insertion_point(outer_class_scope) }
d614933f2594f3c8c65f03070f067b8df5a6ced5
c4086e3cf193104c662ba1a4d4cadce9a7767f5b
/express/WEB-INF/classes/com/alltel/lsr/common/util/PostEvent.java
e0b77133e085c2dd29f4900b9e2e8a697b72c7c6
[]
no_license
srijithManeshkumar/ExpressApp
7b64eccd1fc5cc82252a7ae6008f5e7666f3dc05
7997e3f0cde56404915b0473b1357ea4c64b22d4
refs/heads/master
2023-05-09T02:06:03.916506
2021-05-25T14:11:56
2021-05-25T14:11:56
370,685,144
0
0
null
null
null
null
UTF-8
Java
false
false
5,022
java
/* * NOTICE: * THIS MATERIAL CONTAINS TRADE SECRETS THAT BELONGS TO ALLTEL INFORMATION * SERVICES, INC. AND IS LICENSED BY AN AGREEMENT. ANY UNAUTHORIZED ACCESS, * USE, DUPLICATION, OR DISCLOSURE IS UNLAWFUL. * * COPYRIGHT (C) 2004 * BY * Alltel Communications Inc */ /* * MODULE: PostEvent.java * * DESCRIPTION: * Post events (like XML) to URL * AUTHOR: * DATE: * * CHANGE HISTORY: * 03/22/2004 pjs init * */ /* $Log: $ /* */ package com.alltel.lsr.common.util; import org.w3c.dom.*; import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import com.alltel.lsr.common.util.*; public class PostEvent { private String m_strURL; private String m_strParamsString; private String m_strResponse; public void setURL(String strURL) { this.m_strURL = strURL; } public String getURL() { return this.m_strURL; } public void setParams(String strParams) { this.m_strParamsString = strParams; } public String getParams() { return this.m_strParamsString; } public void setResponseString(String strValue) { this.m_strResponse = strValue; } public String getResponseString() { return this.m_strResponse; } public Document getResponseDocument() throws Exception { XMLUtility xmlUtility = new XMLUtility(); Document returnDocument = xmlUtility.inputStreamToXML(new java.io.ByteArrayInputStream(this.getResponseString().getBytes())); return returnDocument; } // Push a 'GET' xml event to a URL public int sendXMLRequestGET(String strXMLEvent) { int iRC=0; String tmpURL=""; Log.write(Log.DEBUG_VERBOSE,"PostEvent.sendXMLRequest() URL=["+ m_strURL + "]"); Log.write(Log.DEBUG_VERBOSE,"PostEvent.sendXMLRequest() Event=["+strXMLEvent+"]"); setResponseString(""); String strDocRoot = ""; String response = ""; try { int rootIndexStart = 0; int rootIndexEnd = 0; String strOneLine = null; String responseString = ""; // Construct URL && Connection //NOTE: Xml event must be encoded cause it can contain spaces, special chars, etc //String strEncodedURL = m_strURL + URLEncoder.encode(strXMLEvent); String strEncodedURL = m_strURL + URLEncoder.encode(strXMLEvent, "UTF-8"); Log.write(Log.DEBUG_VERBOSE,"PostEvent.sendXMLRequest() strEncodedURL=\n["+ strEncodedURL + "]"); URL url = new URL(strEncodedURL); URLConnection con = url.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( con.getInputStream() ) ); int j=0; if (!in.ready() && j < 30) //get other URL a chance to respond.... { Log.write(Log.DEBUG_VERBOSE,"PostEvent.sendXMLRequest() waiting..."); Thread.sleep(1000); j++; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i=in.read();i > -1;i=in.read()) baos.write(i); byte xmlbytes[] = baos.toByteArray(); baos.close(); // 7-12 String strTemp22 = new String(xmlbytes) ; String strTemp22 = baos.toString(); setResponseString(strTemp22); //Log.write(Log.DEBUG_VERBOSE,"inputStreamToXML =\n"+new String(xmlbytes)); Log.write(Log.DEBUG_VERBOSE,"inputStreamToXML =\n"+getResponseString() ); in.close(); } catch (Exception ee) { System.out.println("Event Check Exception: " + ee.toString()); Log.write(Log.ERROR,"Event Check Exception: " + ee.toString()); iRC=-1; } catch (Throwable e) { System.out.println("Event Check throwable: " + e.toString()); Log.write(Log.ERROR,"Event Check throwable: " + e.toString()); iRC=-2; } return iRC; }//end of sendXMLRequest() // Push a 'POST' xml event to a URL public int sendXMLRequestPOST(String strXMLEvent) throws Exception { int iRC=0; String tmpURL=""; InputStream inputStream = null; Log.write(Log.DEBUG_VERBOSE,"PostEvent.POST() URL=["+ m_strURL + "]"); Log.write(Log.DEBUG_VERBOSE,"PostEvent.POST() Event=["+strXMLEvent+"]"); URL url = new URL(m_strURL); HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("HTTP-Version","HTTP/1.1"); httpURLConnection.setDoOutput(true); OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write( strXMLEvent.toString().getBytes() ); Log.write(Log.DEBUG_VERBOSE,"PostEvent.POST() after POST"); inputStream = httpURLConnection.getInputStream(); Log.write(Log.DEBUG_VERBOSE,"PostEvent.POST() after POST"); XMLUtility xmlUtility = new XMLUtility(); Document returnDocument = xmlUtility.inputStreamToXML(inputStream); // 7-12 String strTemp22 = new String(xmlbytes) ; // String strTemp22 = baos.toString(); // return returnDocument; return iRC; } }
88b2be91c28becffd917784d4da9c77675fdb540
eb33ac1a80b0964d3aa23e2ab21e5bb554000c0b
/src/main/java/com/huawei/it/service/dto/package-info.java
5d62c076f21f5c1bf99e81986c845723e85db76e
[]
no_license
bearlly/msnlp
f7cb56d0e6a04c52fad2526cb8d1e64dc71775d3
0469dcd046893386e989803b1a6f2ecebd45c2dc
refs/heads/master
2020-03-24T07:34:39.001160
2018-07-27T11:25:56
2018-07-27T11:25:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
69
java
/** * Data Transfer Objects. */ package com.huawei.it.service.dto;
cc8aa89354cf3e849db937fb140ceedd0c8ad89a
087136b0ead4dde00b557a02a181be6ea7081c9a
/SupetsCamera/thirdlib/MotuSDKLib/src_sdk/cn/jingling/lib/filters/onekey/CameraFuguSceneryLive.java
d6bff49cb852ff73220146b26b170b6dd9032b8c
[]
no_license
JiShangShiDai/supets-camera
34fb32d16ebeb8de5d0271dbc9fa83314998895c
4976922fd77cfc62afbe64836185faa03642254f
refs/heads/master
2021-05-14T10:59:44.532044
2017-08-09T03:57:56
2017-08-09T03:57:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
740
java
package cn.jingling.lib.filters.onekey; import android.content.Context; import android.graphics.Bitmap; import cn.jingling.lib.filters.CMTProcessor; import cn.jingling.lib.filters.Curve; import cn.jingling.lib.filters.OneKeyFilter; public class CameraFuguSceneryLive extends OneKeyFilter { @Override public Bitmap apply(Context cx, Bitmap bm) { this.statisticEvent(); int w = bm.getWidth(); int h = bm.getHeight(); int[] pixels = new int[w * h]; bm.getPixels(pixels, 0, w, 0, 0, w, h); Curve c = new Curve(cx, "curves/live_fugu_scenery.dat"); CMTProcessor.curveEffect(pixels, c.getCurveRed(), c.getCurveGreen(), c.getCurveBlue(), w, h); bm.setPixels(pixels, 0, w, 0, 0, w, h); pixels = null; return bm; } }
b58cfaea8f696d61b275f5cdf74fae540566e705
9dd1526e874ee69e78abe01ce59e8d13011986d3
/src/cn/edu/zjut/po/Customer.java
637456aa32a77a3c4e6e09251af96f43ea7089f1
[]
no_license
MarsDingC/hibernate-prj1
ede4384f9e67001e1384f9185fc3f913e7dff6ef
877858cb860f72e7440692681103c1576997e38b
refs/heads/master
2021-05-06T14:08:32.916103
2017-12-06T14:39:01
2017-12-06T14:39:01
113,327,329
0
0
null
null
null
null
UTF-8
Java
false
false
4,425
java
package cn.edu.zjut.po; import java.sql.Date; /** * Created by 92377 on 2017/11/8. */ public class Customer { private int customerId; private String account; private String name; private String password; private String sex; private Date birthday; private ContactInfo contactInfo; public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public ContactInfo getContactInfo() { return contactInfo; } public void setContactInfo(ContactInfo contactInfo) { this.contactInfo = contactInfo; } public String getPhone() { return contactInfo.getPhone(); } public void setPhone(String phone) { contactInfo.setPhone(phone); } public String getEmail() { return contactInfo.getEmail(); } public void setEmail(String email) {contactInfo.setEmail(email);} public String getAddress() { return contactInfo.getAddress(); } public void setAddress(String address) { contactInfo.setAddress(address); } public String getZipcode() { return contactInfo.getZipcode(); } public void setZipcode(String zipcode) { contactInfo.setZipcode(zipcode); } public String getFax() { return contactInfo.getFax(); } public void setFax(String fax) { contactInfo.setFax(fax); } public Customer() { super(); contactInfo=new ContactInfo(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer customer = (Customer) o; if (customerId != customer.customerId) return false; if (account != null ? !account.equals(customer.account) : customer.account != null) return false; if (name != null ? !name.equals(customer.name) : customer.name != null) return false; if (password != null ? !password.equals(customer.password) : customer.password != null) return false; if (sex != null ? !sex.equals(customer.sex) : customer.sex != null) return false; if (birthday != null ? !birthday.equals(customer.birthday) : customer.birthday != null) return false; // if (phone != null ? !phone.equals(customer.phone) : customer.phone != null) return false; // if (email != null ? !email.equals(customer.email) : customer.email != null) return false; // if (address != null ? !address.equals(customer.address) : customer.address != null) return false; // if (zipcode != null ? !zipcode.equals(customer.zipcode) : customer.zipcode != null) return false; // if (fax != null ? !fax.equals(customer.fax) : customer.fax != null) return false; return true; } // // @Override // public int hashCode() { // int result = customerId; // result = 31 * result + (account != null ? account.hashCode() : 0); // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (password != null ? password.hashCode() : 0); // result = 31 * result + (sex != null ? sex.hashCode() : 0); // result = 31 * result + (birthday != null ? birthday.hashCode() : 0); // result = 31 * result + (phone != null ? phone.hashCode() : 0); // result = 31 * result + (email != null ? email.hashCode() : 0); // result = 31 * result + (address != null ? address.hashCode() : 0); // result = 31 * result + (zipcode != null ? zipcode.hashCode() : 0); // result = 31 * result + (fax != null ? fax.hashCode() : 0); // return result; // } }
f9e0d7e421c9b3805feff4c840e8928ceae4d8d5
455f8692099d40d41eb94b04cba5c9a82602d7f3
/src/main/java/com/airbnb/airpal/sql/jdbi/URIArgumentFactory.java
e8236d0b2a24595fdb6b03aa331b99db4dfd70bd
[ "Apache-2.0" ]
permissive
combineads/airpal
7556a0411f4fcfd252a22b8c8dcd52237c83c0eb
f1cae9f8469181eba8236a44b49e2486622ea617
refs/heads/master
2020-03-14T05:02:38.189792
2018-04-30T09:06:34
2018-04-30T09:06:34
131,455,648
0
2
Apache-2.0
2018-04-29T02:16:43
2018-04-29T01:03:40
Java
UTF-8
Java
false
false
557
java
package com.airbnb.airpal.sql.jdbi; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.Argument; import org.skife.jdbi.v2.tweak.ArgumentFactory; import java.net.URI; public class URIArgumentFactory implements ArgumentFactory<URI> { @Override public boolean accepts(Class<?> expectedType, Object value, StatementContext ctx) { return value instanceof URI; } @Override public Argument build(Class<?> expectedType, URI value, StatementContext ctx) { return new URIArgument(value); } }
7711f0416486bf6d2e04ef454545d71f438ea81c
fd41b64b6cb47a03e10a7c1c2f08af7e9b502963
/src/Service/ICrudDao.java
e686d765ebe7adab574d4bc277e5c7ef8aa00e3c
[]
no_license
DiegoLooo/ProyectoARC-FE
93a0e08ac8c84149794a32f74f62ebf2d9d3e882
7315205ebc491476cf323855f821ed56caa59519
refs/heads/master
2022-12-22T10:36:42.485948
2020-09-23T04:50:12
2020-09-23T04:50:12
293,453,747
0
0
null
null
null
null
UTF-8
Java
false
false
511
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Service; import java.util.List; /** * * @author ARCRODINPC-02 */ public interface ICrudDao<T> { void create(T t) throws Exception; void update(T t) throws Exception; void delete(T t) throws Exception; T findForId(Object t) throws Exception; List<T> readAll() throws Exception; }
83fa59ebb0120bfbf6c69c483150fc1f27357da1
6bf2ed8639e4fa1df2de8cab2dea1470b4f8b32a
/src/main/java/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java
090455090cf8cc98d2c5aed5f885ea0849d13d9c
[]
no_license
xiefan46/OrderSystem
b4661adc427f0d585feaf4166a9a349082a32338
2ebaaecbcebaa1a367945fe57d547eab559d272e
refs/heads/master
2020-07-03T00:33:58.932855
2016-11-19T12:46:52
2016-11-19T12:46:52
74,208,274
1
0
null
null
null
null
UTF-8
Java
false
false
3,789
java
/* * 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.commons.pool2.impl; /** * The interface that defines the information about pooled objects that will be * exposed via JMX. * * NOTE: This interface exists only to define those attributes and methods that * will be made available via JMX. It must not be implemented by clients * as it is subject to change between major, minor and patch version * releases of commons pool. Clients that implement this interface may * not, therefore, be able to upgrade to a new minor or patch release * without requiring code changes. * * @since 2.0 */ public interface DefaultPooledObjectInfoMBean { /** * Obtain the time (using the same basis as * {@link System#currentTimeMillis()}) that pooled object was created. * * @return The creation time for the pooled object */ long getCreateTime(); /** * Obtain the time that pooled object was created. * * @return The creation time for the pooled object formated as * <code>yyyy-MM-dd HH:mm:ss Z</code> */ String getCreateTimeFormatted(); /** * Obtain the time (using the same basis as * {@link System#currentTimeMillis()}) the polled object was last borrowed. * * @return The time the pooled object was last borrowed */ long getLastBorrowTime(); /** * Obtain the time that pooled object was last borrowed. * * @return The last borrowed time for the pooled object formated as * <code>yyyy-MM-dd HH:mm:ss Z</code> */ String getLastBorrowTimeFormatted(); /** * Obtain the stack trace recorded when the pooled object was last borrowed. * * @return The stack trace showing which code last borrowed the pooled * object */ String getLastBorrowTrace(); /** * Obtain the time (using the same basis as * {@link System#currentTimeMillis()})the wrapped object was last returned. * * @return The time the object was last returned */ long getLastReturnTime(); /** * Obtain the time that pooled object was last returned. * * @return The last returned time for the pooled object formated as * <code>yyyy-MM-dd HH:mm:ss Z</code> */ String getLastReturnTimeFormatted(); /** * Obtain the name of the class of the pooled object. * * @return The pooled object's class name * * @see Class#getName() */ String getPooledObjectType(); /** * Provides a String form of the wrapper for debug purposes. The format is * not fixed and may change at any time. * * @return A string representation of the pooled object * * @see Object#toString() */ String getPooledObjectToString(); /** * Get the number of times this object has been borrowed. * @return The number of times this object has been borrowed. * @since 2.1 */ long getBorrowedCount(); }
a760151cef676371680cfaf8505ae15d069e5d49
b7a1592a60c7ff46dc577a0690671f40788db66b
/app/src/main/java/hr/ferit/tumiljanovic/osnoverwima_lv1/MainActivity.java
5cf610c7a948d28803f6556325dda6a5ea26509f
[]
no_license
TeaUmily/ORWIMA
1194c714efed930b420d56b1dba099f6b5b5e41b
133e02d5de32c2a238b38021198afe36679870a0
refs/heads/master
2020-04-08T00:59:02.356183
2018-11-23T20:43:19
2018-11-23T20:43:19
158,876,345
0
0
null
null
null
null
UTF-8
Java
false
false
4,552
java
package hr.ferit.tumiljanovic.osnoverwima_lv1; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.Random; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity implements OnImageClickListener { @BindView(R.id.recycler) RecyclerView recyclerView; @BindView(R.id.description_edittext) EditText etDescription; @BindView(R.id.edit_description_button) Button btnEditDescription; @BindView(R.id.first_person_checkbox) CheckBox cbFirstPerson; @BindView(R.id.secon_person_checkbox) CheckBox cbSecondPerson; @BindView(R.id.third_person_checkbox) CheckBox cbThirdPerson; private RecyclerAdapter adapter = new RecyclerAdapter(); private List<Person> bestPersons = new ArrayList<Person>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.addItemDecoration(new DividerItemDecorator(this)); recyclerView.setAdapter(adapter); adapter.setOnImageClickListener(this); setView(); } private void setView() { bestPersons.add(new Person("Nikola", "Tesla", 1856, 1943, "Nikola Tesla was an engineer known for designing the alternating-current (AC) electric system, which is still the predominant electrical system used across the world today. He also created the \"Tesla coil,\" which is still used in radio technology. ", R.drawable.nikola, "“I do not think you can name many great inventions that have been made by married men. NIKOLA TESLA” ")); bestPersons.add(new Person("Albert", "Einstein", 1879, 1955, "Albert Einstein was a German mathematician and physicist who developed the special and general theories of relativity. In 1921, he won the Nobel Prize for physics for his explanation of the photoelectric effect.", R.drawable.einstein, "The difference between stupidity and genius is that genius has its limits. ALBERT EINSTEIN")); bestPersons.add(new Person("Isaac", "Newton", 1643, 1727, "Isaac Newton was a physicist and mathematician who developed the principles of modern physics, including the laws of motion, and is credited as one of the great minds of the 17th century Scientific Revolution.", R.drawable.isaac, "We build too many walls and not enough bridges. ISAAC NEWTON")); adapter.addItems(bestPersons); } @OnClick(R.id.inspiration_button) void OnInspirationBtnClick() { Random rn = new Random(); int randomNum = rn.nextInt(2); switch (randomNum) { case 0: Toast.makeText(this, bestPersons.get(0).getQuote(), Toast.LENGTH_SHORT).show(); break; case 1: Toast.makeText(this, bestPersons.get(1).getQuote(), Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(this, bestPersons.get(2).getQuote(), Toast.LENGTH_SHORT).show(); break; } } @OnClick(R.id.edit_description_button) void OnEditDescriptionBtnClick() { if (cbFirstPerson.isChecked()) { bestPersons.get(0).setDescription(etDescription.getText().toString()); } if (cbSecondPerson.isChecked()) { bestPersons.get(1).setDescription(etDescription.getText().toString()); } if (cbThirdPerson.isChecked()) { bestPersons.get(2).setDescription(etDescription.getText().toString()); } adapter.addItems(bestPersons); } @Override public void OnClick(int position) { bestPersons.get(position).setImage(0); adapter.addItems(bestPersons); } }
7e82046f47163158fde8c09df353b29683735af1
5a0bfac7ad00c079fe8e0bdf1482f4271c46eeab
/app/src/main/wechat6.5.3/com/tencent/tmassistantsdk/aidl/ITMAssistantDownloadSDKServiceInterface.java
830b5eb1424516faa447a0a1be6338fc2b4a1591
[]
no_license
newtonker/wechat6.5.3
8af53a870a752bb9e3c92ec92a63c1252cb81c10
637a69732afa3a936afc9f4679994b79a9222680
refs/heads/master
2020-04-16T03:32:32.230996
2017-06-15T09:54:10
2017-06-15T09:54:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
15,203
java
package com.tencent.tmassistantsdk.aidl; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; import com.tencent.tmassistantsdk.downloadclient.TMAssistantDownloadTaskInfo; import java.util.Map; public interface ITMAssistantDownloadSDKServiceInterface extends IInterface { public static abstract class Stub extends Binder implements ITMAssistantDownloadSDKServiceInterface { private static final String DESCRIPTOR = "com.tencent.tmassistantsdk.aidl.ITMAssistantDownloadSDKServiceInterface"; static final int TRANSACTION_cancelDownloadTask = 9; static final int TRANSACTION_getDownloadTaskInfo = 6; static final int TRANSACTION_getServiceVersion = 1; static final int TRANSACTION_isAllDownloadFinished = 5; static final int TRANSACTION_pauseDownloadTask = 8; static final int TRANSACTION_registerDownloadTaskCallback = 10; static final int TRANSACTION_setServiceSetingIsDownloadWifiOnly = 3; static final int TRANSACTION_setServiceSetingIsTaskAutoResume = 2; static final int TRANSACTION_setServiceSetingMaxTaskNum = 4; static final int TRANSACTION_startDownloadTask = 7; static final int TRANSACTION_unregisterDownloadTaskCallback = 11; private static class Proxy implements ITMAssistantDownloadSDKServiceInterface { private IBinder mRemote; Proxy(IBinder iBinder) { this.mRemote = iBinder; } public IBinder asBinder() { return this.mRemote; } public String getInterfaceDescriptor() { return Stub.DESCRIPTOR; } public int getServiceVersion() { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); this.mRemote.transact(1, obtain, obtain2, 0); obtain2.readException(); int readInt = obtain2.readInt(); return readInt; } finally { obtain2.recycle(); obtain.recycle(); } } public void setServiceSetingIsTaskAutoResume(boolean z) { int i = 0; Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); if (z) { i = 1; } obtain.writeInt(i); this.mRemote.transact(2, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public void setServiceSetingIsDownloadWifiOnly(boolean z) { int i = 0; Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); if (z) { i = 1; } obtain.writeInt(i); this.mRemote.transact(3, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public void setServiceSetingMaxTaskNum(int i) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); obtain.writeInt(i); this.mRemote.transact(4, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public boolean isAllDownloadFinished() { boolean z = false; Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); this.mRemote.transact(5, obtain, obtain2, 0); obtain2.readException(); if (obtain2.readInt() != 0) { z = true; } obtain2.recycle(); obtain.recycle(); return z; } catch (Throwable th) { obtain2.recycle(); obtain.recycle(); } } public TMAssistantDownloadTaskInfo getDownloadTaskInfo(String str, String str2) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { TMAssistantDownloadTaskInfo tMAssistantDownloadTaskInfo; obtain.writeInterfaceToken(Stub.DESCRIPTOR); obtain.writeString(str); obtain.writeString(str2); this.mRemote.transact(6, obtain, obtain2, 0); obtain2.readException(); if (obtain2.readInt() != 0) { tMAssistantDownloadTaskInfo = (TMAssistantDownloadTaskInfo) TMAssistantDownloadTaskInfo.CREATOR.createFromParcel(obtain2); } else { tMAssistantDownloadTaskInfo = null; } obtain2.recycle(); obtain.recycle(); return tMAssistantDownloadTaskInfo; } catch (Throwable th) { obtain2.recycle(); obtain.recycle(); } } public int startDownloadTask(String str, String str2, int i, String str3, String str4, Map map) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); obtain.writeString(str); obtain.writeString(str2); obtain.writeInt(i); obtain.writeString(str3); obtain.writeString(str4); obtain.writeMap(map); this.mRemote.transact(7, obtain, obtain2, 0); obtain2.readException(); int readInt = obtain2.readInt(); return readInt; } finally { obtain2.recycle(); obtain.recycle(); } } public void pauseDownloadTask(String str, String str2) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); obtain.writeString(str); obtain.writeString(str2); this.mRemote.transact(8, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public void cancelDownloadTask(String str, String str2) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); obtain.writeString(str); obtain.writeString(str2); this.mRemote.transact(9, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public void registerDownloadTaskCallback(String str, ITMAssistantDownloadSDKServiceCallback iTMAssistantDownloadSDKServiceCallback) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); obtain.writeString(str); obtain.writeStrongBinder(iTMAssistantDownloadSDKServiceCallback != null ? iTMAssistantDownloadSDKServiceCallback.asBinder() : null); this.mRemote.transact(10, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public void unregisterDownloadTaskCallback(String str, ITMAssistantDownloadSDKServiceCallback iTMAssistantDownloadSDKServiceCallback) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken(Stub.DESCRIPTOR); obtain.writeString(str); obtain.writeStrongBinder(iTMAssistantDownloadSDKServiceCallback != null ? iTMAssistantDownloadSDKServiceCallback.asBinder() : null); this.mRemote.transact(11, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } } public Stub() { attachInterface(this, DESCRIPTOR); } public static ITMAssistantDownloadSDKServiceInterface asInterface(IBinder iBinder) { if (iBinder == null) { return null; } IInterface queryLocalInterface = iBinder.queryLocalInterface(DESCRIPTOR); if (queryLocalInterface == null || !(queryLocalInterface instanceof ITMAssistantDownloadSDKServiceInterface)) { return new Proxy(iBinder); } return (ITMAssistantDownloadSDKServiceInterface) queryLocalInterface; } public IBinder asBinder() { return this; } public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) { int i3 = 0; boolean z; switch (i) { case 1: parcel.enforceInterface(DESCRIPTOR); i3 = getServiceVersion(); parcel2.writeNoException(); parcel2.writeInt(i3); return true; case 2: parcel.enforceInterface(DESCRIPTOR); if (parcel.readInt() != 0) { z = true; } setServiceSetingIsTaskAutoResume(z); parcel2.writeNoException(); return true; case 3: parcel.enforceInterface(DESCRIPTOR); if (parcel.readInt() != 0) { z = true; } setServiceSetingIsDownloadWifiOnly(z); parcel2.writeNoException(); return true; case 4: parcel.enforceInterface(DESCRIPTOR); setServiceSetingMaxTaskNum(parcel.readInt()); parcel2.writeNoException(); return true; case 5: parcel.enforceInterface(DESCRIPTOR); boolean isAllDownloadFinished = isAllDownloadFinished(); parcel2.writeNoException(); if (isAllDownloadFinished) { i3 = 1; } parcel2.writeInt(i3); return true; case 6: parcel.enforceInterface(DESCRIPTOR); TMAssistantDownloadTaskInfo downloadTaskInfo = getDownloadTaskInfo(parcel.readString(), parcel.readString()); parcel2.writeNoException(); if (downloadTaskInfo != null) { parcel2.writeInt(1); downloadTaskInfo.writeToParcel(parcel2, 1); return true; } parcel2.writeInt(0); return true; case 7: parcel.enforceInterface(DESCRIPTOR); i3 = startDownloadTask(parcel.readString(), parcel.readString(), parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readHashMap(getClass().getClassLoader())); parcel2.writeNoException(); parcel2.writeInt(i3); return true; case 8: parcel.enforceInterface(DESCRIPTOR); pauseDownloadTask(parcel.readString(), parcel.readString()); parcel2.writeNoException(); return true; case 9: parcel.enforceInterface(DESCRIPTOR); cancelDownloadTask(parcel.readString(), parcel.readString()); parcel2.writeNoException(); return true; case 10: parcel.enforceInterface(DESCRIPTOR); registerDownloadTaskCallback(parcel.readString(), com.tencent.tmassistantsdk.aidl.ITMAssistantDownloadSDKServiceCallback.Stub.asInterface(parcel.readStrongBinder())); parcel2.writeNoException(); return true; case 11: parcel.enforceInterface(DESCRIPTOR); unregisterDownloadTaskCallback(parcel.readString(), com.tencent.tmassistantsdk.aidl.ITMAssistantDownloadSDKServiceCallback.Stub.asInterface(parcel.readStrongBinder())); parcel2.writeNoException(); return true; case 1598968902: parcel2.writeString(DESCRIPTOR); return true; default: return super.onTransact(i, parcel, parcel2, i2); } } } void cancelDownloadTask(String str, String str2); TMAssistantDownloadTaskInfo getDownloadTaskInfo(String str, String str2); int getServiceVersion(); boolean isAllDownloadFinished(); void pauseDownloadTask(String str, String str2); void registerDownloadTaskCallback(String str, ITMAssistantDownloadSDKServiceCallback iTMAssistantDownloadSDKServiceCallback); void setServiceSetingIsDownloadWifiOnly(boolean z); void setServiceSetingIsTaskAutoResume(boolean z); void setServiceSetingMaxTaskNum(int i); int startDownloadTask(String str, String str2, int i, String str3, String str4, Map map); void unregisterDownloadTaskCallback(String str, ITMAssistantDownloadSDKServiceCallback iTMAssistantDownloadSDKServiceCallback); }
e99f8ffe0e46b66f0ca5b7edad59102940013f64
85c98acdfd0698092fcb7d7bd54ee1ce28e83163
/src/代理模式/动态代理/code/IUserDao.java
39cd7e076d6fc9d934a9ad450bc68c18c627538c
[]
no_license
743551828/Design-Patterns-Java
195f420c166ae2d6be23d04ea3dba4346f869538
5e2d7653e7ae6c5a43d3510985dcffebf16c7c28
refs/heads/master
2022-12-03T07:39:04.072279
2020-08-25T02:35:27
2020-08-25T02:35:27
285,503,490
0
0
null
null
null
null
UTF-8
Java
false
false
185
java
package 代理模式.动态代理.code; /** * @description: * @author: zhangys * @create: 2020-08-21 14:12 **/ public interface IUserDao { void save(); void update(); }
00e268b933b56b16ae5aae0b7a928afb384c4d5f
757061288c23f75bbe18fedb34cfd90d5e8def50
/ServerSingle.java
309f86d067d357447c06fa41751d461f09b2fe6c
[]
no_license
stono888/JavaSocket
351a6d05dc6dd6efdb109cae0398e9707476473c
3c6dff494c715229e8e9ccfea82fa0cad610fa40
refs/heads/master
2021-01-01T18:41:37.502620
2014-12-03T08:01:49
2014-12-03T08:01:49
null
0
0
null
null
null
null
GB18030
Java
false
false
1,509
java
package com.srie.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; /** * 基于TCP协议的Socket通信,服务器端 * * @author ThinkPad * */ public class ServerSingle { public static void main(String[] args) { try { // 1,创建serverSocket,指定端口,并进行监听 ServerSocket serverSocket = new ServerSocket(8888); // 2,调用accept()方法,开始监听 System.out.println("***服务器即将启动,等待客户端连接***"); Socket socket = serverSocket.accept(); // 3,获取输入流,读取客户端发送的信息 InputStream is = socket.getInputStream();// 字节流 InputStreamReader isr = new InputStreamReader(is);// 字符流 BufferedReader br = new BufferedReader(isr);// 为输入流添加缓冲 String info = null; while ((info = br.readLine()) != null) { System.out.println("我是服务器,客户端说:" + info); } socket.shutdownInput(); // 4,获取输出流 OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("欢迎您!"); pw.flush();//刷新缓存 // 5,关闭资源 pw.close(); os.close(); br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
4b0d65932578a4c41ece04ed7323dc24beb48f2a
b558c99857bcc4ce1ff97c53ebeba0391fdd3967
/src/test/java/com/kazale/pontointeligente/api/repositories/LancamentoRepositoryTest.java
7586d847f5983e47c9f4d90ec5525c9a8a101aee
[ "MIT" ]
permissive
ESKoda/ponto-inteligente-api
1d31bdf909ca35a6c9743c83871c6a2ea4be1679
88bd2d7ecd2372eb76a58318f70510927b61e10a
refs/heads/master
2023-01-29T06:42:13.708285
2020-12-14T17:30:07
2020-12-14T17:30:07
312,087,475
0
0
null
null
null
null
UTF-8
Java
false
false
3,074
java
package com.kazale.pontointeligente.api.repositories; import static org.junit.Assert.assertEquals; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.ActiveProfiles; import com.kazale.pontointeligente.api.entities.Empresa; import com.kazale.pontointeligente.api.entities.Funcionario; import com.kazale.pontointeligente.api.entities.Lancamento; import com.kazale.pontointeligente.api.enums.PerfilEnum; import com.kazale.pontointeligente.api.enums.TipoEnum; import com.kazale.pontointeligente.api.utils.PasswordUtils; @SpringBootTest @ActiveProfiles("test") public class LancamentoRepositoryTest { @Autowired private LancamentoRepository lancamentoRepository; @Autowired private FuncionarioRepository funcionarioRepository; @Autowired private EmpresaRepository empresaRepository; private Long funcionarioId; @BeforeEach public void setUp() throws Exception { Empresa empresa = this.empresaRepository.save(obterDadosEmpresa()); Funcionario funcionario = this.funcionarioRepository.save(obterDadosFuncionario(empresa)); this.funcionarioId = funcionario.getId(); this.lancamentoRepository.save(obterDadosLancamentos(funcionario)); this.lancamentoRepository.save(obterDadosLancamentos(funcionario)); } @AfterEach public void tearDown() throws Exception { this.empresaRepository.deleteAll(); } @Test public void testBuscarLancamentosPorFuncionarioId() { List<Lancamento> lancamentos = this.lancamentoRepository.findByFuncionarioId(funcionarioId); assertEquals(2, lancamentos.size()); } @Test public void testBuscarLancamentosPorFuncionarioIdPaginado() { Page<Lancamento> lancamentos = this.lancamentoRepository.findByFuncionarioId(funcionarioId, PageRequest.of(0, 10)); assertEquals(2, lancamentos.getTotalElements()); } private Lancamento obterDadosLancamentos(Funcionario funcionario) { Lancamento lancameto = new Lancamento(); lancameto.setData(new Date()); lancameto.setTipo(TipoEnum.INICIO_ALMOCO); lancameto.setFuncionario(funcionario); return lancameto; } private Funcionario obterDadosFuncionario(Empresa empresa) throws NoSuchAlgorithmException { Funcionario funcionario = new Funcionario(); funcionario.setNome("Fulano de Tal"); funcionario.setPerfil(PerfilEnum.ROLE_USUARIO); funcionario.setSenha(PasswordUtils.gerarBCrypt("123456")); funcionario.setCpf("24291173474"); funcionario.setEmail("[email protected]"); funcionario.setEmpresa(empresa); return funcionario; } private Empresa obterDadosEmpresa() { Empresa empresa = new Empresa(); empresa.setRazaoSocial("Empresa de exemplo"); empresa.setCnpj("51463645000100"); return empresa; } }
7537bf7035609d5b542ac068b1f3d535cfb767f5
882d3591752a93792bd8c734dd91b1e5439c5ffe
/android/QNLiveShow_Anchor/liveshowApp/src/main/java/com/qpidnetwork/anchor/framework/widget/barlibrary/BarParams.java
ddf735a7137b0a5d6f98950e0c42a5fc24d1e162
[]
no_license
KingsleyYau/LiveClient
f4d4d2ae23cbad565668b1c4d9cd849ea5ca2231
cdd2694ddb4f1933bef40c5da3cc7d1de8249ae2
refs/heads/master
2022-10-15T13:01:57.566157
2022-09-22T07:37:05
2022-09-22T07:37:05
93,734,517
27
14
null
null
null
null
UTF-8
Java
false
false
3,995
java
package com.qpidnetwork.anchor.framework.widget.barlibrary; import android.database.ContentObserver; import android.graphics.Color; import android.support.annotation.ColorInt; import android.support.annotation.FloatRange; import android.view.View; import android.view.WindowManager; import java.util.HashMap; import java.util.Map; /** * 沉浸式参数信息 * Created by geyifeng on 2017/5/9. */ public class BarParams implements Cloneable { @ColorInt public int statusBarColor = Color.TRANSPARENT; //状态栏颜色 @ColorInt public int navigationBarColor = Color.BLACK; //导航栏颜色 @FloatRange(from = 0f, to = 1f) public float statusBarAlpha = 0.0f; //状态栏透明度 @FloatRange(from = 0f, to = 1f) float navigationBarAlpha = 0.0f; //导航栏透明度 public boolean fullScreen = false; //有导航栏的情况,全屏显示 public boolean fullScreenTemp = fullScreen; public BarHide barHide = BarHide.FLAG_SHOW_BAR; //隐藏Bar public boolean darkFont = false; //状态栏字体深色与亮色标志位 public boolean statusBarFlag = true; //是否可以修改状态栏颜色 @ColorInt public int statusBarColorTransform = Color.BLACK; //状态栏变换后的颜色 @ColorInt public int navigationBarColorTransform = Color.BLACK; //导航栏变换后的颜色 public Map<View, Map<Integer, Integer>> viewMap = new HashMap<>(); //支持view变色 @FloatRange(from = 0f, to = 1f) public float viewAlpha = 0.0f; public boolean fits = false; //解决标题栏与状态栏重叠问题 @ColorInt public int statusBarColorContentView = Color.TRANSPARENT; @ColorInt public int statusBarColorContentViewTransform = Color.BLACK; @FloatRange(from = 0f, to = 1f) public float statusBarContentViewAlpha = 0.0f; public int navigationBarColorTemp = navigationBarColor; public View statusBarView; //4.4自定义一个状态栏 public View navigationBarView; //4.4自定义一个导航栏 public View statusBarViewByHeight; //解决标题栏与状态栏重叠问题 @ColorInt public int flymeOSStatusBarFontColor; //flymeOS状态栏字体变色 public boolean isSupportActionBar = false; //结合actionBar使用 public View titleBarView; //标题栏view public int titleBarHeight; //标题栏的高度 public int titleBarPaddingTopHeight; //标题栏的paddingTop高度 public View titleBarViewMarginTop; //使用margin来修正标题栏位置 public boolean titleBarViewMarginTopFlag = false; //标题栏标识,保证只执行一次 public boolean keyboardEnable = false; //解决软键盘与输入框冲突问题 public int keyboardMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE; //软键盘属性 public boolean navigationBarEnable = true; //是否能修改导航栏颜色 public boolean navigationBarWithKitkatEnable = true; //是否能修改4.4手机导航栏颜色 @Deprecated public boolean fixMarginAtBottom = false; //解决出现底部多余导航栏高度,默认为false public boolean systemWindows = false; //也没是否使用fitsSystemWindows属性 public KeyboardPatch keyboardPatch; //软键盘监听类 public OnKeyboardListener onKeyboardListener; //软键盘监听类 public ContentObserver navigationStatusObserver; //emui3.1监听器 @Override protected BarParams clone() { BarParams barParams = null; try { barParams = (BarParams) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return barParams; } }
eb287dc482bfff84d38567b3e7471ba5391957d7
9a13de8ba2517924f09bbc8b7bc8e40d3225f598
/src/main/java/com/tt/teach/dao/StudentDao.java
423fe78ffe9d39068540ea4ce8ed6032eceb3b79
[]
no_license
songce1/teach
f44ab07147b66057ad1adaff0dc31a46ae0ffdc1
ea31816b030999f186bc3930fec26fa6438a2434
refs/heads/master
2020-04-12T10:32:54.933012
2018-12-19T12:17:30
2018-12-19T12:17:30
162,432,994
0
0
null
null
null
null
UTF-8
Java
false
false
481
java
package com.tt.teach.dao; import com.tt.teach.pojo.Student; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface StudentDao { @Select("select * from student where studentNo=#{studentNo} and loginPwd=#{loginPwd}") Student dologin(Student student); @Select("select * from student") List<Student> getStudentList(); }
9d062adcbe39a14cf2856e17b07ad762ba226074
b5cfe0f0ea89c2f4d4ba3a662fc178736fab5636
/Printing numbers in pyramid pattern/Main.java
bacbd249719a9e4e47d118e82ddecfefc02bacd8
[]
no_license
diksha9023/Playground
568e7fcd4b6943c125b80dca622d5a0e357f5aa3
cfb113b982d9faff794b929fedeeab9b061b4823
refs/heads/master
2020-04-14T17:00:24.648100
2019-05-02T09:59:10
2019-05-02T09:59:10
163,967,297
0
0
null
null
null
null
UTF-8
Java
false
false
483
java
import java.util.Scanner; class Main{ public static void main (String[] args){ Scanner scan = new Scanner(System.in); int n =scan.nextInt(); int val=1; for(int i=1;i<=n;i++) { for(int space =1;space<=(n-i);space++) { System.out.print(" "); } for(int j=1;j<=i;j++) { System.out.print(val+" "); val++; } System.out.print("\n"); } } }
6c6d44fda9fdb70ce1c2c2220662443a5740a879
05078c9584083f3f0e4a861894893ffe50dd54e8
/Yok/app/src/main/java/com/example/zuhal/yok/Tab3.java
4eedbaa86de37d398c4a1b7d049ae1db9ec3a9d7
[]
no_license
zuhalhur/UniversityApp
a1fec96f5d47cc2a17878177e179b104d5b77cfe
c64882e086d3be0dbbd983ac8394668b87e6efb1
refs/heads/master
2020-09-16T06:58:05.755022
2017-06-15T22:43:51
2017-06-15T22:43:51
94,484,363
0
0
null
null
null
null
UTF-8
Java
false
false
4,279
java
package com.example.zuhal.yok; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.DisplayMetrics; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class Tab3 extends Fragment { ListView newsList; ArrayAdapter<String> adapter1; ArrayList<String> news; ArrayList<String>html; LinearLayout haber; public Tab3() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view= inflater.inflate(R.layout.fragment_tab3, container, false); news =new ArrayList<String>(); newsList=(ListView)view.findViewById(R.id.newsList); haber=(LinearLayout)view.findViewById(R.id.haber); html=new ArrayList<String>(); new News().execute(); newsList.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent=new Intent(getActivity(),OpenUrl.class); intent.putExtra("web","http://ybu.edu.tr/muhendislik/bilgisayar/"+html.get(position)); startActivity(intent); } }); haber.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getActivity(),OpenUrl.class); intent.putExtra("web","http://www.ybu.edu.tr/muhendislik/bilgisayar/content_list-314-haberler.html"); startActivity(intent); } }); return view; } private class News extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { try { // Connect to the web site Document doc; Elements element; doc = Jsoup.connect("http://ybu.edu.tr/muhendislik/bilgisayar/").get(); element = doc.select("div.cnContent"); element =element.select("div.cncItem"); for( int i=0;i<element.size();i++){ news.add(element.get(i).text()); Elements element3 = element.get(i).select("span > a"); String url = element3.attr("href"); html.add(url); } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); final int height = metrics.heightPixels; adapter1 = new ArrayAdapter<String>(getActivity(),R.layout.text_layout, news){ @Override public View getView(int position, View convertView, ViewGroup parent){ ViewGroup.LayoutParams layoutparams; View view = super.getView(position,convertView,parent); layoutparams = view.getLayoutParams(); //Define your height here. layoutparams.height = height/(news.size()+1); view.setLayoutParams(layoutparams); return view; } }; newsList.setAdapter(adapter1); } } }
69246fa6d851c5349dd87f82a0a4c288d2ffea9a
e0f91ceb995d7876ab40bc549d1f0ae1257ee410
/dto/src/main/java/kr/co/theplay/zzz/ZUserSingleResDto.java
f7ebd20d42f884d8607e200fbffcf189c684118b
[]
no_license
Hae-Riri/alcohol
41b41905f6959efa6d01fbd13dfb4067bd83f975
1f3816deb0687bb2e80116acd8e065362e15b955
refs/heads/master
2023-03-17T16:51:11.278602
2021-02-22T06:28:10
2021-02-22T06:28:10
337,103,572
0
0
null
null
null
null
UTF-8
Java
false
false
638
java
package kr.co.theplay.zzz; import io.swagger.annotations.ApiModelProperty; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor public class ZUserSingleResDto { @ApiModelProperty(value = "uid", dataType = "String", required = true, example = "[email protected]") private String uid; @ApiModelProperty(value = "phoneNumber", dataType = "String", required = true, example = "010-5768-5933") private String phoneNumber; @Builder public ZUserSingleResDto(String uid, String phoneNumber){ this.uid = uid; this.phoneNumber = phoneNumber; } }
e7c3099e2c804082d44ae1c7b7176beb63e8a011
0ef389a004d0f36de8f24bdc76cd76122a9c0638
/easymock/src/main/java/com/tsingsoft/android/util/PointLoadHandleUtil.java
694cbc2bbf3a8806af2d08f918a036c41eb57723
[]
no_license
songjz2011/water
8d677b33641efb3da16c9fad176fc1a66a021119
434732385f401ce7c239495ebe79c0d141e27723
refs/heads/master
2016-09-06T08:40:17.673896
2014-12-09T06:45:20
2014-12-09T06:45:20
11,657,188
1
2
null
null
null
null
UTF-8
Java
false
false
3,366
java
package com.tsingsoft.android.util; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import com.tsingsoft.android.common.SysConstant; /** * <pre> * 时刻点值处理的工具类 * </pre> * * @author songjz * @time 2013-12-10 */ public class PointLoadHandleUtil { /** * <pre> * 去除null(以空字串替代),若不是null,则保留两位小数 * 并且时刻点的格式T0000转换成00:00 * * <pre> * @param pointValueMap * @return */ public static TreeMap<String, Object> killNullAndFormatKeyValue(Map<String, ?> pointValueMap) { Map<String, ?> valueMap = pointValueMap; if (valueMap == null || valueMap.isEmpty()) { valueMap = buildEmpty96PointValueMap(); } TreeMap<String, Object> result = new TreeMap<String, Object>(); NumberFormat format = NumberUtil.getNumberFormat(); for (Entry<String, ?> entry : valueMap.entrySet()) { String key = entry.getKey(); result.put(convertPointTimeKey(key), numberFormatValue(entry.getValue(), format)); } return result; } /** * 只去除null(以空字串替代),并且时刻点的格式T0000转换成00:00 * * @param pointValueMap * @return */ public static TreeMap<String, Object> killNullAndFormatKey(Map<String, Object> pointValueMap) { TreeMap<String, Object> result = new TreeMap<String, Object>(); if (pointValueMap == null || pointValueMap.isEmpty()) { return result; } for (Entry<String, Object> entry : pointValueMap.entrySet()) { String key = entry.getKey(); result.put(convertPointTimeKey(key), killEmpty(entry.getValue())); } return result; } /** * 构造空字串的96点负荷数据map */ private static TreeMap<String, Object> buildEmpty96PointValueMap() { String[] points = SysConstant.DAY_LOAD_CURVE_96COLUMN; TreeMap<String, Object> result = new TreeMap<String, Object>(); for (String point : points) { result.put(point, ""); } return result; } /** * 构造空字串的96点负荷数据list */ public static List<String> buildEmpty96PointValueList() { String[] points = SysConstant.DAY_LOAD_CURVE_96COLUMN; List<String> result = new ArrayList<String>(); for (int i = 0; i < points.length; i++) { result.add(""); } return result; } /** * 格式化数据 * * @param value * @param format * @return */ public static Object numberFormatValue(Object value, NumberFormat format) { if (StringUtil.isEmpty(value)) { return ""; } try { return format.format(Double.valueOf(value.toString().trim())); } catch (RuntimeException e) { e.printStackTrace(); } return value; } /** * 去除空值,若是空则返回“”,不是则返回原始值 * * @param obj * @return */ private static Object killEmpty(Object obj) { if (StringUtil.isEmpty(obj)) { return ""; } return obj; } /** * 转换时刻点,若是T1000,转成10:00 * * @param pointTime * @return */ public static String convertPointTimeKey(String pointTime) { if (!pointTime.startsWith("T")) { return pointTime; } return pointTime.substring(1, 3) + ":" + pointTime.substring(3); } }
311ede7e8550da6e573b21b68084ef2d6ef5fa67
e4a21bee21efb3b79b7767980b2f07c49957ca86
/step 15/NewReleasePrice.java
43085f89930a6df65662c136e5e0e7572ab98700
[]
no_license
bladefo/FinalRefactoring
6fb5da93889b647d0ed1c3785ca08873e49c8975
cc78ca43015e32d87e52e8d1cd7589a5a8923b38
refs/heads/master
2020-04-11T20:18:53.719127
2018-12-17T07:56:47
2018-12-17T07:56:47
162,066,169
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package bad.robot.refactoring.chapter1; public class NewReleasePrice extends Price{ @Override public int getPriceCode(){ return Movie.NEW_RELEASE; } @Override public double getCharge(int daysRented){ return daysRented*3; } @Override public int getRentalPts(int daysRented){ if (daysRented > 1) return 2; return 1; } }
bb1c7a0f179efe709f0f8e5d6fb77adde6b86f50
5aacddb3f25ff4b7231f0be38f56056fc2063b25
/Etudiant/src/com/formation/etudiant/Modifier.java
33cd7a341255dc1e77cbee87d8575e5071f8132f
[]
no_license
rihi001/WorkAndroid
ea54979931094629b2a4350b724ddc017523dbc7
759c74f486a6a324ffa4eb6c1884bb7d2544801e
refs/heads/master
2021-01-10T05:11:49.792234
2016-02-03T23:52:12
2016-02-03T23:52:12
50,382,708
2
0
null
null
null
null
UTF-8
Java
false
false
967
java
package com.formation.etudiant; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class Modifier extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_modifier); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.modifier, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
83db697dc6e10ab77e5694d5b2dc0cb4650fdff7
be1faf8675ebf3ca53e46b97b08935a4c2ea4426
/Sannad_App/app/src/main/java/com/Sannad/SannadApp/TrackerService.java
6fde1d9ebb175d435c9ead1a03ffeaa8dfc3d60c
[]
no_license
tareksoliman26072020/sannad
fe489a69ce57b3506dd7a70c94ebcd1f8daf90ec
25f268152942bd296ab60b3c6c1fc32b79b3008a
refs/heads/main
2023-04-06T01:33:42.980256
2021-05-04T16:07:15
2021-05-04T16:07:15
364,309,989
0
0
null
null
null
null
UTF-8
Java
false
false
3,985
java
package com.Sannad.SannadApp; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.Looper; import android.util.Log; import android.widget.Toast; import androidx.core.app.ActivityCompat; import com.Sannad.SannadApp.Activity.AccountSettingActivity; import com.Sannad.SannadApp.Activity.MainActivity; import pub.devrel.easypermissions.EasyPermissions; /**This class is for the tracking of the location.*/ public class TrackerService extends Service implements LocationListener { /**Latitude.*/ private Double latitude; /**Longitude.*/ private Double longitude; /**The context (activity).*/ private Context context; /**The Location.*/ private Location location; /**The Location manager.*/ private LocationManager locationManager; /**Required a empty constructor.*/ public TrackerService() {} public TrackerService(Context context) { this.context = context; location = locate(); } /**Determine the location.*/ @SuppressLint("MissingPermission") private Location locate() { if(EasyPermissions.hasPermissions(context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,})) { Location location = null; locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE); boolean isGPSActive = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); boolean isNetActive = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); Log.d("Reeeeeeee", "" + isGPSActive + " " + isNetActive + " " + locationManager + "111"); if (isNetActive) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 20, this); location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); Log.d("Reeeeeeee", "" + isGPSActive + " " + isNetActive + " " + locationManager + "222"); } else if (isGPSActive) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 20, this); location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.d("Reeeeeeee", "" + isGPSActive + " " + isNetActive + " " + locationManager + "333"); } if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } }else{ Toast.makeText(context, "Your address was not located, you need to allow access location permission.", Toast.LENGTH_LONG).show(); } return location; } /**Stop updating.*/ public void stopUpdates(){ if(locationManager != null) locationManager.removeUpdates(this); } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }
79ad3fb0efaf954dbdd427d2d9f764ac67ff6418
5d2240448ec30daf6164661e1f9984e54f403417
/repositories/impl/src/test/java/com/alexkbit/iblog/repository/RepositoryTestApplication.java
804749dc63de3877859b18ff34a5b600446fd1f4
[]
no_license
gestatech/iblog
bb3003243bcdb5f370576110c115f621e3ee06c1
ab46b2011af91eff0bc2c955e150a330280d73a3
refs/heads/master
2021-05-05T16:20:05.311591
2017-04-15T12:39:11
2017-04-15T12:39:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
776
java
/* * Copyright (c) T-Systems International, 2016 * The copyright of the computer program herein is the property of * T-Systems International. The program may be used and/or copied * only with the written permission of T-Systems International or in * accordance with the terms and conditions stipulated in the * agreement/contract under which the program has been supplied. * * Created by dKobylki on 6/28/16 4:34 PM. */ package com.alexkbit.iblog.repository; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * Spring boot application for test repositories */ @SpringBootApplication @ComponentScan(basePackages = "com.alexkbit.iblog") public class RepositoryTestApplication { }
f0cacfa9eb4934f9f07dc19fd36a6c28a9b7c300
74c4c831c2411e02ec7212dce6a7a993cd0bc59d
/TankArenaTalk/src/main/java/com/tiem625/tankarenatalk/utils/GUIScene.java
5e472320c5b644351cdad7067433e97965f43438
[]
no_license
Anatolij-Grigorjev/TankArenaTalk
104f9e516d2e254c39ae066449b48195a516395e
24441c1d887b15b3bfe08cc2c6c9faa5c30f30a0
refs/heads/master
2020-12-30T10:23:46.741158
2017-08-17T06:55:11
2017-08-17T06:55:11
98,869,319
0
0
null
null
null
null
UTF-8
Java
false
false
1,387
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tiem625.tankarenatalk.utils; import com.tiem625.tankarenatalk.constants.GUIScenes; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import lombok.Getter; /** * * @author Anatolij */ public class GUIScene<T> { @Getter private final Scene scene; @Getter private final T controller; private final List<String> styleSheets; private GUIScene(String fxmlPath, Class<T> controllerClazz, List<String> stylesPaths) throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlPath)); scene = new Scene(loader.load()); controller = (T) loader.getController(); styleSheets = new ArrayList<>(); styleSheets.add("/styles/Common.css"); styleSheets.addAll(stylesPaths); scene.getStylesheets().addAll(styleSheets); } public static <T> GUIScene<T> initScene(GUIScenes scene) throws IOException { return new GUIScene<>( scene.getScenePath(), (Class<T>) scene.getControllerClass(), scene.getStylesheetPaths()); } }
cac8e0d47272b5bbf8f43a5909c81df278ad8522
a5d01febfd8d45a61f815b6f5ed447e25fad4959
/Source Code/5.27.0/sources/com/google/android/youtube/player/internal/e.java
b76488ca856ffbdec2301228eae023d34e363939
[]
no_license
kkagill/Decompiler-IQ-Option
7fe5911f90ed2490687f5d216cb2940f07b57194
c2a9dbbe79a959aa1ab8bb7a89c735e8f9dbc5a6
refs/heads/master
2020-09-14T20:44:49.115289
2019-11-04T06:58:55
2019-11-04T06:58:55
223,236,327
1
0
null
2019-11-21T18:17:17
2019-11-21T18:17:16
null
UTF-8
Java
false
false
2,043
java
package com.google.android.youtube.player.internal; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; public interface e extends IInterface { public static abstract class a extends Binder implements e { private static class a implements e { private IBinder Rr; a(IBinder iBinder) { this.Rr = iBinder; } public final void a(String str, IBinder iBinder) { Parcel obtain = Parcel.obtain(); Parcel obtain2 = Parcel.obtain(); try { obtain.writeInterfaceToken("com.google.android.youtube.player.internal.IConnectionCallbacks"); obtain.writeString(str); obtain.writeStrongBinder(iBinder); this.Rr.transact(1, obtain, obtain2, 0); obtain2.readException(); } finally { obtain2.recycle(); obtain.recycle(); } } public final IBinder asBinder() { return this.Rr; } } public a() { attachInterface(this, "com.google.android.youtube.player.internal.IConnectionCallbacks"); } public IBinder asBinder() { return this; } public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) { String str = "com.google.android.youtube.player.internal.IConnectionCallbacks"; if (i == 1) { parcel.enforceInterface(str); a(parcel.readString(), parcel.readStrongBinder()); parcel2.writeNoException(); return true; } else if (i != 1598968902) { return super.onTransact(i, parcel, parcel2, i2); } else { parcel2.writeString(str); return true; } } } void a(String str, IBinder iBinder); }
62622dd06bcce9e7ff3b729f4093628176aab41c
f27dc411ee142d5d299661a6194ba4c2a7506a30
/src/main/java/rest/clone/domain/model/greeting/GreetId.java
b6a19e9a469c72dce4dff5939f4f4a4d2e05de01
[]
no_license
ymzkjpx/restclone
62679903ae981ea4856b485b4538de565fbb79fa
4098843b9fd6bc58308714e796cd850374948550
refs/heads/main
2023-07-04T20:20:55.464998
2021-08-29T00:19:19
2021-08-29T00:19:19
398,527,415
0
0
null
2021-08-25T14:57:29
2021-08-21T10:19:41
Java
UTF-8
Java
false
false
526
java
package rest.clone.domain.model.greeting; public class GreetId { Integer value; @Deprecated GreetId() {} public GreetId(Integer value) { this.value = value; } public GreetId(String textValue) { this.value = Integer.parseInt(textValue); } public Integer value() { return value; } public String format() { return Integer.toString(value); } @Override public String toString() { return "GreetId{" + "value=" + value + '}'; } }
ced636438245cc823b97cec71e83de515b572ee6
4b832b7837f4878d6a55310e08e040f073f467fe
/src/main/java/rtc/signaling/SignalingServerApplication.java
461d86eaabc17a6244336cda7d102f4117f6ab5c
[ "MIT" ]
permissive
pcimcioch/rtc-signal-server
59f7f29a8471c918ed0320a08f387af565e47152
d9e535d12576fd406ef64c2837f2e154b8c304ed
refs/heads/master
2020-05-22T10:03:12.673994
2019-05-13T21:49:40
2019-05-13T21:49:40
186,302,543
0
2
null
null
null
null
UTF-8
Java
false
false
700
java
package rtc.signaling; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class SignalingServerApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SignalingServerApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SignalingServerApplication.class); } }
5b38ff0c14a045887a63e8e3d9ccd5a926d6d787
2af5fb9f6d063a4dc2aee533e0b57d4aba88e47f
/gmall-user/src/main/java/com/fate/gmall/user/controller/UserController.java
afdf08c9c60506918229bb8a60f8037bcb612760
[]
no_license
fate-xjc/gmall0105
2a8170f706d7b9d67a2bcade43247de87a0b3427
52b69e47d304711e80564884b2c8bf5925a16f1b
refs/heads/master
2022-09-12T12:30:55.608212
2020-04-09T09:52:51
2020-04-09T09:52:51
239,666,426
0
0
null
2022-09-01T23:20:32
2020-02-11T03:20:54
CSS
UTF-8
Java
false
false
1,204
java
package com.fate.gmall.user.controller; import com.fate.gmall.bean.UmsMember; import com.fate.gmall.bean.UmsMemberReceiveAddress; import com.fate.gmall.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller public class UserController { @Autowired UserService userService; @RequestMapping("getAllUser") @ResponseBody public List<UmsMember> getAllUser(){ List<UmsMember> umsMembers= userService.getAllUser(); return umsMembers; } @RequestMapping("getReceiveAddressByMemberId") public List<UmsMemberReceiveAddress> getReceiveAddressByMemberId(@RequestBody String memberId){ List<UmsMemberReceiveAddress> umsMemberReceiveAddress= userService.getReceiveAddressByMemberId(memberId); return umsMemberReceiveAddress; } @RequestMapping("index") @ResponseBody public String index(){ return "hello user!"; } }
8686d69c6669e14d1f0e7b53a8af837d679fa423
3ccea1c2e0f186dae42f1808201f8eda9f8bd826
/src/test/java/steps/SearchResultsSteps.java
a11554c17f349d92eb48c9bbe2c15b5238a8d45d
[]
no_license
hubs0n/automationOtoApp
446f71e3eef48aa47e0235a1fd0e72bdefeb875d
1b5676970307562d4228ad23f5ce931d45d6f6d1
refs/heads/master
2020-12-04T08:35:35.147325
2020-01-04T02:24:30
2020-01-04T02:24:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
759
java
package steps; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidElement; import pages.SearchResultsPages; import utilities.AndroidModel; import java.util.List; public class SearchResultsSteps { public static int checkResulst() { int res = 0; List<MobileElement> results = null; try { AndroidElement list = AndroidModel.findElementBy(SearchResultsPages.searchListResults); results = list.findElements(SearchResultsPages.result); res = results.size(); } catch (Exception e) { } if (results == null) { AndroidModel.findElementBy(SearchResultsPages.emptyList); res = 0; } return res; } }
52b6842a7e87cf2925001f872d73f0b9b6567b87
1052c529bace6d587bf349b7d56be715e52ce311
/array_2d_minmaxfinder.java
0ede2cd073c9eea9d4dcd37d2f7dbca04ef89ab3
[]
no_license
KrishivVora/Main-Program-Archive
89bf9f7affe571c208706bf9ced75b673ab15d95
5ee65e0a1d244c0939df2242acab0c03d2058724
refs/heads/master
2020-04-11T11:03:12.578407
2018-12-15T02:50:46
2018-12-15T02:50:46
161,735,533
0
0
null
null
null
null
UTF-8
Java
false
false
2,838
java
import java.util.*; public class array_2d_minmaxfinder { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("\fEnter dimensions of array, first rows then columns. (size between 2 and 20)"); int M=sc.nextInt(); int N=sc.nextInt(); int A[][]=new int[M][N]; System.out.println("Enter elements of array matrix, row by row."); for(int i=0; i<M; i++) //2d array input { for(int j=0; j<N; j++) { A[i][j]=sc.nextInt(); } } System.out.println("\fYour entered array is:"); for(int i=0; i<M; i++) //prints original 2d array { for(int j=0; j<N; j++) { System.out.print(A[i][j]+" "); } System.out.println(); } int min=A[0][0]; int max=A[0][0]; int loc1=0, loc2=0, loc3=0, loc4=0; for(int i=0; i<M; i++) //finds min and max along with position in original 2d array and prints { for(int j=0; j<N; j++) { if(A[i][j]<min) { min=A[i][j]; loc1=i+1; loc2=j+1; } if(A[i][j]>max) { max=A[i][j]; loc3=i+1; loc4=j+1; } } } System.out.println("Minimum value in the array is: "+min); System.out.println("It is in Row "+loc1+" and Column "+loc2); System.out.println("Maximum value in the array is: "+max); System.out.println("It is in Row "+loc3+" and Column "+loc4); int O=M*N; int B[]=new int[O]; int cnt=0; for(int i=0; i<M; i++) //2d array transfer to 1d array { for(int j=0; j<N; j++, cnt++) { B[cnt]=A[i][j]; } } int pos1, pos2, temp; for(int a=O; a>=0; a--) //1d array sorted { for(int j=1; j<a; j++) { pos1=B[j]; pos2=B[j-1]; if(pos1<pos2) { temp=B[j]; B[j]=B[j-1]; B[j-1]=temp; } } } cnt=0; System.out.println(); System.out.println("The sorted array is:"); for(int i=0; i<M; i++) //1d array transferred back to 2d array and PRINTS { for(int j=0; j<N; j++, cnt++) { A[i][j]=B[cnt]; System.out.print(A[i][j]+" "); } System.out.println(); } } }
d3c31011fa38cd558aaf1eed6d4296ffcfb5c82e
8b37a6fe0a647f7b2dea197cb9c2456faa09e408
/src/main/java/com/makun/proxy/Test.java
626086be0bfda4ac76387f11a94a34e643e88297
[]
no_license
MichaelDady/java_base_knowledge
9212e4eee66a3362012a84acdca089a3b6957adf
a80dda3766baa6b2d944786eb8392d0cdad8cb34
refs/heads/master
2022-12-22T14:45:45.721196
2020-02-03T14:10:01
2020-02-03T14:10:01
205,149,494
0
0
null
2022-12-16T04:32:38
2019-08-29T11:36:50
Java
UTF-8
Java
false
false
189
java
package com.makun.proxy; /** * @author Created by makun * @Date 2019-09-19 */ public class Test { public static void main(String[] args) { System.out.println(1<<2); } }
2700de052b4e375362f131da295752eeb44c36a2
9d1d28d62367d3063c9cb9d8b978c3f78f7d4f99
/src/gov/nist/sip/instantmessaging/ConfigurationFrame.java
0f16787c5ec7841e128cc5a3aac384953df15df4
[]
no_license
eliasbaixas/chat-p2p-sip
a00192db973d0b1e54d64fb8007d286e616bbdb1
a9c609fa855c1190a6a6b6ee395a9aeee4d6c5f2
refs/heads/master
2021-01-22T05:15:28.061664
2008-10-07T17:53:18
2008-10-07T17:53:18
60,503
6
2
null
null
null
null
UTF-8
Java
false
false
14,379
java
/* * * * Created on April 1, 2002, 3:08 PM */ package gov.nist.sip.instantmessaging; import javax.swing.*; import javax.swing.border.*; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import gov.nist.sip.instantmessaging.presence.*; /** * * @author deruelle * @version 1.0 */ public class ConfigurationFrame extends JFrame { protected JLabel outboundProxyAddressLabel; protected JLabel outboundProxyPortLabel; protected JLabel registrarAddressLabel; protected JLabel registrarPortLabel; protected JLabel imAddressLabel; protected JLabel imPortLabel; protected JLabel imProtocolLabel; protected JLabel outputFileLabel; protected JLabel buddiesFileLabel; protected JLabel authenticationFileLabel; protected JLabel defaultRouterLabel; protected JTextField outboundProxyAddressTextField; protected JTextField outboundProxyPortTextField; protected JTextField registrarAddressTextField; protected JTextField registrarPortTextField; protected JTextField imAddressTextField; protected JTextField imPortTextField; protected JTextField imProtocolTextField; protected JTextField outputFileTextField; protected JTextField buddiesFileTextField; protected JTextField authenticationFileTextField; protected JTextField defaultRouterTextField; protected JPanel firstPanel; protected JPanel thirdPanel; protected JButton submitButton; protected InstantMessagingGUI imGUI; // All for the container: public Color containerBackGroundColor = new Color(204, 204, 204); // All for the labels: public Border labelBorder = new EtchedBorder(EtchedBorder.RAISED); public Color labelBackGroundColor = new Color(217, 221, 221); // All for the TextField public Color textBackGroundColor = Color.white; // All for the Button public Border buttonBorder = new BevelBorder(BevelBorder.RAISED); public Color buttonBackGroundColor = new Color(186, 175, 175); private static Logger logger = Logger.getLogger(ConfigurationFrame.class); /** Creates new form SIPHeadersParametersFrame */ public ConfigurationFrame(InstantMessagingGUI imGUI, String title) { super(title); this.imGUI = imGUI; initComponents(); } public String getRouterPath() { return defaultRouterTextField.getText(); } public String getOutboundProxyAddress() { return outboundProxyAddressTextField.getText(); } public String getOutboundProxyPort() { return outboundProxyPortTextField.getText(); } public String getRegistrarAddress() { return registrarAddressTextField.getText(); } public String getRegistrarPort() { return registrarPortTextField.getText(); } public String getIMAddress() { return imAddressTextField.getText(); } public String getIMPort() { return imPortTextField.getText(); } public String getIMProtocol() { return imProtocolTextField.getText(); } public String getOutputFile() { return outputFileTextField.getText(); } public void hideFrame() { this.hide(); } public void blockProperties() { outboundProxyAddressTextField.setEditable(false); outboundProxyAddressTextField.setBackground(Color.lightGray); outboundProxyPortTextField.setEditable(false); outboundProxyPortTextField.setBackground(Color.lightGray); registrarAddressTextField.setEditable(false); registrarAddressTextField.setBackground(Color.lightGray); registrarPortTextField.setEditable(false); registrarPortTextField.setBackground(Color.lightGray); imAddressTextField.setEditable(false); imAddressTextField.setBackground(Color.lightGray); imPortTextField.setEditable(false); imPortTextField.setBackground(Color.lightGray); imProtocolTextField.setEditable(false); imProtocolTextField.setBackground(Color.lightGray); outputFileTextField.setEditable(false); outputFileTextField.setBackground(Color.lightGray); buddiesFileTextField.setEditable(false); buddiesFileTextField.setBackground(Color.lightGray); authenticationFileTextField.setEditable(false); authenticationFileTextField.setBackground(Color.lightGray); defaultRouterTextField.setEditable(false); defaultRouterTextField.setBackground(Color.lightGray); } public void unblockProperties() { outboundProxyAddressTextField.setEditable(true); outboundProxyAddressTextField.setBackground(Color.white); outboundProxyPortTextField.setEditable(true); outboundProxyPortTextField.setBackground(Color.white); registrarAddressTextField.setEditable(true); registrarAddressTextField.setBackground(Color.white); registrarPortTextField.setEditable(true); registrarPortTextField.setBackground(Color.white); imAddressTextField.setEditable(true); imAddressTextField.setBackground(Color.white); imPortTextField.setEditable(true); imPortTextField.setBackground(Color.white); imProtocolTextField.setEditable(true); imProtocolTextField.setBackground(Color.white); outputFileTextField.setEditable(true); outputFileTextField.setBackground(Color.white); buddiesFileTextField.setEditable(true); buddiesFileTextField.setBackground(Color.white); authenticationFileTextField.setEditable(true); authenticationFileTextField.setBackground(Color.white); defaultRouterTextField.setEditable(true); defaultRouterTextField.setBackground(Color.white); } /** * This method is called from within the constructor to initialize the form. */ public void initComponents() { /** *************** The main frame ************************************** */ // width, height this.setSize(560, 370); Container container = this.getContentPane(); container.setLayout(new BoxLayout(getContentPane(), 1)); container.setBackground(containerBackGroundColor); this.setLocation(0, 0); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { new AlertInstantMessaging( "Your changes will not be checked: use the Submit button!!!", JOptionPane.WARNING_MESSAGE); hideFrame(); } }); /** **************** The components ********************************* */ firstPanel = new JPanel(); firstPanel.setBorder(BorderFactory.createEmptyBorder(15, 4, 15, 4)); // If put to False: we see the container's background firstPanel.setOpaque(false); // rows, columns, horizontalGap, verticalGap firstPanel.setLayout(new GridLayout(11, 2, 2, 2)); container.add(firstPanel); outboundProxyAddressLabel = new JLabel("Outbound proxy IP address:"); outboundProxyAddressLabel.setForeground(Color.black); outboundProxyAddressTextField = new JTextField(20); outboundProxyAddressLabel.setBorder(labelBorder); outboundProxyAddressLabel.setOpaque(true); outboundProxyAddressLabel.setBackground(labelBackGroundColor); firstPanel.add(outboundProxyAddressLabel); firstPanel.add(outboundProxyAddressTextField); outboundProxyPortLabel = new JLabel("Outbound proxy port:"); outboundProxyPortLabel.setForeground(Color.black); outboundProxyPortTextField = new JTextField(20); outboundProxyPortLabel.setBorder(labelBorder); outboundProxyPortLabel.setOpaque(true); outboundProxyPortLabel.setBackground(labelBackGroundColor); firstPanel.add(outboundProxyPortLabel); firstPanel.add(outboundProxyPortTextField); registrarAddressLabel = new JLabel("Registrar IP address:"); registrarAddressLabel.setForeground(Color.black); registrarAddressTextField = new JTextField(20); registrarAddressLabel.setBorder(labelBorder); registrarAddressLabel.setOpaque(true); registrarAddressLabel.setBackground(labelBackGroundColor); firstPanel.add(registrarAddressLabel); firstPanel.add(registrarAddressTextField); registrarPortLabel = new JLabel("Registrar port:"); registrarPortLabel.setForeground(Color.black); registrarPortTextField = new JTextField(20); registrarPortLabel.setBorder(labelBorder); registrarPortLabel.setOpaque(true); registrarPortLabel.setBackground(labelBackGroundColor); firstPanel.add(registrarPortLabel); firstPanel.add(registrarPortTextField); imAddressLabel = new JLabel("Contact IP address:"); imAddressLabel.setForeground(Color.black); imAddressTextField = new JTextField(20); imAddressLabel.setBorder(labelBorder); imAddressLabel.setOpaque(true); imAddressLabel.setBackground(labelBackGroundColor); firstPanel.add(imAddressLabel); firstPanel.add(imAddressTextField); imPortLabel = new JLabel("Contact port:"); imPortLabel.setForeground(Color.black); imPortTextField = new JTextField(20); imPortLabel.setBorder(labelBorder); imPortLabel.setOpaque(true); imPortLabel.setBackground(labelBackGroundColor); firstPanel.add(imPortLabel); firstPanel.add(imPortTextField); imProtocolLabel = new JLabel("Contact transport:"); imProtocolLabel.setForeground(Color.black); imProtocolTextField = new JTextField(20); imProtocolLabel.setBorder(labelBorder); imProtocolLabel.setOpaque(true); imProtocolLabel.setBackground(labelBackGroundColor); firstPanel.add(imProtocolLabel); firstPanel.add(imProtocolTextField); outputFileLabel = new JLabel("Output file:"); outputFileLabel.setForeground(Color.black); outputFileTextField = new JTextField(20); outputFileLabel.setBorder(labelBorder); outputFileLabel.setOpaque(true); outputFileLabel.setBackground(labelBackGroundColor); firstPanel.add(outputFileLabel); firstPanel.add(outputFileTextField); buddiesFileLabel = new JLabel("Buddies file:"); buddiesFileLabel.setForeground(Color.black); buddiesFileTextField = new JTextField(20); buddiesFileLabel.setBorder(labelBorder); buddiesFileLabel.setOpaque(true); buddiesFileLabel.setBackground(labelBackGroundColor); firstPanel.add(buddiesFileLabel); firstPanel.add(buddiesFileTextField); authenticationFileLabel = new JLabel("Authentication file:"); authenticationFileLabel.setForeground(Color.black); authenticationFileTextField = new JTextField(20); authenticationFileLabel.setBorder(labelBorder); authenticationFileLabel.setOpaque(true); authenticationFileLabel.setBackground(labelBackGroundColor); firstPanel.add(authenticationFileLabel); firstPanel.add(authenticationFileTextField); defaultRouterLabel = new JLabel("Default router class name:"); defaultRouterLabel.setForeground(Color.black); defaultRouterTextField = new JTextField(20); defaultRouterLabel.setBorder(labelBorder); defaultRouterLabel.setOpaque(true); defaultRouterLabel.setBackground(labelBackGroundColor); firstPanel.add(defaultRouterLabel); firstPanel.add(defaultRouterTextField); thirdPanel = new JPanel(); thirdPanel.setOpaque(false); // top, left, bottom, right thirdPanel.setLayout(new FlowLayout(FlowLayout.CENTER)); submitButton = new JButton(" Submit "); submitButton.setToolTipText("Submit your changes!"); submitButton.setFocusPainted(false); submitButton.setFont(new Font("Dialog", 1, 16)); submitButton.setBackground(buttonBackGroundColor); submitButton.setBorder(buttonBorder); submitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { submitButtonActionPerformed(evt); } }); thirdPanel.add(submitButton); container.add(thirdPanel); } public boolean check(String text) { if (text == null || text.trim().equals("")) { return false; } else return true; } public void submitButtonActionPerformed(ActionEvent evt) { String text = ""; IMUserAgent imUA = imGUI.getInstantMessagingUserAgent(); IMRegisterProcessing imRegisterProcessing = imUA .getIMRegisterProcessing(); if (!imRegisterProcessing.isRegistered()) { String temp = outboundProxyAddressTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.outboundProxyAddress=" + temp + "\n"; temp = outboundProxyPortTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.outboundProxyPort=" + temp + "\n"; temp = registrarAddressTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.registrarAddress=" + temp + "\n"; temp = registrarPortTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.registrarPort=" + temp + "\n"; temp = imAddressTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.imAddress=" + temp + "\n"; temp = imPortTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.imPort=" + temp + "\n"; temp = imProtocolTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.imProtocol=" + temp + "\n"; temp = outputFileTextField.getText(); if (temp != null && !temp.trim().equals("")) { text += "examples.im.outputFile=" + temp + "\n"; Logger logger = Logger .getLogger("gov.nist.sip.instantmessaging"); try { logger.addAppender(new FileAppender(new SimpleLayout(), text)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Logger logger = Logger .getLogger("gov.nist.sip.instantmessaging"); logger.addAppender(new ConsoleAppender(new SimpleLayout())); } temp = buddiesFileTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.buddiesFile=" + temp + "\n"; temp = authenticationFileTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.authenticationFile=" + temp + "\n"; temp = defaultRouterTextField.getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.defaultRouter=" + temp + "\n"; temp = imGUI.getLocalSipURLTextField().getText(); if (temp != null && !temp.trim().equals("")) text += "examples.im.localSipURL=" + temp + "\n"; String propertiesFile = imGUI.getPropertiesFile(); if (propertiesFile == null) logger .error("DebugIM, unable to write the " + "properties, specify a properties file when you start the client"); else { IMUtilities.writeFile(propertiesFile, text); imGUI.restart(); } this.setVisible(false); } else { new AlertInstantMessaging( "You must sign out from the registrar before changing something!!!", JOptionPane.ERROR_MESSAGE); } } }
d01d3ebdf8b865f0c918d264c06cd8b56bacf057
5f767a1699880eb026edcc886a9415c42d11bb50
/Sistema academico/src/sistema/academico/ListaProfessor.java
9c03ce6f95f8551c9f670b5c547d766f56d8c42e
[]
no_license
marcosr123/Projetos
ecad9dd012350f77223085cffda5c22477b2d83a
825bf1b75b57164c9913bf41e72d78b6417cdda7
refs/heads/master
2021-04-15T07:54:52.192424
2018-03-24T18:02:57
2018-03-24T18:02:57
126,624,963
1
0
null
null
null
null
UTF-8
Java
false
false
378
java
package sistema.academico; public class ListaProfessor extends Lista { public Professor find(String nome){ Professor obj; for(int i = 0; i < this.length(); i++){ obj = (Professor)this.get(); if(obj.getNome().equalsIgnoreCase(nome)){ return obj; } } return null; } }
31a480e9f84f6a4149ddd43e29b183c7f6aaf81b
e7d6a0d74a2a4a137c16c014a8525483dff99e42
/src/main/java/com/github/pagehelper/Constant.java
b3faf7d978e0e3f4149409dfca0010af5de73c72
[ "MIT" ]
permissive
MrhuRose/Mybatis-PageHelper
87790d2a7b4dd416f6603ea6da149feabf9fdd10
4dbd735ddd23c3597ae6ae339cd408a66017497a
refs/heads/master
2021-06-28T14:30:58.160089
2020-09-09T09:01:58
2020-09-09T09:01:58
140,372,608
1
0
MIT
2018-07-10T03:33:17
2018-07-10T03:33:17
null
UTF-8
Java
false
false
1,556
java
/* * The MIT License (MIT) * * Copyright (c) 2014-2017 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper; /** * @author liuzh */ public interface Constant { //分页的id后缀 String SUFFIX_PAGE = "_PageHelper"; //count查询的id后缀 String SUFFIX_COUNT = SUFFIX_PAGE + "_Count"; //第一个分页参数 String PAGEPARAMETER_FIRST = "First" + SUFFIX_PAGE; //第二个分页参数 String PAGEPARAMETER_SECOND = "Second" + SUFFIX_PAGE; }
9c8051ece87a1d818bb91cf8ac3d30738c96fc45
7b2d2cb399636bf7284e78f975e0970a0b70949f
/Day five/dou/dou/src/main/java/com/bytedance/androidcamp/network/dou/MainActivity.java
54c5e0c1c00be86cd36bd7da925fc294dff07197
[]
no_license
Zoe923/Android-software-development
0d2a23622cf462e64eb8a0477103fce7a30a6a57
75ce0b14875a97a2026a010b0c0a4e6ff04ef1f0
refs/heads/master
2022-11-15T19:39:28.311163
2020-07-15T13:58:43
2020-07-15T13:58:43
277,551,083
0
0
null
null
null
null
UTF-8
Java
false
false
9,744
java
package com.bytedance.androidcamp.network.dou; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.bytedance.androidcamp.network.dou.api.IMiniDouyinService; import com.bytedance.androidcamp.network.dou.model.GetVideosResponse; import com.bytedance.androidcamp.network.dou.model.PostVideoResponse; import com.bytedance.androidcamp.network.dou.model.Video; import com.bytedance.androidcamp.network.dou.util.ResourceUtils; import com.bytedance.androidcamp.network.lib.util.ImageHelper; import java.io.File; import java.util.ArrayList; import java.util.List; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { private static final int PICK_IMAGE = 1; private static final int PICK_VIDEO = 2; private static final String TAG = "MainActivity"; private RecyclerView mRv; private List<Video> mVideos = new ArrayList<>(); public Uri mSelectedImage; private Uri mSelectedVideo; public Button mBtn; private Button mBtnRefresh; private Retrofit retrofit = new Retrofit.Builder() .baseUrl(IMiniDouyinService.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); private IMiniDouyinService miniDouyinService = retrofit.create(IMiniDouyinService.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecyclerView(); initBtns(); } private void initBtns() { mBtn = findViewById(R.id.btn); mBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String s = mBtn.getText().toString(); if (getString(R.string.select_an_image).equals(s)) { //@TODO 1填充选择图片的功能 chooseImage(); } else if (getString(R.string.select_a_video).equals(s)) { //@TODO 2填充选择视频的功能 chooseVideo(); } else if (getString(R.string.post_it).equals(s)) { if (mSelectedVideo != null && mSelectedImage != null) { //@TODO 3调用上传功能 postVideo(); } else { throw new IllegalArgumentException("error data uri, mSelectedVideo = " + mSelectedVideo + ", mSelectedImage = " + mSelectedImage); } } else if ((getString(R.string.success_try_refresh).equals(s))) { mBtn.setText(R.string.select_an_image); } } }); mBtnRefresh = findViewById(R.id.btn_refresh); } public static class MyViewHolder extends RecyclerView.ViewHolder { public ImageView img; public MyViewHolder(@NonNull View itemView) { super(itemView); img = itemView.findViewById(R.id.img); } public void bind(final Activity activity, final Video video) { ImageHelper.displayWebImage(video.imageUrl, img); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { VideoActivity.launch(activity, video.videoUrl); } }); } } private void initRecyclerView() { mRv = findViewById(R.id.rv); mRv.setLayoutManager(new LinearLayoutManager(this)); mRv.setAdapter(new RecyclerView.Adapter<MyViewHolder>() { @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { return new MyViewHolder( LayoutInflater.from(MainActivity.this) .inflate(R.layout.video_item_view, viewGroup, false)); } @Override public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int i) { final Video video = mVideos.get(i); viewHolder.bind(MainActivity.this, video); } @Override public int getItemCount() { return mVideos.size(); } }); } public void chooseImage() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE); } public void chooseVideo() { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO); } @Override protected void onActivityResult(int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(TAG, "onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]"); if (resultCode == RESULT_OK && null != data) { if (requestCode == PICK_IMAGE) { mSelectedImage = data.getData(); Log.d(TAG, "selectedImage = " + mSelectedImage); mBtn.setText(R.string.select_a_video); } else if (requestCode == PICK_VIDEO) { mSelectedVideo = data.getData(); Log.d(TAG, "mSelectedVideo = " + mSelectedVideo); mBtn.setText(R.string.post_it); } } } private MultipartBody.Part getMultipartFromUri(String name, Uri uri) { File f = new File(ResourceUtils.getRealPath(MainActivity.this, uri)); RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), f); return MultipartBody.Part.createFormData(name, f.getName(), requestFile); } private void postVideo() { mBtn.setText("POSTING..."); mBtn.setEnabled(false); MultipartBody.Part coverImagePart = getMultipartFromUri("cover_image", mSelectedImage); MultipartBody.Part videoPart = getMultipartFromUri("video", mSelectedVideo); //@TODO 4下面的id和名字替换成自己的 miniDouyinService.postVideo("18888916639", "zoe923", coverImagePart, videoPart).enqueue( new Callback<PostVideoResponse>() { @Override public void onResponse(Call<PostVideoResponse> call, Response<PostVideoResponse> response) { if (response.body() != null) { Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_SHORT) .show(); } mBtn.setText(R.string.select_an_image); mBtn.setEnabled(true); } @Override public void onFailure(Call<PostVideoResponse> call, Throwable throwable) { mBtn.setText(R.string.select_an_image); mBtn.setEnabled(true); Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show(); } }); } public void fetchFeed(View view) { mBtnRefresh.setText("requesting..."); mBtnRefresh.setEnabled(false); miniDouyinService.getVideos().enqueue(new Callback<GetVideosResponse>() { @Override public void onResponse(Call<GetVideosResponse> call, Response<GetVideosResponse> response) { if (response.body() != null && response.body().videos != null) { mVideos = response.body().videos; //@TODO 5服务端没有做去重,拿到列表后,可以在端侧根据自己的id,做列表筛选。 int i; for(i=0;i<mVideos.size();i++) { if(!mVideos.get(i).studentId.equals("18888916639")) { mVideos.remove(i); i--; } } mRv.getAdapter().notifyDataSetChanged(); } mBtnRefresh.setText(R.string.refresh_feed); mBtnRefresh.setEnabled(true); } @Override public void onFailure(Call<GetVideosResponse> call, Throwable throwable) { mBtnRefresh.setText(R.string.refresh_feed); mBtnRefresh.setEnabled(true); Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
466b825995017fb12818b7a3b0d6f157cead045f
dd6cb045babdb8977aaa5afc39b105f7bc651305
/fila/src/main/java/one/digitalInovation/No.java
4d3ee20467746088922d58ed09031b7c30b43ec0
[]
no_license
andreaPaulo/estrutura-de-dados
c56e0ab7df14bd6df252b5d8780074707833d309
c08565c8c5fb3fc984ba60fac49b0076891c8957
refs/heads/main
2023-07-14T13:47:09.354590
2021-08-23T16:27:03
2021-08-23T16:27:03
396,113,064
0
0
null
null
null
null
UTF-8
Java
false
false
674
java
package one.digitalInovation; public class No <T>{ private T objectNo; private No refNo; public No() { } public No(T objectNo) { this.refNo = null; this.objectNo = objectNo; } public Object getObjectNo() { return objectNo; } public void setObjectNo(T objectNo) { this.objectNo = objectNo; } public No getRefNo() { return refNo; } public void setRefNo(No refNo) { this.refNo = refNo; } @Override public String toString() { return "No{" + "objectNo=" + objectNo + '}'; } }
9c37d25c5d32e640ab32c628d2b8ed5b8179ce1e
3910929e060740183bbf3716e3c6d1943cda97ee
/core/src/com/crashinvaders/texturepackergui/controllers/ConfigurationController.java
ef2df7e92fb464cf441c2c0f137be7fc9ba5497a
[ "Apache-2.0" ]
permissive
iromk/gdx-texture-packer-gui
afc662b1da4d4c41301b80dc23b4d58fdd5c9341
ef7c5a0b1dc98d8ba6beadd36a038cc6f7da9fde
refs/heads/master
2021-08-28T23:04:44.228030
2017-12-13T07:42:37
2017-12-13T07:42:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,363
java
package com.crashinvaders.texturepackergui.controllers; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TooltipManager; import com.badlogic.gdx.utils.I18NBundle; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.crashinvaders.texturepackergui.App; import com.crashinvaders.texturepackergui.AppConstants; import com.crashinvaders.texturepackergui.AppParams; import com.crashinvaders.texturepackergui.lml.AppLmlSyntax; import com.crashinvaders.texturepackergui.controllers.extensionmodules.CjkFontExtensionModule; import com.crashinvaders.texturepackergui.controllers.projectserializer.ProjectSerializer; import com.crashinvaders.texturepackergui.controllers.model.ModelService; import com.crashinvaders.texturepackergui.controllers.model.ProjectModel; import com.github.czyzby.autumn.annotation.Component; import com.github.czyzby.autumn.annotation.Initiate; import com.github.czyzby.autumn.mvc.component.i18n.LocaleService; import com.github.czyzby.autumn.mvc.component.ui.InterfaceService; import com.github.czyzby.autumn.mvc.component.ui.SkinService; import com.github.czyzby.autumn.mvc.component.ui.action.ActionProvider; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewController; import com.github.czyzby.autumn.mvc.stereotype.preference.*; import com.github.czyzby.kiwi.util.common.Strings; import com.github.czyzby.kiwi.util.gdx.asset.lazy.provider.ObjectProvider; import com.github.czyzby.lml.parser.LmlParser; import com.github.czyzby.lml.parser.LmlSyntax; import com.kotcrab.vis.ui.Locales; import com.kotcrab.vis.ui.VisUI; import com.kotcrab.vis.ui.widget.file.FileUtils; import java.util.Locale; import static com.github.czyzby.autumn.mvc.config.AutumnActionPriority.*; @SuppressWarnings("unused") @Component public class ConfigurationController { private static final String TAG = ConfigurationController.class.getSimpleName(); @LmlParserSyntax LmlSyntax syntax = new AppLmlSyntax(); @StageViewport ObjectProvider<Viewport> viewportProvider = new ObjectProvider<Viewport>() { @Override public Viewport provide() { return new ScreenViewport(); } }; /** These i18n-related fields will allow {@link LocaleService} to save game's locale in preferences file. Locale * changing actions will be automatically added to LML templates - see settings.lml. */ @I18nLocale(propertiesPath = AppConstants.PREF_NAME_COMMON, defaultLocale = "en") String localePreference = "locale"; @AvailableLocales String[] availableLocales = new String[] { "en", "ru", "de", "zh_TW" }; @I18nBundle String bundlePath = "i18n/bundle"; @Initiate(priority = VERY_HIGH_PRIORITY) public void initiateSkin(final SkinService skinService, CjkFontExtensionModule cjkFontModule) { Skin skin = new Skin(); { FreeTypeFontGenerator.setMaxTextureSize(2048); FreeTypeFontGenerator fontGenerator = new FreeTypeFontGenerator(Gdx.files.internal("VisOpenSansKerned.ttf")); FreeTypeFontGenerator.FreeTypeFontParameter paramsDefault = new FreeTypeFontGenerator.FreeTypeFontParameter(); paramsDefault.color = new Color(0xffffffe8); paramsDefault.size = 15; paramsDefault.incremental = true; paramsDefault.renderCount = 1; paramsDefault.gamma = 1.0f; paramsDefault.hinting = FreeTypeFontGenerator.Hinting.Full; FreeTypeFontGenerator.FreeTypeFontParameter paramsSmall = new FreeTypeFontGenerator.FreeTypeFontParameter(); paramsSmall.color = new Color(0xffffffe8); paramsSmall.size = 12; paramsSmall.incremental = true; paramsSmall.renderCount = 1; paramsSmall.gamma = 0.5f; paramsSmall.hinting = FreeTypeFontGenerator.Hinting.Full; FreeTypeFontGenerator.FreeTypeFontParameter paramsBig = new FreeTypeFontGenerator.FreeTypeFontParameter(); paramsBig.color = new Color(0xffffffe8); paramsBig.size = 22; paramsBig.incremental = true; paramsBig.renderCount = 1; paramsBig.gamma = 0.75f; paramsBig.hinting = FreeTypeFontGenerator.Hinting.Full; BitmapFont fontDefault = fontGenerator.generateFont(paramsDefault); BitmapFont fontSmall = fontGenerator.generateFont(paramsSmall); BitmapFont fontBig = fontGenerator.generateFont(paramsBig); if (cjkFontModule.isActivated()) { Gdx.app.log(TAG, "Skin initialized with CJK font."); FreeTypeFontGenerator.FreeTypeBitmapFontData ftFontDataDefault = (FreeTypeFontGenerator.FreeTypeBitmapFontData) fontDefault.getData(); ftFontDataDefault.addGenerator(new FreeTypeFontGenerator(cjkFontModule.getFontFile())); FreeTypeFontGenerator.FreeTypeBitmapFontData ftFontDataSmall = (FreeTypeFontGenerator.FreeTypeBitmapFontData) fontSmall.getData(); ftFontDataSmall.addGenerator(new FreeTypeFontGenerator(cjkFontModule.getFontFile())); FreeTypeFontGenerator.FreeTypeBitmapFontData ftFontDataBig = (FreeTypeFontGenerator.FreeTypeBitmapFontData) fontBig.getData(); ftFontDataBig.addGenerator(new FreeTypeFontGenerator(cjkFontModule.getFontFile())); } skin.add("default-font", fontDefault, BitmapFont.class); skin.add("small-font", fontSmall, BitmapFont.class); skin.add("big-font", fontBig, BitmapFont.class); } skin.addRegions(new TextureAtlas(Gdx.files.internal("skin/uiskin.atlas"))); skin.load(Gdx.files.internal("skin/uiskin.json")); VisUI.load(skin); skinService.addSkin("default", skin); for (BitmapFont font : skin.getAll(BitmapFont.class).values()) { font.getData().markupEnabled = true; font.getData().missingGlyph = font.getData().getGlyph((char)0xFFFD); } // Extracting all colors from the skin and importing them into global color collection for (ObjectMap.Entry<String, Color> entry : skin.getAll(Color.class)) { Colors.put(entry.key, entry.value); } } @Initiate(priority = HIGH_PRIORITY) public void initVisUiI18n(InterfaceService interfaceService, final LocaleService localeService) { Locales.setLocale(localeService.getCurrentLocale()); interfaceService.setActionOnBundlesReload(new Runnable() { @Override public void run() { Locale locale = localeService.getCurrentLocale(); Locales.setButtonBarBundle(I18NBundle.createBundle(Gdx.files.internal("i18n/visui/buttonbar"), locale)); Locales.setColorPickerBundle(I18NBundle.createBundle(Gdx.files.internal("i18n/visui/colorpicker"), locale)); Locales.setDialogsBundle(I18NBundle.createBundle(Gdx.files.internal("i18n/visui/dialogs"), locale)); Locales.setFileChooserBundle(I18NBundle.createBundle(Gdx.files.internal("i18n/visui/filechooser"), locale)); Locales.setTabbedPaneBundle(I18NBundle.createBundle(Gdx.files.internal("i18n/visui/tabbedpane"), locale)); } }); } @Initiate(priority = HIGH_PRIORITY) public void initializeInterface(InterfaceService interfaceService) { InterfaceService.DEFAULT_FADING_TIME = 0.15f; TooltipManager tooltipManager = interfaceService.getParser().getData().getDefaultTooltipManager(); tooltipManager.initialTime = 0.75f; tooltipManager.hideAll(); LmlParser parser = interfaceService.getParser(); parser.getData().addArgument("projectExt", "."+AppConstants.PROJECT_FILE_EXT); parser.getData().addArgument("imageExt", "."+Strings.join(" .", AppConstants.IMAGE_FILE_EXT)); interfaceService.setShowingActionProvider(new ActionProvider() { @Override public Action provideAction(final ViewController forController, final ViewController connectedView) { return Actions.sequence( Actions.alpha(0f), Actions.fadeIn(InterfaceService.DEFAULT_FADING_TIME), Actions.run(new Runnable() { @Override public void run() { App.inst().getInput().addProcessor(forController.getStage(), 100); } })); } }); interfaceService.setHidingActionProvider(new ActionProvider() { @Override public Action provideAction(final ViewController forController, final ViewController connectedView) { return Actions.sequence( Actions.run(new Runnable() { @Override public void run() { App.inst().getInput().removeProcessor(forController.getStage()); } }), Actions.fadeOut(InterfaceService.DEFAULT_FADING_TIME)); } }); } // Try load initial project @Initiate(priority = -1000) public void startupProject(ModelService modelService, ProjectSerializer projectSerializer) { AppParams params = App.inst().getParams(); if (params.startupProject == null) return; FileHandle projectFile = FileUtils.toFileHandle(params.startupProject); if (!projectFile.exists()) { Gdx.app.error(TAG, "Project file: " + projectFile + " doesn't exists."); return; } ProjectModel project = projectSerializer.loadProject(projectFile); project.setProjectFile(projectFile); modelService.setProject(project); } }
3cef2e6f04741a35cbf7de5eadf02ef1d61f7e02
1f87e4e449c44743002da2a2bf302d3cc44828bb
/ColorsWitch/src/colorswitch/Level5.java
f5a8256e32977255eaba38353cfdf1806a944140
[]
no_license
wyj4630/finished_projects
9770ac10c0600fea726ca3ffc879769473112c7d
852cd49790855b8617e866cc7333af6742685dfd
refs/heads/master
2020-05-07T10:41:56.435456
2019-04-10T12:44:18
2019-04-10T12:44:18
180,428,004
0
0
null
null
null
null
UTF-8
Java
false
false
1,056
java
package colorswitch; public class Level5 extends Level { public Level5(double screenWidth, double screenHeight) { super(screenWidth, screenHeight); double x = screenWidth / 2; // Création des obstacles RotatingCircle obstacle1 = new RotatingCircle(x, 0.75*screenHeight, 25, 100, 5); RotatingCircle obstacle2 = new RotatingCircle(x, 2.0*screenHeight, 25, 100, -5); RotatingCircle obstacle3 = new RotatingCircle(x, 3.2*screenHeight, 25, 100, 10); RotatingCircle obstacle4 = new RotatingCircle(x, 3.8*screenHeight, 25, 100, -10); obstacles.add(obstacle1); obstacles.add(obstacle2); obstacles.add(obstacle3); obstacles.add(obstacle4); //creation d'item Shield item1 = new Shield(x, 1.5*screenHeight); Potion item2 = new Potion(x, 2.8 * screenHeight); items.add(item1); items.add(item2); victoryMushroom = new Mushroom(screenWidth / 2, 4.5* screenHeight); } }
1d57c47a77781b55df6624868efc4f3e417db495
7f01b7ca55d23aed2d3a3e295200a214cfbf051d
/Decorator/src/My/Ford.java
64702f7de5d8acdfc2f3ea8555303988e6960571
[]
no_license
Nekit-vp/Design-Patterns-Java
ad2d4e17b75f3eddbd023ab1e722607057056376
97274c1a8389546c354b4098c78839409f4a08a1
refs/heads/main
2023-04-16T11:09:07.386860
2021-04-15T08:23:50
2021-04-15T08:23:50
346,417,031
0
0
null
null
null
null
UTF-8
Java
false
false
172
java
package My; public class Ford extends Car{ @Override public int cost() { return 300000; } public Ford() { description = "Ford"; } }
f26dae2a73dadbe81e639cf422aa79cee8ce38fa
4d35e6dc0aabb06fd702df38cbac8cdb750621e1
/app/src/main/java/com/connectycube/sample/chat/ui/activity/SelectUsersActivity.java
62d6acd686e6c3a375ccf9d7d5f4fd57ed9ea443
[ "MIT" ]
permissive
Alfian5229/connectycube-android-sample-chat
3b80fef3f2bdbaf70c0004705a6738d493a72cc4
9ca1ca1729d2aecd4f6ea3fd0840f1bd11235cdb
refs/heads/master
2020-09-08T00:12:22.964572
2019-11-11T10:12:33
2019-11-11T10:12:33
220,948,640
0
0
null
null
null
null
UTF-8
Java
false
false
7,012
java
package com.connectycube.sample.chat.ui.activity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.connectycube.chat.ConnectycubeChatService; import com.connectycube.chat.model.ConnectycubeChatDialog; import com.connectycube.core.EntityCallback; import com.connectycube.core.exception.ResponseException; import com.connectycube.sample.chat.R; import com.connectycube.sample.chat.ui.adapter.CheckboxUsersAdapter; import com.connectycube.sample.chat.utils.holder.DialogHolder; import com.connectycube.users.ConnectycubeUsers; import com.connectycube.users.model.ConnectycubeUser; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static com.connectycube.sample.chat.ui.activity.ChatActivity.EXTRA_DIALOG_ID; import static com.connectycube.sample.chat.utils.Consts.SAMPLE_USER_CONFIG; import static com.connectycube.sample.chat.utils.configs.UserConfig.getAllUsersFromFile; public class SelectUsersActivity extends BaseActivity { public static final String EXTRA_USERS = "users"; public static final int MINIMUM_CHAT_OCCUPANTS_SIZE = 2; private static final long CLICK_DELAY = TimeUnit.SECONDS.toMillis(2); private ListView usersListView; private CheckboxUsersAdapter usersAdapter; private long lastClickTime = 0L; public static void start(Context context) { Intent intent = new Intent(context, SelectUsersActivity.class); context.startActivity(intent); } /** * Start activity for picking users * * @param activity activity to return result * @param code request code for onActivityResult() method * <p> * in onActivityResult there will be 'ArrayList<ConnectycubeUser>' in the intent extras * which can be obtained with SelectPeopleActivity.EXTRA_USERS key */ public static void startForResult(Activity activity, int code) { startForResult(activity, code, null); } public static void startForResult(Activity activity, int code, String dialogId) { Intent intent = new Intent(activity, SelectUsersActivity.class); intent.putExtra(EXTRA_DIALOG_ID, dialogId); activity.startActivityForResult(intent, code); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_users); usersListView = findViewById(R.id.list_select_users); TextView listHeader = (TextView) LayoutInflater.from(this) .inflate(R.layout.include_list_hint_header, usersListView, false); listHeader.setText(R.string.select_users_list_hint); usersListView.addHeaderView(listHeader, null, false); if (isEditingChat()) { setActionBarTitle(R.string.select_users_edit_chat); } else { setActionBarTitle(R.string.select_users_create_chat); } actionBar.setDisplayHomeAsUpEnabled(true); loadUsers(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_select_users, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if ((SystemClock.uptimeMillis() - lastClickTime) < CLICK_DELAY) { return super.onOptionsItemSelected(item); } lastClickTime = SystemClock.uptimeMillis(); switch (item.getItemId()) { case R.id.menu_select_people_action_done: if (usersAdapter != null) { List<ConnectycubeUser> users = new ArrayList<>(usersAdapter.getSelectedUsers()); if (users.size() >= MINIMUM_CHAT_OCCUPANTS_SIZE) { passResultToCallerActivity(); } else { Toast.makeText(this, R.string.select_users_choose_users, Toast.LENGTH_SHORT).show(); } } return true; case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected View getSnackbarAnchorView() { return findViewById(R.id.layout_root); } private void passResultToCallerActivity() { Intent result = new Intent(); ArrayList<ConnectycubeUser> selectedUsers = new ArrayList<>(usersAdapter.getSelectedUsers()); result.putExtra(EXTRA_USERS, selectedUsers); setResult(RESULT_OK, result); finish(); } private void loadUsers() { showProgressDialog(R.string.dlg_loading_opponents); ArrayList<String> usersLogins = new ArrayList<>(); List<ConnectycubeUser> users = getAllUsersFromFile(SAMPLE_USER_CONFIG, this); for (ConnectycubeUser user : users) { usersLogins.add(user.getLogin()); } ConnectycubeUsers.getUsersByLogins(usersLogins, null).performAsync(new EntityCallback<ArrayList<ConnectycubeUser>>() { @Override public void onSuccess(ArrayList<ConnectycubeUser> users, Bundle bundle) { hideProgressDialog(); initCurrentUserFullNameIfExist(users); initAdapter(users); } @Override public void onError(ResponseException e) { hideProgressDialog(); Toast.makeText(getApplicationContext(), getString(R.string.loading_users_error, e.getMessage()), Toast.LENGTH_SHORT).show(); } }); } private void initCurrentUserFullNameIfExist(ArrayList<ConnectycubeUser> users) { ConnectycubeUser currentUser = ConnectycubeChatService.getInstance().getUser(); for (ConnectycubeUser user : users) { if (currentUser.getId().equals(user.getId())) { currentUser.setFullName(user.getFullName()); break; } } } private void initAdapter(ArrayList<ConnectycubeUser> users) { String dialogId = getIntent().getStringExtra(EXTRA_DIALOG_ID); usersAdapter = new CheckboxUsersAdapter(SelectUsersActivity.this, users); if (dialogId != null) { ConnectycubeChatDialog dialog = DialogHolder.getInstance().getChatDialogById(dialogId); if (dialog != null) { usersAdapter.addSelectedUsers(dialog.getOccupants()); } } usersListView.setAdapter(usersAdapter); } private boolean isEditingChat() { return getIntent().getSerializableExtra(EXTRA_DIALOG_ID) != null; } }
6cdd02219a5d9619a15a99313101b33124f2d652
fa475f76ba6f655380d1e4eee901600541ae3d66
/sandbox/DaemonTestThread.java
cafcbdf628dc977b2334e57a216aba7b4b2399ba
[]
no_license
Mokane3562/secret-java-hipster-sandbox
de86ce4d842c1662d1deb83f885726f436ddc938
32d92e0d1c55f2d8a6be7a27e194150a8fe2f055
refs/heads/master
2022-08-07T23:05:41.287141
2015-02-10T19:27:58
2015-02-10T19:27:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
325
java
import java.util.Timer; import java.util.TimerTask; public class DaemonTestThread { public static void main(String[] args) { TimerTask task = new TimerTask() { public void run(){ System.out.println("zombie thread!"); return; } }; Timer timer = new Timer(true); timer.schedule(task, 10000); } }
27b9aa0da0479d970cbb36c9afdee38afe90b07a
a22df36bf6f8c7e1d072335d6214011cccc2f668
/com/drturner/nowcoderv2/problem34/CommonNode.java
cdd13316d3767452ab2f401f976ce4f9391e51a0
[]
no_license
Turnarde/nowcoderv2
2897231726dab155a195b2e15a7c480cbcd1690a
8502fa6c883c948117ac2b51ff7f9248f547f2b4
refs/heads/master
2021-04-17T16:08:18.426831
2020-03-23T14:39:18
2020-03-23T14:39:18
249,458,039
1
0
null
null
null
null
UTF-8
Java
false
false
1,743
java
package com.drturner.nowcoderv2.problem34; import com.drturner.nowcoderv2.listNode.ListNode; public class CommonNode { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { int count=0; ListNode node1=pHead1; ListNode node2=pHead2; if (pHead1==null||pHead2==null) return null; while (node1!=null&&node2!=null){ node1=node1.next; node2=node2.next; } while (node1!=null){ node1=node1.next; count++; } while (node2!=null){ node2=node2.next; count--; } node1=pHead1; node2=pHead2; if (count>0){ while (count>0){ node1=node1.next; count--; } } else if (count<0){ while (count<0){ node2=node2.next; count++; } } while (node1!=null&&node2!=null){ if (node1==node2) return node1; node1=node1.next; node2=node2.next; } return null; } public static void main(String[] args) { ListNode listNode1=new ListNode(0); ListNode listNode2=new ListNode(2); ListNode listNode3=new ListNode(3); ListNode listNode4=new ListNode(1); ListNode listNode5=new ListNode(4); ListNode listNode6=new ListNode(5); listNode1.next=listNode2; listNode2.next=listNode3; listNode3.next=listNode4; listNode5.next=listNode6; listNode6.next=listNode3; ListNode listNode = new CommonNode().FindFirstCommonNode(listNode1, listNode2); System.out.println(listNode.val); } }
e7710b4edb3352c7748243030659374c60db0297
2ec242ede1e8929b2b2416cee889041329f74bdb
/src/main/java/com/coalescebd/spotwifi/AdService.java
143f4b70bf137cd59074b7d57cd92e91de3b17cb
[]
no_license
redviper2017/SpotWifiApplication
d1f6a8af7bf9948fd9bb4da66792e7ce03d50bcf
e1ca014acd32bd48ea8f3cb1b3e756abb673cf0f
refs/heads/master
2020-03-08T10:08:37.959683
2018-04-03T09:54:01
2018-04-03T09:54:01
113,000,264
0
0
null
null
null
null
UTF-8
Java
false
false
2,570
java
package com.coalescebd.spotwifi; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.DhcpInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.IBinder; import android.util.Log; import java.net.InetAddress; import java.net.UnknownHostException; /** * Created by User on 11/26/2017. */ public class AdService extends Service { private static final String TAG = "AdService"; private static final String LOG_TAG = "AdService"; String address; String rAddress; int a; public AdService(){} @Override public void onCreate() { Log.i(TAG,"Service onCreate"); //getting MAC address of the device WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); WifiInfo info = manager.getConnectionInfo(); address=info.getMacAddress(); boolean isRunning = true; //getting router's ip address final DhcpInfo dhcpInfo = manager.getDhcpInfo(); a=dhcpInfo.gateway; rAddress= String.valueOf(intToInetAddress(a)); Log.d(TAG,"Router IP: "+rAddress); } public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { //Let it continue running until it is stopped if (intent.getExtras().getBoolean("run service")){ Log.i(LOG_TAG,"Received Start Foreground Intent "); showNotification(); }else { Log.i(LOG_TAG,"Received Stop Foreground Intent"); stopForeground(true); stopSelf(); } return START_STICKY; } private void showNotification() { Intent notificationIntent = new Intent(this,MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); } @Override public void onDestroy() { super.onDestroy(); } public static InetAddress intToInetAddress(int hostAddress) { byte[] addressBytes = { (byte)(0xff & hostAddress), (byte)(0xff & (hostAddress >> 8)), (byte)(0xff & (hostAddress >> 16)), (byte)(0xff & (hostAddress >> 24)) }; try { return InetAddress.getByAddress(addressBytes); } catch (UnknownHostException e) { throw new AssertionError(); } } }
b60dbb378a2a9a05a6ac592963073e9fe51defcf
90435c1126a3451ad857ec3132085b440d28c79f
/Java/KafkaReader.java
6ab3a3136c74321abe9f2cec876417caae2db977
[]
no_license
spldlehich/demo
a38766b458447785346550529283f39d2855e178
570b428e005e78b56052c35785a6ff0d335c7325
refs/heads/master
2021-01-21T13:49:12.366806
2016-05-06T08:35:36
2016-05-06T08:35:36
20,923,458
0
0
null
null
null
null
UTF-8
Java
false
false
5,794
java
--- import java.net.InetSocketAddress; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import kafka.common.KafkaException; --- import static com.google.common.base.Preconditions.checkArgument; /** * Запускает обработчики сообщений из Kafka. Представляет из себя ридеры для разделов из временного хранилища. * * <p> * Вариант использования: * * <pre> * KafkaReader reader = new KafkaReader(propsKafka, topicName, countThread, serializedFactory); * reader.begin(brokers, shard, bufController); * </pre> * * <p> * <b>Synchronization</b> * <p> * Экземпляр данного класса является потокобезопасным. * * @see IKafkaReader * @see KafkaWorker */ public class KafkaReader implements IKafkaReader { /** * Тайм-аут для scheduleWithFixedDelay(читатели разделов) */ private static final int TIMEOUT = 1; private final Properties propsKafka; private final String topicName; private final ISerializerFactory serializedFactory; private final ScheduledThreadPoolExecutor serviceKafka; private final Map<Shard, KafkaShardWorker> workers = new HashMap<>(); private final Map<Shard, ScheduledFuture<?>> processes = new HashMap<>(); private final int maxCountThread; /** * Конструктор. Инициализирует потоки для обработки сообщений * * @param propsKafka настройки Kafka * @param topicName имя топика * @param countThread количество потоков для чтения сообщений * @param serializedFactory фабрика сериализатора */ public KafkaReader(Properties propsKafka, String topicName, int countThread, ISerializerFactory serializedFactory) { checkArgument(propsKafka != null); this.propsKafka = propsKafka; this.topicName = topicName; this.serializedFactory = serializedFactory; DefaultThreadFactory threadFactory = new DefaultThreadFactory("KafkaReader"); this.serviceKafka = new ScheduledThreadPoolExecutor(countThread, threadFactory); this.maxCountThread = countThread; } @Override public synchronized void commit() { for (Entry<Shard, KafkaShardWorker> entry : workers.entrySet()) { entry.getValue().commit(); } } @Override public synchronized void begin(List<InetSocketAddress> brokers, Shard shard, IKafkaReaderBufferController kafkaReaderBufferController, IRecoveryService recoveryService) throws KafkaException { if (processes.size() < maxCountThread) { if (processes.get(shard) == null) { KafkaShardWorker kafkaWorker = new KafkaShardWorker(propsKafka, brokers, topicName, shard.getShardNumber(), serializedFactory, kafkaReaderBufferController, recoveryService); try { ScheduledFuture<?> future = serviceKafka.scheduleWithFixedDelay(kafkaWorker, TIMEOUT, TIMEOUT, TimeUnit.SECONDS); workers.put(shard, kafkaWorker); processes.put(shard, future); } catch (RejectedExecutionException ex) { throw new KafkaException(ex); } } } } @Override public synchronized void end(Shard shard) throws KafkaException { Future<?> future = processes.get(shard); if (future != null) { boolean calceled = future.cancel(true); if (!calceled) throw new KafkaException(Messages.failed_cancel_thread()); processes.remove(shard); workers.remove(shard); } } @Override public void initialize() { } @Override public void release() { for (Entry<Shard, ScheduledFuture<?>> entry : processes.entrySet()) entry.getValue().cancel(true); for (Entry<Shard, KafkaShardWorker> entry : workers.entrySet()) entry.getValue().close(); processes.clear(); workers.clear(); serviceKafka.shutdown(); } @Override public int maxCountShards() { return maxCountThread; } @Override public synchronized boolean isWork(Shard shard) { return processes.get(shard) == null ? false : true; } @Override public void setCommitOffset(Shard shard) { KafkaShardWorker worker = workers.get(shard); if (worker != null) worker.setCommitOffset(); } @Override public boolean isCommitted(Shard shard) { KafkaShardWorker worker = workers.get(shard); if (worker != null) return worker.isCommitted(); return false; } @Localizable interface IMessagesList { IMessagesList Messages = LocalizableFactory.create(IMessagesList.class); @DefaultString("Cannot stop event reader thread.") @Context("В случае ошибки остановки потока по чтению событий из временного хранилища.") @Tags({"logs"}) String failed_cancel_thread(); } }
cece604bdc3b5f7978f948c98ef583bc4e399333
8f5d3d144cf98de0b0c535526eb65db0702d4ffc
/main/java/dqr/entity/petEntity/render2/DqmRenderPetGoldmanto.java
154a567d5217b9fd9173636306e0372a77b973d1
[]
no_license
azelDqm/MC1.7.10_DQRmod
54c0790b80c11a8ae591f17d233adc95f1b7e41a
bfec0e17fcade9d4616ac29b5abcbb12aa562d2a
refs/heads/master
2020-04-16T02:26:44.596119
2020-04-06T08:58:47
2020-04-06T08:58:47
57,311,023
6
2
null
null
null
null
UTF-8
Java
false
false
1,266
java
package dqr.entity.petEntity.render2; import net.minecraft.client.renderer.entity.RenderLiving; import dqr.entity.petEntity.DqmPetBase; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import dqr.entity.mobEntity.model2.DqmModelGoldmanto; public class DqmRenderPetGoldmanto extends RenderLiving { /* * テクスチャへのResourceLocationを設定する. */ private static final ResourceLocation DqmMobTexture = new ResourceLocation("dqr:textures/entity/mob/Goldmanto.png"); private static final ResourceLocation DqmMobSleepTexture = new ResourceLocation("dqr:textures/entity/mobSleep/GoldmantoPetzzz.png"); public DqmRenderPetGoldmanto() { /* * スーパークラスのコンストラクタの引数は * (このRenderと紐付けするModel, このRenderを使うEntityの足元の影の大きさ) */ super(new DqmModelGoldmanto(), 0.5F); } @Override protected ResourceLocation getEntityTexture(Entity par1EntityLiving) { // TODO 自動生成されたメソッド・スタブ //return null; if(par1EntityLiving instanceof DqmPetBase) { DqmPetBase pet = (DqmPetBase)par1EntityLiving; if(pet.isSitting()) { return this.DqmMobSleepTexture; } } return this.DqmMobTexture; } }
b57193ed2a34c0c7ad06bda489264a17289b0b10
6ea5a7020fed331ad06703d4054a72a8b059885c
/src/main/java/android/api/model/User.java
15128e3d8d5346878f578ba39fdb499e00502301
[]
no_license
ljorge19/Android-lista-supermercado-api
2b480ffc9aa5826aec1bb988f397a269a58e7dbd
c96d128b7e6d8e484cf4e64267720e597ff6d256
refs/heads/master
2020-04-08T05:16:05.582494
2018-11-27T20:46:45
2018-11-27T20:46:45
159,053,500
0
0
null
null
null
null
UTF-8
Java
false
false
1,131
java
package android.api.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; public class User { @Id public String id; @Indexed(unique=true) private String login; private String name; private String password; public User() { super(); } public User(String login, String name, String password) { super(); this.login = login; this.name = name; this.password = password; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [id=" + id + ", login=" + login + ", name=" + name + ", password=" + password + "]"; //return "User [login=" + login + ", name=" + name + ", password=" + password + "]"; } }
282d44a50472aa238e4a1c11cf7188b70675ef49
f65f9694b65ed252c9ae6322f00d6eef622f051a
/2.JavaCore/src/com/javarush/task/task17/task1707/IMF.java
8ae090a74fb6013d3c308735e0471a6f157f2c1c
[]
no_license
osavenko/JavaRushTasks
de6886e0643a97dc420aae1610685a7d88cfc3c5
30815d2e6be9262f87dac8f8575b4d2592ac27c3
refs/heads/master
2020-05-05T11:55:33.487963
2019-12-14T13:41:15
2019-12-14T13:41:15
180,008,573
0
0
null
null
null
null
UTF-8
Java
false
false
345
java
package com.javarush.task.task17.task1707; public class IMF { private static IMF imf;// = new IMF(); public static IMF getFund() { //add your code here - добавь код тут synchronized (IMF.class){ if(imf == null) imf = new IMF(); } return imf; } private IMF() { } }
7d02d3bcc302ea7f8a9af2f5006a0daa62747672
b6ec7e0be4fb11fcc61dcc84f598179f0e0f2775
/src/main/java/com/starmcc/qmframework/redis/QmRedisServiceImpl.java
97d68a213d4c6cae5033432a424d097c5de4213a
[ "Apache-2.0" ]
permissive
starmcc/qm-framework
71ba66a88a1aaf11c2a5c60225e323539d175298
8eb8678d783749de0e1a6ff079ed83da7b56d5c9
refs/heads/master
2022-06-24T07:43:41.513804
2021-12-28T07:37:01
2021-12-28T07:37:01
189,567,639
1
0
Apache-2.0
2022-06-17T02:09:47
2019-05-31T09:30:54
Java
UTF-8
Java
false
false
24,082
java
package com.starmcc.qmframework.redis; import com.starmcc.qmframework.exception.QmRedisServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import redis.clients.jedis.*; import redis.clients.jedis.resps.KeyedListElement; import java.util.*; import java.util.stream.Collectors; /** * 使用qm缓存Redis服务实现类 * * @author starmcc * @date 2021/11/19 */ public class QmRedisServiceImpl implements QmRedisService { private static final Logger LOG = LoggerFactory.getLogger(QmRedisServiceImpl.class); @Autowired private QmRedisTemplate template; @Override public JedisPool getJedisPool() { return template.getJedisPool(); } @Override public Jedis getJedis() { return template.getJedis(); } @Override public Jedis getJedis(final int index) { return template.getJedis(index); } /*######################## 基础操作 ####################*/ @Override public Set<String> keys(final String pattern) { return this.keys(pattern, 0); } @Override public Set<String> keys(final String pattern, final int index) { QmRedisKeyModel keyModel = QmRedisKeyModel.builder().index(index).build(); return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.keys(pattern); }, false); } @Override public Long del(final QmRedisKeyModel... keyModels) { return Arrays.stream(keyModels).collect(Collectors.summingLong(keyModel -> { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.del(key); }, false); })); } @Override public Boolean exists(final QmRedisKeyModel keyModel) { return (Boolean) template.execute(keyModel, (jedis, key) -> { return jedis.exists(key); }, false); } @Override public Long expire(final String key, final int index, final long seconds) { QmRedisKeyModel keyModel = QmRedisKeyModel.builder().keyPrefix(key).index(index).expTime(seconds).build(); return (Long) template.execute(keyModel, (jedis, k) -> { return jedis.expire(k, seconds); }, false); } @Override public Long expire(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.expire(key, keyModel.getExpTime()); }, false); } @Override public Long timeToLive(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.ttl(key); }, false); } /*######################## string(字符串)操作 ####################*/ @Override public String get(final QmRedisKeyModel keyModel) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.get(key); }, false); } @Override public String set(final QmRedisKeyModel keyModel, final String value) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.setex(key, keyModel.getExpTime(), value); }, false); } @Override public String getrange(final QmRedisKeyModel keyModel, final long startOffset, final long endOffset) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.getrange(key, startOffset, endOffset); }, false); } @Override public String getSet(final QmRedisKeyModel keyModel, final String value) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.getSet(key, value); }, true); } @Override public void lock(final QmRedisKeyModel keyModel, final QmRedisTemplate.Procedure procedure) { template.execute(keyModel, (jedis, key) -> { Long lock = jedis.setnx(keyModel.buildKey(), "lock"); boolean is = Objects.nonNull(lock) && lock.compareTo(1L) == 0; if (is) { try { procedure.run(); } catch (Exception e) { throw new QmRedisServiceException("Redis Service error", e); } finally { // 执行完毕后,锁释放 this.del(keyModel); } } }, true); } @Override public boolean lock(final QmRedisKeyModel keyModel) { return (boolean) template.execute(keyModel, (jedis, key) -> { Long lock = jedis.setnx(key, "lock"); return Objects.nonNull(lock) && lock.compareTo(1L) == 0; }, true); } @Override public Long strlen(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.strlen(key); }, false); } @Override public Long incr(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.incr(key); }, true); } @Override public Long incrBy(final QmRedisKeyModel keyModel, final long increment) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.incrBy(key, increment); }, true); } @Override public Double incrbyfloat(final QmRedisKeyModel keyModel, final double increment) { return (Double) template.execute(keyModel, (jedis, key) -> { return jedis.incrByFloat(key, increment); }, true); } @Override public Long decr(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.decr(key); }, true); } @Override public Long decrBy(final QmRedisKeyModel keyModel, final long decrement) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.decrBy(key, decrement); }, true); } @Override public Long append(final QmRedisKeyModel keyModel, final String value) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.append(key, value); }, true); } /*######################## hash(哈希)操作 ####################*/ @Override public Long hdel(final QmRedisKeyModel keyModel, final String... fields) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.hdel(key, fields); }, true); } @Override public Boolean hexists(final QmRedisKeyModel keyModel, final String field) { try { return (Boolean) template.execute(keyModel, (jedis, key) -> { return jedis.hexists(key, field); }, false); } catch (Exception e) { LOG.error("Redis Error {}", e.getMessage(), e); return true; } } @Override public String hget(final QmRedisKeyModel keyModel, final String field) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.hget(key, field); }, false); } @Override public Map<String, String> hgetAll(final QmRedisKeyModel keyModel) { return (Map<String, String>) template.execute(keyModel, (jedis, key) -> { return jedis.hgetAll(key); }, false); } @Override public Long hincrBy(final QmRedisKeyModel keyModel, final String field, final long increment) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.hincrBy(key, field, increment); }, true); } @Override public Double hincrByFloat(final QmRedisKeyModel keyModel, final String field, final double increment) { return (Double) template.execute(keyModel, (jedis, key) -> { return jedis.hincrByFloat(key, field, increment); }, true); } @Override public Set<String> hkeys(final QmRedisKeyModel keyModel) { return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.hkeys(key); }, false); } @Override public Long hlen(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.hlen(key); }, false); } @Override public List<String> hmget(final QmRedisKeyModel keyModel) { return (List<String>) template.execute(keyModel, (jedis, key) -> { return jedis.hmget(key); }, false); } @Override public String hmset(final QmRedisKeyModel keyModel, final Map<String, String> hash) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.hmset(key, hash); }, true); } @Override public Long hset(final QmRedisKeyModel keyModel, final String field, final String value) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.hset(key, field, value); }, true); } @Override public Long hsetnx(final QmRedisKeyModel keyModel, final String field, final String value) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.hsetnx(key, field, value); }, true); } @Override public List<String> hvals(final QmRedisKeyModel keyModel) { return (List<String>) template.execute(keyModel, (jedis, key) -> { return jedis.hvals(key); }, false); } @Override public ScanResult<Map.Entry<String, String>> hvals(final QmRedisKeyModel keyModel, final String cursor) { return (ScanResult<Map.Entry<String, String>>) template.execute(keyModel, (jedis, key) -> { return jedis.hscan(key, cursor); }, false); } /*######################## List(列表)操作 ####################*/ @Override public List<String> blpop(final QmRedisKeyModel... keyModels) { List<String> list = new ArrayList<>(); for (QmRedisKeyModel keyModel : keyModels) { List<String> tempList = (List<String>) template.execute(keyModel, (jedis, key) -> { return jedis.blpop(key); }, false); list.addAll(tempList); } return list; } @Override public KeyedListElement blpop(final QmRedisKeyModel keyModel, final long timeout) { return (KeyedListElement) template.execute(keyModel, (jedis, key) -> { return jedis.blpop(timeout, key); }, false); } @Override public List<String> brpop(final QmRedisKeyModel... keyModels) { List<String> list = new ArrayList<>(); for (QmRedisKeyModel keyModel : keyModels) { List<String> tempList = (List<String>) template.execute(keyModel, (jedis, key) -> { return jedis.brpop(key); }, false); list.addAll(tempList); } return list; } @Override public KeyedListElement brpop(final QmRedisKeyModel keyModel, final long timeout) { return (KeyedListElement) template.execute(keyModel, (jedis, key) -> { return jedis.brpop(timeout, key); }, false); } @Override public String lindex(final QmRedisKeyModel keyModel, final long index) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.lindex(key, index); }, false); } @Override public Long linsert(final QmRedisKeyModel keyModel, final ListPosition where, final String pivot, final String value) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.linsert(key, where, pivot, value); }, true); } @Override public Long llen(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.llen(key); }, false); } @Override public Long lpop(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.lpop(key); }, true); } @Override public Long lpush(final QmRedisKeyModel keyModel, final String... values) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.lpush(key, values); }, true); } @Override public Long lpushx(final QmRedisKeyModel keyModel, final String... values) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.lpushx(key, values); }, true); } @Override public List<String> lrange(final QmRedisKeyModel keyModel, final long start, final long stop) { return (List<String>) template.execute(keyModel, (jedis, key) -> { return jedis.lrange(key, start, stop); }, false); } @Override public Long lrem(final QmRedisKeyModel keyModel, final long count, final String value) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.lrem(key, count, value); }, true); } @Override public String lset(final QmRedisKeyModel keyModel, final long index, final String value) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.lset(key, index, value); }, true); } @Override public String ltrim(final QmRedisKeyModel keyModel, final long start, final long stop) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.ltrim(key, start, stop); }, true); } @Override public String rpoplpush(final QmRedisKeyModel sourceKeyModel, final QmRedisKeyModel targetKeyModel) { return (String) template.execute(targetKeyModel, (jedis, key) -> { return jedis.rpoplpush(sourceKeyModel.buildKey(), key); }, true); } @Override public Long rpush(final QmRedisKeyModel keyModel, final String... values) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.rpush(key, values); }, true); } @Override public Long rpushx(final QmRedisKeyModel keyModel, final String... values) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.rpushx(key, values); }, true); } /*######################## Set(集合)操作 ####################*/ @Override public Long sadd(final QmRedisKeyModel keyModel, final String... values) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.sadd(key, values); }, true); } @Override public Long scard(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.scard(key); }, false); } @Override public Set<String> sdiff(final QmRedisKeyModel... keyModels) { return (Set<String>) template.execute(keyModels[0], (jedis, key) -> { List<String> keys = Arrays.stream(keyModels).map(QmRedisKeyModel::buildKey).collect(Collectors.toList()); return jedis.sdiff(keys.toArray(new String[keys.size()])); }, false); } @Override public Long sdiffstore(final QmRedisKeyModel destinationKeyModel, final QmRedisKeyModel... keyModels) { return (Long) template.execute(destinationKeyModel, (jedis, key) -> { List<String> keys = Arrays.stream(keyModels).map(QmRedisKeyModel::buildKey).collect(Collectors.toList()); return jedis.sdiffstore(key, keys.toArray(new String[keys.size()])); }, true); } @Override public Boolean sismember(final QmRedisKeyModel keyModel, final String member) { return (Boolean) template.execute(keyModel, (jedis, key) -> { return jedis.sismember(key, member); }, false); } @Override public Set<String> smembers(final QmRedisKeyModel keyModel) { return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.smembers(key); }, false); } @Override public Long smove(final QmRedisKeyModel srcKeyModel, final QmRedisKeyModel dstKeyModel, final String member) { return (Long) template.execute(dstKeyModel, (jedis, key) -> { return jedis.smove(dstKeyModel.buildKey(), key, member); }, true); } @Override public String spop(final QmRedisKeyModel keyModel) { return (String) template.execute(keyModel, (jedis, key) -> { return jedis.spop(key); }, false); } @Override public List<String> srandmember(QmRedisKeyModel keyModel) { return this.srandmember(keyModel, 1); } @Override public List<String> srandmember(final QmRedisKeyModel keyModel, final int count) { return (List<String>) template.execute(keyModel, (jedis, key) -> { return jedis.srandmember(key, count); }, false); } @Override public Long srem(final QmRedisKeyModel keyModel, final String... member) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.srem(key, member); }, false); } @Override public Set<String> sunion(final QmRedisKeyModel... keyModels) { return (Set<String>) template.execute(keyModels[0], (jedis, key) -> { List<String> keys = Arrays.stream(keyModels).map(QmRedisKeyModel::buildKey).collect(Collectors.toList()); return jedis.sunion(keys.toArray(new String[keys.size()])); }, false); } @Override public Long sunionstore(final QmRedisKeyModel keyModel, final QmRedisKeyModel... keyModels) { return (Long) template.execute(keyModel, (jedis, key) -> { List<String> keys = Arrays.stream(keyModels).map(QmRedisKeyModel::buildKey).collect(Collectors.toList()); return jedis.sunionstore(key, keys.toArray(new String[keys.size()])); }, true); } @Override public ScanResult<String> sscan(final QmRedisKeyModel keyModel, final String cursor) { return (ScanResult<String>) template.execute(keyModel, (jedis, key) -> { return jedis.sscan(key, cursor); }, true); } /*######################## sorted set(有序集合)操作 ####################*/ @Override public Long zadd(final QmRedisKeyModel keyModel, final double score, final String member) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zadd(key, score, member); }, true); } @Override public Long zadd(final QmRedisKeyModel keyModel, final Map<String, Double> scoreMembers) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zadd(key, scoreMembers); }, true); } @Override public Long zcard(final QmRedisKeyModel keyModel) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zcard(key); }, false); } @Override public Long zcount(final QmRedisKeyModel keyModel, final double min, final double max) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zcount(key, min, max); }, false); } @Override public Double zincrby(final QmRedisKeyModel keyModel, final double increment, final String member) { return (Double) template.execute(keyModel, (jedis, key) -> { return jedis.zincrby(key, increment, member); }, true); } @Override public Long zinterstore(final QmRedisKeyModel keyModel, final String... sets) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zinterstore(key, sets); }, false); } @Override public Long zlexcount(final QmRedisKeyModel keyModel, final String min, final String max) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zlexcount(key, min, max); }, false); } @Override public Set<String> zrange(final QmRedisKeyModel keyModel, final long min, final long max) { return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.zrange(key, min, max); }, false); } @Override public Set<String> zrangeByLex(final QmRedisKeyModel keyModel, final String min, final String max, final int offset, final int count) { return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.zrangeByLex(key, min, max, offset, count); }, false); } @Override public Set<String> zrangeByLex(final QmRedisKeyModel keyModel, final String min, final String max) { return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.zrangeByLex(key, min, max); }, false); } @Override public Set<String> zrangeByScore(final QmRedisKeyModel keyModel, final double min, final double max) { return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.zrangeByScore(key, min, max); }, false); } @Override public Long zrank(final QmRedisKeyModel keyModel, final String member) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zrank(key, member); }, false); } @Override public Long zrem(final QmRedisKeyModel keyModel, final String... members) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zrem(key, members); }, true); } @Override public Long zremrangeByLex(final QmRedisKeyModel keyModel, final String min, final String max) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zremrangeByLex(key, min, max); }, true); } @Override public Long zremrangeByRank(final QmRedisKeyModel keyModel, final long start, final long stop) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zremrangeByRank(key, start, stop); }, true); } @Override public Long zremrangeByScore(final QmRedisKeyModel keyModel, final double min, final double max) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zremrangeByScore(key, min, max); }, true); } @Override public Set<String> zrevrange(final QmRedisKeyModel keyModel, final long start, final long stop) { return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.zrevrange(key, start, stop); }, false); } @Override public Set<String> zrevrangeByScore(final QmRedisKeyModel keyModel, final double max, final double min) { return (Set<String>) template.execute(keyModel, (jedis, key) -> { return jedis.zrevrangeByScore(key, max, min); }, false); } @Override public Long zrevrank(final QmRedisKeyModel keyModel, final String member) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zrevrank(key, member); }, false); } @Override public Double zscore(final QmRedisKeyModel keyModel, final String member) { return (Double) template.execute(keyModel, (jedis, key) -> { return jedis.zscore(key, member); }, false); } @Override public Long zunionstore(final QmRedisKeyModel keyModel, final String... sets) { return (Long) template.execute(keyModel, (jedis, key) -> { return jedis.zunionstore(key, sets); }, false); } @Override public ScanResult<Tuple> zscan(final QmRedisKeyModel keyModel, final String cursor) { return (ScanResult<Tuple>) template.execute(keyModel, (jedis, key) -> { return jedis.zscan(key, cursor); }, false); } }
a48847dfff9b5edf994667b3caebd98d65dc50f1
ccb342428bb50c72dc1b482505bf8c6e9f91471d
/shancha-config-server/src/main/java/com/shancha/config/server/ShanchaConfigServerApplication.java
337fab95c68bcc998a635e5a07f21f7632f9db6c
[]
no_license
AndyWee213/shancha-parent
6e8155c71ebc14c270d5b5b8addea65b902cc5d6
85bd328b337320958d274c3e11eedc7fa5ae6ac3
refs/heads/master
2021-09-18T09:07:16.564380
2018-07-12T09:53:10
2018-07-12T09:53:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
679
java
package com.shancha.config.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Configuration; @EnableConfigServer @EnableEurekaClient @Configuration @EnableAutoConfiguration public class ShanchaConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ShanchaConfigServerApplication.class, args); } }
513a1243ba0ab65fc0fff59aadce681233ce434f
fa2a63e78d5c8010a9dbe65846c326f7bee9faa2
/WeClean source/weClean/src/main/java/com/ligootech/weclean/Shopdetails.java
50e353af1768e3b5ca0f0f819ba2b17584be26f1
[]
no_license
cubecnelson/WeClean
ea89297b2c2b33926767034852822c1cb6b05a61
ce5928ca986e83ebda8f5970f4f533e11a187b2c
refs/heads/master
2016-09-12T22:17:11.196510
2016-04-22T04:13:33
2016-04-22T04:13:33
56,349,306
0
0
null
null
null
null
UTF-8
Java
false
false
7,621
java
package com.ligootech.weclean; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Locale; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.actionbarsherlock.app.ActionBar; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class Shopdetails extends Activity { TextView phoneno, address, shopname; ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); InputStream is = null; Boolean errfl = false; StringBuilder sb = null; // shopShopdetails private static final String TAG_SHOPARRAY = "Shopdetails"; private static final String TAG_PHONE = "phone"; private static final String TAG_ADDRESS = "address"; private static final String TAG_SHOPNAME = "shopname"; private static final String TAG_ADDRESSC = "addressC"; private static final String TAG_SHOPNAMEC = "shopnameC"; private static final String TAG_ITEMNAMEC = "ItemNameChinese"; private static final String TAG_ITEMNAME = "ItemName"; private static final String TAG_PRICE = "Price"; JSONArray jversion = null; String result = null; String PHONE, ADDRESS, Link3, SHOPNAME, ITEMNAME, PRICE; String value; ListView listprice; ArrayList<String> Values = new ArrayList<String>(); Handler handler; ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.shopdetails); //set action bar final android.app.ActionBar actionBar = this.getActionBar(); // actionBar.setCustomView(R.layout.action_home); actionBar.setTitle(getString(R.string.ShopDetails)); // change it to actual // title actionBar.setDisplayUseLogoEnabled(false); actionBar.setDisplayShowHomeEnabled(false); centerActionBarTitle(); phoneno = (TextView) findViewById(R.id.phonetextView2); address = (TextView) findViewById(R.id.addresstextView4); shopname = (TextView) findViewById(R.id.shopname); listprice = (ListView) findViewById(R.id.listprice); adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, android.R.id.text1, Values); Bundle extras = getIntent().getExtras(); if (extras != null) { value = extras.getString("variable"); System.out.println("Shopvalue" + value); } Link3 = getString(R.string.lnk_shop_details); handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); listprice.setAdapter(adapter); phoneno.setText(PHONE); address.setText(ADDRESS); shopname.setText(SHOPNAME); } }; ShopToServer myTask1 = new ShopToServer(); myTask1.execute(); } public class ShopToServer extends AsyncTask<Void, Void, Void> { ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(Shopdetails.this, "WeClean", "Processing..."); nameValuePairs.add(new BasicNameValuePair("shopid", value)); } @Override protected Void doInBackground(Void... arg0) { httppost(Link3); fetchshop(); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); progressDialog.dismiss(); handler.sendEmptyMessage(0); } } private void fetchshop() { // convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "UTF-8"), 8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line = "0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); if (result != null) { JSONObject jsonObj = new JSONObject(result); // Getting JSON Array node jversion = jsonObj.getJSONArray(TAG_SHOPARRAY); Locale current = getResources().getConfiguration().locale; try { // looping through All product items for (int itemlistidx = 0; itemlistidx < jversion.length(); itemlistidx++) { JSONObject c = jversion.getJSONObject(itemlistidx); PHONE = (c.getString(TAG_PHONE)); if(current.equals(Locale.SIMPLIFIED_CHINESE) || current.equals(Locale.TRADITIONAL_CHINESE)) { ADDRESS = (c.getString(TAG_ADDRESSC)); SHOPNAME = (c.getString(TAG_SHOPNAMEC)); ITEMNAME = (c.getString(TAG_ITEMNAMEC)) + " - " + (c.getString(TAG_PRICE)) + getResources().getString(R.string.chinesecur); Values.add(ITEMNAME); } else { ADDRESS = (c.getString(TAG_ADDRESS)); SHOPNAME = (c.getString(TAG_SHOPNAME)); ITEMNAME = (c.getString(TAG_ITEMNAME)) + " - " + (c.getString(TAG_PRICE)) + getResources().getString(R.string.chinesecur); Values.add(ITEMNAME); } } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } } catch (Exception exception) { } } private void httppost(String link) { try { HttpClient httpclient = new DefaultHttpClient(); // accountNameSV=accountNameSV.replaceAll("\\s+",""); HttpPost httppost = new HttpPost(link); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); final Activity activity = Shopdetails.this; activity.runOnUiThread(new Runnable() { public void run() { Toast.makeText(activity, "Request timeout, please try again!!!!", Toast.LENGTH_LONG) .show(); } }); errfl = true; finish(); } } private void centerActionBarTitle() { int titleId = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { titleId = getResources().getIdentifier("action_bar_title", "id", "android"); } else { // This is the id is from your app's generated R class when // ActionBarActivity is used // for SupportActionBar titleId = R.id.abs__action_bar; } // Final check for non-zero invalid id if (titleId > 0) { TextView titleTextView = (TextView) findViewById(titleId); DisplayMetrics metrics = getResources().getDisplayMetrics(); // Fetch layout parameters of titleTextView // (LinearLayout.LayoutParams : Info from HierarchyViewer) LinearLayout.LayoutParams txvPars = (android.widget.LinearLayout.LayoutParams) titleTextView .getLayoutParams(); txvPars.gravity = Gravity.CENTER_HORIZONTAL; txvPars.width = metrics.widthPixels; titleTextView.setLayoutParams(txvPars); titleTextView.setGravity(Gravity.CENTER); } } }
[ "cubecnelson" ]
cubecnelson
ee44486e47d8717b4f98bc47c4b54e38ad3d75bf
20eb62855cb3962c2d36fda4377dfd47d82eb777
/newEvaluatedBugs/Jsoup_42_buggy/mutated/75/TokeniserState.java
bf8c7d3c8568bf3622d093d83c73ca6ebc3294bd
[]
no_license
ozzydong/CapGen
356746618848065cce4e253e5d3c381baa85044a
0ba0321b6b1191443276021f1997833342f02515
refs/heads/master
2023-03-18T20:12:02.923428
2020-08-21T03:08:28
2020-08-21T03:08:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
61,202
java
package org.jsoup.parser; /** * States and transition activations for the Tokeniser. */ enum TokeniserState { Data { // in data state, gather characters until a character reference or tag is found void read(Tokeniser t, CharacterReader r) { switch (r.current()) { case '&': t.advanceTransition(CharacterReferenceInData); break; case '<': t.advanceTransition(TagOpen); break; case nullChar: t.error(this); // NOT replacement character (oddly?) t.emit(r.consume()); break; case eof: t.emit(new Token.EOF()); break; default: String data = r.consumeToAny('&', '<', nullChar); t.emit(data); break; } } }, CharacterReferenceInData { // from & in data void read(Tokeniser t, CharacterReader r) { Character c = t.consumeCharacterReference(null, false); if (c == null) t.emit('&'); else t.emit(c); t.transition(Data); } }, Rcdata { /// handles data in title, textarea etc void read(Tokeniser t, CharacterReader r) { switch (r.current()) { case '&': t.advanceTransition(CharacterReferenceInRcdata); break; case '<': t.advanceTransition(RcdataLessthanSign); break; case nullChar: t.error(this); r.advance(); t.emit(replacementChar); break; case eof: t.emit(new Token.EOF()); break; default: String data = r.consumeToAny('&', '<', nullChar); t.emit(data); break; } } }, CharacterReferenceInRcdata { void read(Tokeniser t, CharacterReader r) { Character c = t.consumeCharacterReference(null, false); if (c == null) t.emit('&'); else t.emit(c); t.transition(Rcdata); } }, Rawtext { void read(Tokeniser t, CharacterReader r) { switch (r.current()) { case '<': t.advanceTransition(RawtextLessthanSign); break; case nullChar: t.error(this); r.advance(); t.emit(replacementChar); break; case eof: t.emit(new Token.EOF()); break; default: String data = r.consumeToAny('<', nullChar); t.emit(data); break; } } }, ScriptData { void read(Tokeniser t, CharacterReader r) { switch (r.current()) { case '<': t.advanceTransition(ScriptDataLessthanSign); break; case nullChar: t.error(this); r.advance(); t.emit(replacementChar); break; case eof: t.emit(new Token.EOF()); break; default: String data = r.consumeToAny('<', nullChar); t.emit(data); break; } } }, PLAINTEXT { void read(Tokeniser t, CharacterReader r) { switch (r.current()) { case nullChar: t.error(this); r.advance(); t.emit(replacementChar); break; case eof: t.emit(new Token.EOF()); break; default: String data = r.consumeTo(nullChar); t.emit(data); break; } } }, TagOpen { // from < in data void read(Tokeniser t, CharacterReader r) { switch (r.current()) { case '!': t.advanceTransition(MarkupDeclarationOpen); break; case '/': t.advanceTransition(EndTagOpen); break; case '?': t.advanceTransition(BogusComment); break; default: if (r.matchesLetter()) { t.createTagPending(true); t.transition(TagName); } else { t.error(this); t.emit('<'); // char that got us here t.transition(Data); } break; } } }, EndTagOpen { void read(Tokeniser t, CharacterReader r) { if (r.isEmpty()) { t.eofError(this); t.emit("</"); t.transition(Data); } else if (r.matchesLetter()) { t.createTagPending(false); t.transition(TagName); } else if (r.matches('>')) { t.error(this); t.advanceTransition(Data); } else { t.error(this); t.advanceTransition(BogusComment); } } }, TagName { // from < or </ in data, will have start or end tag pending void read(Tokeniser t, CharacterReader r) { // previous TagOpen state did NOT consume, will have a letter char in current String tagName = r.consumeToAny('\t', '\n', '\f', ' ', '/', '>', nullChar).toLowerCase(); t.tagPending.appendTagName(tagName); switch (r.consume()) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeAttributeName); break; case '/': t.transition(SelfClosingStartTag); break; case '>': t.emitTagPending(); t.transition(Data); break; case nullChar: // replacement t.tagPending.appendTagName(replacementStr); break; case eof: // should emit pending tag? t.eofError(this); t.transition(Data); // no default, as covered with above consumeToAny } } }, RcdataLessthanSign { // from < in rcdata void read(Tokeniser t, CharacterReader r) { if (r.matches('/')) { t.createTempBuffer(); t.advanceTransition(RCDATAEndTagOpen); } else if (r.matchesLetter() && !r.containsIgnoreCase("</" + t.appropriateEndTagName())) { // diverge from spec: got a start tag, but there's no appropriate end tag (</title>), so rather than // consuming to EOF; break out here t.tagPending = new Token.EndTag(t.appropriateEndTagName()); t.emitTagPending(); r.unconsume(); // undo "<" t.transition(Data); } else { t.emit("<"); t.transition(Rcdata); } } }, RCDATAEndTagOpen { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { t.createTagPending(false); t.tagPending.appendTagName(Character.toLowerCase(r.current())); t.dataBuffer.append(Character.toLowerCase(r.current())); t.advanceTransition(RCDATAEndTagName); } else { t.emit("</"); t.transition(Rcdata); } } }, RCDATAEndTagName { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.tagPending.appendTagName(name.toLowerCase()); t.dataBuffer.append(name); return; } char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': if (t.isAppropriateEndTagToken()) t.transition(BeforeAttributeName); else anythingElse(t, r); break; case '/': if (t.isAppropriateEndTagToken()) t.transition(SelfClosingStartTag); else anythingElse(t, r); break; case '>': if (t.isAppropriateEndTagToken()) { t.emitTagPending(); t.transition(Data); } else anythingElse(t, r); break; default: anythingElse(t, r); } } private void anythingElse(Tokeniser t, CharacterReader r) { t.emit("</" + t.dataBuffer.toString()); t.transition(Rcdata); } }, RawtextLessthanSign { void read(Tokeniser t, CharacterReader r) { if (r.matches('/')) { t.createTempBuffer(); t.advanceTransition(RawtextEndTagOpen); } else { t.emit('<'); t.transition(Rawtext); } } }, RawtextEndTagOpen { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { t.createTagPending(false); t.transition(RawtextEndTagName); } else { t.emit("</"); t.transition(Rawtext); } } }, RawtextEndTagName { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.tagPending.appendTagName(name.toLowerCase()); t.dataBuffer.append(name); return; } if (t.isAppropriateEndTagToken() && !r.isEmpty()) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeAttributeName); break; case '/': t.transition(SelfClosingStartTag); break; case '>': t.emitTagPending(); t.transition(Data); break; default: t.dataBuffer.append(c); anythingElse(t, r); } } else anythingElse(t, r); } private void anythingElse(Tokeniser t, CharacterReader r) { t.emit("</" + t.dataBuffer.toString()); t.transition(Rawtext); } }, ScriptDataLessthanSign { void read(Tokeniser t, CharacterReader r) { switch (r.consume()) { case '/': t.createTempBuffer(); t.transition(ScriptDataEndTagOpen); break; case '!': t.emit("<!"); t.transition(ScriptDataEscapeStart); break; default: t.emit("<"); r.unconsume(); t.transition(ScriptData); } } }, ScriptDataEndTagOpen { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { t.createTagPending(false); t.transition(ScriptDataEndTagName); } else { t.emit("</"); t.transition(ScriptData); } } }, ScriptDataEndTagName { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.tagPending.appendTagName(name.toLowerCase()); t.dataBuffer.append(name); return; } if (t.isAppropriateEndTagToken() && !r.isEmpty()) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeAttributeName); break; case '/': t.transition(SelfClosingStartTag); break; case '>': t.emitTagPending(); t.transition(Data); break; default: t.dataBuffer.append(c); anythingElse(t, r); } } else { anythingElse(t, r); } } private void anythingElse(Tokeniser t, CharacterReader r) { t.emit("</" + t.dataBuffer.toString()); t.transition(ScriptData); } }, ScriptDataEscapeStart { void read(Tokeniser t, CharacterReader r) { if (r.matches('-')) { t.emit('-'); t.advanceTransition(ScriptDataEscapeStartDash); } else { t.transition(ScriptData); } } }, ScriptDataEscapeStartDash { void read(Tokeniser t, CharacterReader r) { if (r.matches('-')) { t.emit('-'); t.advanceTransition(ScriptDataEscapedDashDash); } else { t.transition(ScriptData); } } }, ScriptDataEscaped { void read(Tokeniser t, CharacterReader r) { if (r.isEmpty()) { t.eofError(this); t.transition(Data); return; } switch (r.current()) { case '-': t.emit('-'); t.advanceTransition(ScriptDataEscapedDash); break; case '<': t.advanceTransition(ScriptDataEscapedLessthanSign); break; case nullChar: t.error(this); r.advance(); t.emit(replacementChar); break; default: String data = r.consumeToAny('-', '<', nullChar); t.emit(data); } } }, ScriptDataEscapedDash { void read(Tokeniser t, CharacterReader r) { if (r.isEmpty()) { t.eofError(this); t.transition(Data); return; } char c = r.consume(); switch (c) { case '-': t.emit(c); t.transition(ScriptDataEscapedDashDash); break; case '<': t.transition(ScriptDataEscapedLessthanSign); break; case nullChar: t.error(this); t.emit(replacementChar); t.transition(ScriptDataEscaped); break; default: t.emit(c); t.transition(ScriptDataEscaped); } } }, ScriptDataEscapedDashDash { void read(Tokeniser t, CharacterReader r) { if (r.isEmpty()) { t.eofError(this); t.transition(Data); return; } char c = r.consume(); switch (c) { case '-': t.emit(c); break; case '<': t.transition(ScriptDataEscapedLessthanSign); break; case '>': t.emit(c); t.transition(ScriptData); break; case nullChar: t.error(this); t.emit(replacementChar); t.transition(ScriptDataEscaped); break; default: t.emit(c); t.transition(ScriptDataEscaped); } } }, ScriptDataEscapedLessthanSign { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { t.createTempBuffer(); t.dataBuffer.append(Character.toLowerCase(r.current())); t.emit("<" + r.current()); t.advanceTransition(ScriptDataDoubleEscapeStart); } else if (r.matches('/')) { t.createTempBuffer(); t.advanceTransition(org.jsoup.parser.TokeniserState.DoctypeSystemIdentifier_singleQuoted); } else { t.emit('<'); t.transition(ScriptDataEscaped); } } }, ScriptDataEscapedEndTagOpen { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { t.createTagPending(false); t.tagPending.appendTagName(Character.toLowerCase(r.current())); t.dataBuffer.append(r.current()); t.advanceTransition(ScriptDataEscapedEndTagName); } else { t.emit("</"); t.transition(ScriptDataEscaped); } } }, ScriptDataEscapedEndTagName { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.tagPending.appendTagName(name.toLowerCase()); t.dataBuffer.append(name); r.advance(); return; } if (t.isAppropriateEndTagToken() && !r.isEmpty()) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeAttributeName); break; case '/': t.transition(SelfClosingStartTag); break; case '>': t.emitTagPending(); t.transition(Data); break; default: t.dataBuffer.append(c); anythingElse(t, r); break; } } else { anythingElse(t, r); } } private void anythingElse(Tokeniser t, CharacterReader r) { t.emit("</" + t.dataBuffer.toString()); t.transition(ScriptDataEscaped); } }, ScriptDataDoubleEscapeStart { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.dataBuffer.append(name.toLowerCase()); t.emit(name); return; } char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': case '/': case '>': if (t.dataBuffer.toString().equals("script")) t.transition(ScriptDataDoubleEscaped); else t.transition(ScriptDataEscaped); t.emit(c); break; default: r.unconsume(); t.transition(ScriptDataEscaped); } } }, ScriptDataDoubleEscaped { void read(Tokeniser t, CharacterReader r) { char c = r.current(); switch (c) { case '-': t.emit(c); t.advanceTransition(ScriptDataDoubleEscapedDash); break; case '<': t.emit(c); t.advanceTransition(ScriptDataDoubleEscapedLessthanSign); break; case nullChar: t.error(this); r.advance(); t.emit(replacementChar); break; case eof: t.eofError(this); t.transition(Data); break; default: String data = r.consumeToAny('-', '<', nullChar); t.emit(data); } } }, ScriptDataDoubleEscapedDash { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '-': t.emit(c); t.transition(ScriptDataDoubleEscapedDashDash); break; case '<': t.emit(c); t.transition(ScriptDataDoubleEscapedLessthanSign); break; case nullChar: t.error(this); t.emit(replacementChar); t.transition(ScriptDataDoubleEscaped); break; case eof: t.eofError(this); t.transition(Data); break; default: t.emit(c); t.transition(ScriptDataDoubleEscaped); } } }, ScriptDataDoubleEscapedDashDash { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '-': t.emit(c); break; case '<': t.emit(c); t.transition(ScriptDataDoubleEscapedLessthanSign); break; case '>': t.emit(c); t.transition(ScriptData); break; case nullChar: t.error(this); t.emit(replacementChar); t.transition(ScriptDataDoubleEscaped); break; case eof: t.eofError(this); t.transition(Data); break; default: t.emit(c); t.transition(ScriptDataDoubleEscaped); } } }, ScriptDataDoubleEscapedLessthanSign { void read(Tokeniser t, CharacterReader r) { if (r.matches('/')) { t.emit('/'); t.createTempBuffer(); t.advanceTransition(ScriptDataDoubleEscapeEnd); } else { t.transition(ScriptDataDoubleEscaped); } } }, ScriptDataDoubleEscapeEnd { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.dataBuffer.append(name.toLowerCase()); t.emit(name); return; } char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': case '/': case '>': if (t.dataBuffer.toString().equals("script")) t.transition(ScriptDataEscaped); else t.transition(ScriptDataDoubleEscaped); t.emit(c); break; default: r.unconsume(); t.transition(ScriptDataDoubleEscaped); } } }, BeforeAttributeName { // from tagname <xxx void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': break; // ignore whitespace case '/': t.transition(SelfClosingStartTag); break; case '>': t.emitTagPending(); t.transition(Data); break; case nullChar: t.error(this); t.tagPending.newAttribute(); r.unconsume(); t.transition(AttributeName); break; case eof: t.eofError(this); t.transition(Data); break; case '"': case '\'': case '<': case '=': t.error(this); t.tagPending.newAttribute(); t.tagPending.appendAttributeName(c); t.transition(AttributeName); break; default: // A-Z, anything else t.tagPending.newAttribute(); r.unconsume(); t.transition(AttributeName); } } }, AttributeName { // from before attribute name void read(Tokeniser t, CharacterReader r) { String name = r.consumeToAny('\t', '\n', '\f', ' ', '/', '=', '>', nullChar, '"', '\'', '<'); t.tagPending.appendAttributeName(name.toLowerCase()); char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(AfterAttributeName); break; case '/': t.transition(SelfClosingStartTag); break; case '=': t.transition(BeforeAttributeValue); break; case '>': t.emitTagPending(); t.transition(Data); break; case nullChar: t.error(this); t.tagPending.appendAttributeName(replacementChar); break; case eof: t.eofError(this); t.transition(Data); break; case '"': case '\'': case '<': t.error(this); t.tagPending.appendAttributeName(c); // no default, as covered in consumeToAny } } }, AfterAttributeName { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': // ignore break; case '/': t.transition(SelfClosingStartTag); break; case '=': t.transition(BeforeAttributeValue); break; case '>': t.emitTagPending(); t.transition(Data); break; case nullChar: t.error(this); t.tagPending.appendAttributeName(replacementChar); t.transition(AttributeName); break; case eof: t.eofError(this); t.transition(Data); break; case '"': case '\'': case '<': t.error(this); t.tagPending.newAttribute(); t.tagPending.appendAttributeName(c); t.transition(AttributeName); break; default: // A-Z, anything else t.tagPending.newAttribute(); r.unconsume(); t.transition(AttributeName); } } }, BeforeAttributeValue { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': // ignore break; case '"': t.transition(AttributeValue_doubleQuoted); break; case '&': r.unconsume(); t.transition(AttributeValue_unquoted); break; case '\'': t.transition(AttributeValue_singleQuoted); break; case nullChar: t.error(this); t.tagPending.appendAttributeValue(replacementChar); t.transition(AttributeValue_unquoted); break; case eof: t.eofError(this); t.transition(Data); break; case '>': t.error(this); t.emitTagPending(); t.transition(Data); break; case '<': case '=': case '`': t.error(this); t.tagPending.appendAttributeValue(c); t.transition(AttributeValue_unquoted); break; default: r.unconsume(); t.transition(AttributeValue_unquoted); } } }, AttributeValue_doubleQuoted { void read(Tokeniser t, CharacterReader r) { String value = r.consumeToAny('"', '&', nullChar); if (value.length() > 0) t.tagPending.appendAttributeValue(value); char c = r.consume(); switch (c) { case '"': t.transition(AfterAttributeValue_quoted); break; case '&': Character ref = t.consumeCharacterReference('"', true); if (ref != null) t.tagPending.appendAttributeValue(ref); else t.tagPending.appendAttributeValue('&'); break; case nullChar: t.error(this); t.tagPending.appendAttributeValue(replacementChar); break; case eof: t.eofError(this); t.transition(Data); break; // no default, handled in consume to any above } } }, AttributeValue_singleQuoted { void read(Tokeniser t, CharacterReader r) { String value = r.consumeToAny('\'', '&', nullChar); if (value.length() > 0) t.tagPending.appendAttributeValue(value); char c = r.consume(); switch (c) { case '\'': t.transition(AfterAttributeValue_quoted); break; case '&': Character ref = t.consumeCharacterReference('\'', true); if (ref != null) t.tagPending.appendAttributeValue(ref); else t.tagPending.appendAttributeValue('&'); break; case nullChar: t.error(this); t.tagPending.appendAttributeValue(replacementChar); break; case eof: t.eofError(this); t.transition(Data); break; // no default, handled in consume to any above } } }, AttributeValue_unquoted { void read(Tokeniser t, CharacterReader r) { String value = r.consumeToAny('\t', '\n', '\f', ' ', '&', '>', nullChar, '"', '\'', '<', '=', '`'); if (value.length() > 0) t.tagPending.appendAttributeValue(value); char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeAttributeName); break; case '&': Character ref = t.consumeCharacterReference('>', true); if (ref != null) t.tagPending.appendAttributeValue(ref); else t.tagPending.appendAttributeValue('&'); break; case '>': t.emitTagPending(); t.transition(Data); break; case nullChar: t.error(this); t.tagPending.appendAttributeValue(replacementChar); break; case eof: t.eofError(this); t.transition(Data); break; case '"': case '\'': case '<': case '=': case '`': t.error(this); t.tagPending.appendAttributeValue(c); break; // no default, handled in consume to any above } } }, // CharacterReferenceInAttributeValue state handled inline AfterAttributeValue_quoted { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeAttributeName); break; case '/': t.transition(SelfClosingStartTag); break; case '>': t.emitTagPending(); t.transition(Data); break; case eof: t.eofError(this); t.transition(Data); break; default: t.error(this); r.unconsume(); t.transition(BeforeAttributeName); } } }, SelfClosingStartTag { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '>': t.tagPending.selfClosing = true; t.emitTagPending(); t.transition(Data); break; case eof: t.eofError(this); t.transition(Data); break; default: t.error(this); t.transition(BeforeAttributeName); } } }, BogusComment { void read(Tokeniser t, CharacterReader r) { // todo: handle bogus comment starting from eof. when does that trigger? // rewind to capture character that lead us here r.unconsume(); Token.Comment comment = new Token.Comment(); comment.data.append(r.consumeTo('>')); // todo: replace nullChar with replaceChar t.emit(comment); t.advanceTransition(Data); } }, MarkupDeclarationOpen { void read(Tokeniser t, CharacterReader r) { if (r.matchConsume("--")) { t.createCommentPending(); t.transition(CommentStart); } else if (r.matchConsumeIgnoreCase("DOCTYPE")) { t.transition(Doctype); } else if (r.matchConsume("[CDATA[")) { // todo: should actually check current namepspace, and only non-html allows cdata. until namespace // is implemented properly, keep handling as cdata //} else if (!t.currentNodeInHtmlNS() && r.matchConsume("[CDATA[")) { t.transition(CdataSection); } else { t.error(this); t.advanceTransition(BogusComment); // advance so this character gets in bogus comment data's rewind } } }, CommentStart { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '-': t.transition(CommentStartDash); break; case nullChar: t.error(this); t.commentPending.data.append(replacementChar); t.transition(Comment); break; case '>': t.error(this); t.emitCommentPending(); t.transition(Data); break; case eof: t.eofError(this); t.emitCommentPending(); t.transition(Data); break; default: t.commentPending.data.append(c); t.transition(Comment); } } }, CommentStartDash { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '-': t.transition(CommentStartDash); break; case nullChar: t.error(this); t.commentPending.data.append(replacementChar); t.transition(Comment); break; case '>': t.error(this); t.emitCommentPending(); t.transition(Data); break; case eof: t.eofError(this); t.emitCommentPending(); t.transition(Data); break; default: t.commentPending.data.append(c); t.transition(Comment); } } }, Comment { void read(Tokeniser t, CharacterReader r) { char c = r.current(); switch (c) { case '-': t.advanceTransition(CommentEndDash); break; case nullChar: t.error(this); r.advance(); t.commentPending.data.append(replacementChar); break; case eof: t.eofError(this); t.emitCommentPending(); t.transition(Data); break; default: t.commentPending.data.append(r.consumeToAny('-', nullChar)); } } }, CommentEndDash { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '-': t.transition(CommentEnd); break; case nullChar: t.error(this); t.commentPending.data.append('-').append(replacementChar); t.transition(Comment); break; case eof: t.eofError(this); t.emitCommentPending(); t.transition(Data); break; default: t.commentPending.data.append('-').append(c); t.transition(Comment); } } }, CommentEnd { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '>': t.emitCommentPending(); t.transition(Data); break; case nullChar: t.error(this); t.commentPending.data.append("--").append(replacementChar); t.transition(Comment); break; case '!': t.error(this); t.transition(CommentEndBang); break; case '-': t.error(this); t.commentPending.data.append('-'); break; case eof: t.eofError(this); t.emitCommentPending(); t.transition(Data); break; default: t.error(this); t.commentPending.data.append("--").append(c); t.transition(Comment); } } }, CommentEndBang { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '-': t.commentPending.data.append("--!"); t.transition(CommentEndDash); break; case '>': t.emitCommentPending(); t.transition(Data); break; case nullChar: t.error(this); t.commentPending.data.append("--!").append(replacementChar); t.transition(Comment); break; case eof: t.eofError(this); t.emitCommentPending(); t.transition(Data); break; default: t.commentPending.data.append("--!").append(c); t.transition(Comment); } } }, Doctype { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeDoctypeName); break; case eof: t.eofError(this); t.createDoctypePending(); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.error(this); t.transition(BeforeDoctypeName); } } }, BeforeDoctypeName { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { t.createDoctypePending(); t.transition(DoctypeName); return; } char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': break; // ignore whitespace case nullChar: t.error(this); t.doctypePending.name.append(replacementChar); t.transition(DoctypeName); break; case eof: t.eofError(this); t.createDoctypePending(); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.createDoctypePending(); t.doctypePending.name.append(c); t.transition(DoctypeName); } } }, DoctypeName { void read(Tokeniser t, CharacterReader r) { if (r.matchesLetter()) { String name = r.consumeLetterSequence(); t.doctypePending.name.append(name.toLowerCase()); return; } char c = r.consume(); switch (c) { case '>': t.emitDoctypePending(); t.transition(Data); break; case '\t': case '\n': case '\f': case ' ': t.transition(AfterDoctypeName); break; case nullChar: t.error(this); t.doctypePending.name.append(replacementChar); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.doctypePending.name.append(c); } } }, AfterDoctypeName { void read(Tokeniser t, CharacterReader r) { if (r.isEmpty()) { t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); return; } if (r.matchesAny('\t', '\n', '\f', ' ')) r.advance(); // ignore whitespace else if (r.matches('>')) { t.emitDoctypePending(); t.advanceTransition(Data); } else if (r.matchConsumeIgnoreCase("PUBLIC")) { t.transition(AfterDoctypePublicKeyword); } else if (r.matchConsumeIgnoreCase("SYSTEM")) { t.transition(AfterDoctypeSystemKeyword); } else { t.error(this); t.doctypePending.forceQuirks = true; t.advanceTransition(BogusDoctype); } } }, AfterDoctypePublicKeyword { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeDoctypePublicIdentifier); break; case '"': t.error(this); // set public id to empty string t.transition(DoctypePublicIdentifier_doubleQuoted); break; case '\'': t.error(this); // set public id to empty string t.transition(DoctypePublicIdentifier_singleQuoted); break; case '>': t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.error(this); t.doctypePending.forceQuirks = true; t.transition(BogusDoctype); } } }, BeforeDoctypePublicIdentifier { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': break; case '"': // set public id to empty string t.transition(DoctypePublicIdentifier_doubleQuoted); break; case '\'': // set public id to empty string t.transition(DoctypePublicIdentifier_singleQuoted); break; case '>': t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.error(this); t.doctypePending.forceQuirks = true; t.transition(BogusDoctype); } } }, DoctypePublicIdentifier_doubleQuoted { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '"': t.transition(AfterDoctypePublicIdentifier); break; case nullChar: t.error(this); t.doctypePending.publicIdentifier.append(replacementChar); break; case '>': t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.doctypePending.publicIdentifier.append(c); } } }, DoctypePublicIdentifier_singleQuoted { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\'': t.transition(AfterDoctypePublicIdentifier); break; case nullChar: t.error(this); t.doctypePending.publicIdentifier.append(replacementChar); break; case '>': t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.doctypePending.publicIdentifier.append(c); } } }, AfterDoctypePublicIdentifier { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BetweenDoctypePublicAndSystemIdentifiers); break; case '>': t.emitDoctypePending(); t.transition(Data); break; case '"': t.error(this); // system id empty t.transition(DoctypeSystemIdentifier_doubleQuoted); break; case '\'': t.error(this); // system id empty t.transition(DoctypeSystemIdentifier_singleQuoted); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.error(this); t.doctypePending.forceQuirks = true; t.transition(BogusDoctype); } } }, BetweenDoctypePublicAndSystemIdentifiers { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': break; case '>': t.emitDoctypePending(); t.transition(Data); break; case '"': t.error(this); // system id empty t.transition(DoctypeSystemIdentifier_doubleQuoted); break; case '\'': t.error(this); // system id empty t.transition(DoctypeSystemIdentifier_singleQuoted); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.error(this); t.doctypePending.forceQuirks = true; t.transition(BogusDoctype); } } }, AfterDoctypeSystemKeyword { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': t.transition(BeforeDoctypeSystemIdentifier); break; case '>': t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; case '"': t.error(this); // system id empty t.transition(DoctypeSystemIdentifier_doubleQuoted); break; case '\'': t.error(this); // system id empty t.transition(DoctypeSystemIdentifier_singleQuoted); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); } } }, BeforeDoctypeSystemIdentifier { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': break; case '"': // set system id to empty string t.transition(DoctypeSystemIdentifier_doubleQuoted); break; case '\'': // set public id to empty string t.transition(DoctypeSystemIdentifier_singleQuoted); break; case '>': t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.error(this); t.doctypePending.forceQuirks = true; t.transition(BogusDoctype); } } }, DoctypeSystemIdentifier_doubleQuoted { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '"': t.transition(AfterDoctypeSystemIdentifier); break; case nullChar: t.error(this); t.doctypePending.systemIdentifier.append(replacementChar); break; case '>': t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.doctypePending.systemIdentifier.append(c); } } }, DoctypeSystemIdentifier_singleQuoted { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\'': t.transition(AfterDoctypeSystemIdentifier); break; case nullChar: t.error(this); t.doctypePending.systemIdentifier.append(replacementChar); break; case '>': t.error(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.doctypePending.systemIdentifier.append(c); } } }, AfterDoctypeSystemIdentifier { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\f': case ' ': break; case '>': t.emitDoctypePending(); t.transition(Data); break; case eof: t.eofError(this); t.doctypePending.forceQuirks = true; t.emitDoctypePending(); t.transition(Data); break; default: t.error(this); t.transition(BogusDoctype); // NOT force quirks } } }, BogusDoctype { void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '>': t.emitDoctypePending(); t.transition(Data); break; case eof: t.emitDoctypePending(); t.transition(Data); break; default: // ignore char break; } } }, CdataSection { void read(Tokeniser t, CharacterReader r) { String data = r.consumeTo("]]>"); t.emit(data); r.matchConsume("]]>"); t.transition(Data); } }; abstract void read(Tokeniser t, CharacterReader r); private static final char nullChar = '\u0000'; private static final char replacementChar = Tokeniser.replacementChar; private static final String replacementStr = String.valueOf(Tokeniser.replacementChar); private static final char eof = CharacterReader.EOF; }
d672d14c6766cf417da6a54b6c26e873e30b4a11
5a90bfc1147e143df82ea9a8a3c6dab99c3dd67b
/CS445_Project1_Client.java
8f93a8f7df820abecac0979ab1f2de0a1386f24e
[ "Apache-2.0" ]
permissive
FightingGinger/Carson-Use-This
4c6a8e41b6d00fdfb5c6a2e877af3755e6ad383c
9ae1c37703a072314bd03449feba1fa177ee8db2
refs/heads/master
2021-01-15T14:59:03.203506
2015-10-19T00:02:20
2015-10-19T00:02:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,515
java
import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; /* CS 445 - Computer Architecture & Organization * File Name: CS445_Project1_Client.java * Project 1 - Due X/XX/XXXX * Instructor: Dr. Dan Grissom * * Name: FirstName LastName * Name: FirstName LastName * Description: Insert your meaningful description for the CS445_Project1_Client client. */ /////////////////////////////////////////////////////////////////////////////// // INSTRUCTIONS: Update the header above with the correct due date, // first/last name(s) and description for this specific project. You should also update // the first/last name below in the "System.out.println" statement at the beginning // of the "main()" method. Failure to do so will result in lost points. DO NOT change // the name of the class or the autograder will give you 0 points. // // COLLABORATION: Students may work alone or with 1 (one) partner. AT NO POINT should you // ever look at the code of your classmate's project OR show your code to help another // classmate. If you need help, please ask your instructor, who is MORE THAN HAPPY to assist // you and point you in the right direction. // // CHEATING: Your projects will be automatically and algorithmically checked for cheating // by the online submission system. These algorithms are very good and will check against // each of your classmate's submissions (in this section and other sections), projects that // have been submitted in the past by previous students at this university and other // universities, as well as content and code found on the internet. In short, if you cheat, // EXPECT TO BE CAUGHT. // // Be aware that being caught for cheating can result in a 0% on the project for you AND the // person that gave their code (it is your responsibility to not share your code, too). By the // course breakdown, this will result in an automatic loss in 15% of your entire course grade. // // The instructor is available for help and there is NO REASON to take the risk in cheating. /////////////////////////////////////////////////////////////////////////////// public class CS445_Project1_Client { public static void main(String[] args) { // Your program should always output your name and the project number. // DO NOT DELETE OR COMMENT OUT. Replace with relevant info. System.out.println("Josh Dubisz & Carson Hall"); System.out.println("CS445 Project 1"); System.out.println(""); // String[][] array = new String [160][4]; // for (String[] row : array) // Arrays.fill(row, "0"); // // System.out.println(Arrays.deepToString(array)); BigEndianMemorySystem mem = new BigEndianMemorySystem(); mem.printRawBytes(); //Reads the next line Scanner in = new Scanner(System.in); System.out.println("enter a string"); String str = in.nextLine(); mem.addData(str, 4, false); mem.printRawBytes(); // str is the input // use the spaces as delimeters /**Carson's Code**/ // int y = 0; // // StringTokenizer newstr = new StringTokenizer(str," "); // while(newstr.hasMoreTokens()){ // // String temp = newstr.nextToken(); // int len = temp.length(); // int fillLine = len % 4; // System.out.println(fillLine); // if(fillLine != 0){ // while(fillLine < 4){ // temp = temp + '$'; // fillLine++; // } // } // System.out.println(temp); // int lines = len/4; // //lines is the amount of lines we need for each word // //array[y][x] // int ch = 0; // int positionOfInput = 0; // // while(y <= lines){ // for(int x = 0; x < 4; x++){ // char c = temp.charAt(positionOfInput); // array[y][x] = Character.toString(c); // positionOfInput++; // } // y++; // } // } // // System.out.println(Arrays.deepToString(array)); /////////////////////////////////////////////////////////////////////// // Your code should go below these comments. // // See the "User Interface Requirements - Details" section (with // steps 1-4, including all sub-steps) of the project description // for a description of the program flow that should be found here. // // When done, your console output should look similar to that seen in the // "User Interface Requirements - Sample Console Input/Output" section of // the project description. } }
46db5d594f2a3027625d4e03d6599a051f418423
0b34a6d866078ab01fd35df6d5d8b088580febb2
/app/src/main/java/fpt/com/virtualoutfitroom/room/database/VOFRDatabase.java
0a5a4b2ff4043932c12524f63dcb5e5a4ea7b726
[]
no_license
chitrung252/MobileReleaseVOFR
9dcc024cb22c8f4c85885e2ebc1765f2158b1b19
4f9e8e4a35a7c440d7b83034b98efdc1551f6ead
refs/heads/master
2020-09-03T08:41:44.959481
2020-05-10T06:36:09
2020-05-10T06:36:09
219,428,649
0
0
null
2020-02-24T02:36:38
2019-11-04T06:01:27
Java
UTF-8
Java
false
false
1,307
java
package fpt.com.virtualoutfitroom.room.database; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.content.Context; import fpt.com.virtualoutfitroom.room.AccountItemEntities; import fpt.com.virtualoutfitroom.room.OrderItemEntities; import fpt.com.virtualoutfitroom.room.dao.AccountDAO; import fpt.com.virtualoutfitroom.room.dao.OrderDAO; @Database(entities = {OrderItemEntities.class, AccountItemEntities.class},exportSchema = false,version = VOFRDatabase.DATABASE_VERSION) public abstract class VOFRDatabase extends RoomDatabase { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "VOFR-database"; private static VOFRDatabase INSTANCE; public abstract OrderDAO orderDAO(); public abstract AccountDAO accountDao(); public static VOFRDatabase getDatabase(final Context context) { if (INSTANCE == null) { synchronized (VOFRDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), VOFRDatabase.class, DATABASE_NAME) .build(); } } } return INSTANCE; } }
042b65e0f6b54790ebbb89197e0ec21d73e95e7f
26b7f30c6640b8017a06786e4a2414ad8a4d71dd
/src/number_of_direct_superinterfaces/i55443.java
b45512723bd23e7d0541a21dc80fa4d31e7b18ed
[]
no_license
vincentclee/jvm-limits
b72a2f2dcc18caa458f1e77924221d585f23316b
2fd1c26d1f7984ea8163bc103ad14b6d72282281
refs/heads/master
2020-05-18T11:18:41.711400
2014-09-14T04:25:18
2014-09-14T04:25:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
69
java
package number_of_direct_superinterfaces; public interface i55443 {}
c70b160543353c4300f7a9423d3c379982a83c43
0ed256d41f02ac3110e57b2de4bb46dcea214699
/ecsite/src/main/java/jp/co/internous/ecsite/model/form/Cart.java
8a6a403700566bdc2d9390d1e8013a29684d14e5
[]
no_license
HirofumiSomeya/ecsite
d9bcea3383b7747580f8b486d82a5aa929d5466c
6f2dadbca1ac9cf9abf98f54d72946254457c4e4
refs/heads/master
2023-07-05T23:08:32.071711
2021-08-14T12:31:45
2021-08-14T12:31:45
395,858,379
0
0
null
null
null
null
UTF-8
Java
false
false
705
java
package jp.co.internous.ecsite.model.form; import java.io.Serializable; public class Cart implements Serializable { private static final long serialVersioonUID = 1L; private long id; private String goodsName; private long price; private long count; public long getId() { return id; } public void setId(long id) { this.id=id; } public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName=goodsName; } public long getPrice() { return price; } public void setPrice(long price) { this.price=price; } public long getCount() { return count; } public void setCount(long count) { this.count=count; } }
8b426f0f831f741d7b6737920dc1bcc430d40c63
1c8db0988dc681abdafce766796af2acbfd66a04
/src/main/java/com/lennie/cse/repositoryImpl/InformationDAOImpl.java
481f10efa0a068dd12a80db369a177cf044a82ae
[]
no_license
lennie-li/hello-java
7ac6e6e1f241396a979c626f6a3830fe5b9cd4c6
cdddaa55a86a139424ce905e552760e6c636885f
refs/heads/master
2020-04-16T22:02:00.286110
2019-01-16T01:19:33
2019-01-16T01:19:33
165,949,703
0
0
null
null
null
null
UTF-8
Java
false
false
2,072
java
package com.lennie.cse.repositoryImpl; import com.lennie.cse.model.Information; import com.lennie.cse.repository.InformationDAO; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.springframework.stereotype.Repository; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static com.lennie.cse.common.MyUtils.getDataSource; @Repository("InformationDAOImpl") public class InformationDAOImpl implements InformationDAO { @Override public List<Information> findAll() throws SQLException { QueryRunner queryRunner = new QueryRunner(getDataSource()); List<Information> informationList = queryRunner.query("select * from information_release", new ResultSetHandler<List<Information>>() { public List<Information> handle(ResultSet resultSet) throws SQLException { List<Information> informationList = new ArrayList<Information>(); Information information = new Information(); while (resultSet.next()) { int id = resultSet.getInt("id"); String title = resultSet.getString("title"); String content = resultSet.getString("content"); String creater = resultSet.getString("creater"); Date datetime = resultSet.getDate("datetime"); information.setContent(content); information.setId(id); information.setTitle(title); information.setCreater(creater); information.setDatetime(datetime); informationList.add(information); } return informationList; } }); return informationList; } @Override public int update() { return 0; } @Override public int insert() { return 0; } @Override public int delete() { return 0; } }
d46f1f01805be7dbc82940f9c10eff80d2250142
e112ee9fba8cfcf368217277dfc25b976026a232
/modules/implementation-script/src/main/java/org/apache/tuscany/sca/implementation/script/impl/ScriptImplementationImpl.java
a610e77147679542a7a358f1ed9affce621bf19f
[ "BSD-3-Clause", "Apache-2.0", "W3C-19980720", "W3C", "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
apache/tuscany-sca-2.x
3ea2dc984b980d925ac835b6ac0dfcd4541f94b6
89f2d366d4b0869a4e42ff265ccf4503dda4dc8b
refs/heads/trunk
2023-09-01T06:21:08.318064
2013-09-10T16:50:53
2013-09-10T16:50:53
390,004
19
22
Apache-2.0
2023-08-29T21:33:50
2009-11-30T09:00:10
Java
UTF-8
Java
false
false
3,144
java
/* * 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.tuscany.sca.implementation.script.impl; import javax.xml.namespace.QName; import org.apache.tuscany.sca.assembly.Base; import org.apache.tuscany.sca.assembly.impl.ImplementationImpl; import org.apache.tuscany.sca.implementation.script.ScriptImplementation; /** * Represents a Script implementation. * * @version $Rev$ $Date$ */ public class ScriptImplementationImpl extends ImplementationImpl implements ScriptImplementation { public static final QName TYPE = new QName(Base.SCA11_TUSCANY_NS, "implementation.script"); private String script; // Relative URI to the script private String language; // Scripting lang private String location; // Resolved location of the script public ScriptImplementationImpl() { super(TYPE); } public String getScript() { return script; } public void setScript(String script) { this.script = script; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public void setLanguage(String language) { this.language = language; } public String getLanguage() { return language; } @Override public String toString() { return "Script : " + getScript(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((language == null) ? 0 : language.hashCode()); result = prime * result + ((script == null) ? 0 : script.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ScriptImplementationImpl other = (ScriptImplementationImpl)obj; if (language == null) { if (other.language != null) return false; } else if (!language.equals(other.language)) return false; if (script == null) { if (other.script != null) return false; } else if (!script.equals(other.script)) return false; return true; } }
07741d831ecc676f1b7b0c9062009735a01d3b6d
fa93c9be2923e697fb8a2066f8fb65c7718cdec7
/sources/u6/a/b.java
db730e6ab59b0089cd71b87b3c5900dc5cfea41f
[]
no_license
Auch-Auch/avito_source
b6c9f4b0e5c977b36d5fbc88c52f23ff908b7f8b
76fdcc5b7e036c57ecc193e790b0582481768cdc
refs/heads/master
2023-05-06T01:32:43.014668
2021-05-25T10:19:22
2021-05-25T10:19:22
370,650,685
0
0
null
null
null
null
UTF-8
Java
false
false
6,398
java
package u6.a; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import kotlin.Result; import kotlin.Unit; import kotlin.coroutines.Continuation; import kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt; import kotlin.coroutines.jvm.internal.Boxing; import kotlin.coroutines.jvm.internal.DebugProbesKt; import kotlin.jvm.internal.Intrinsics; import kotlinx.coroutines.CancelHandler; import kotlinx.coroutines.CancellableContinuation; import kotlinx.coroutines.CancellableContinuationImpl; import kotlinx.coroutines.Deferred; import kotlinx.coroutines.DisposableHandle; import kotlinx.coroutines.Job; import kotlinx.coroutines.JobNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class b<T> { public static final AtomicIntegerFieldUpdater b = AtomicIntegerFieldUpdater.newUpdater(b.class, "notCompletedCount"); public final Deferred<T>[] a; public volatile int notCompletedCount; public final class a extends JobNode<Job> { public volatile Object _disposer = null; @NotNull public DisposableHandle d; public final CancellableContinuation<List<? extends T>> e; /* JADX DEBUG: Multi-variable search result rejected for r2v0, resolved type: kotlinx.coroutines.CancellableContinuation<? super java.util.List<? extends T>> */ /* JADX WARN: Multi-variable type inference failed */ public a(@NotNull CancellableContinuation<? super List<? extends T>> cancellableContinuation, @NotNull Job job) { super(job); this.e = cancellableContinuation; } /* Return type fixed from 'java.lang.Object' to match base method */ /* JADX DEBUG: Method arguments types fixed to match base method, original types: [java.lang.Object] */ @Override // kotlin.jvm.functions.Function1 public /* bridge */ /* synthetic */ Unit invoke(Throwable th) { invoke(th); return Unit.INSTANCE; } /* JADX DEBUG: Multi-variable search result rejected for r0v0, resolved type: java.util.concurrent.atomic.AtomicIntegerFieldUpdater */ /* JADX WARN: Multi-variable type inference failed */ @Override // kotlinx.coroutines.CompletionHandlerBase public void invoke(@Nullable Throwable th) { if (th != null) { Object tryResumeWithException = this.e.tryResumeWithException(th); if (tryResumeWithException != null) { this.e.completeResume(tryResumeWithException); C0687b bVar = (C0687b) this._disposer; if (bVar != null) { bVar.a(); return; } return; } return; } if (b.b.decrementAndGet(b.this) == 0) { CancellableContinuation<List<? extends T>> cancellableContinuation = this.e; Deferred<T>[] deferredArr = b.this.a; ArrayList arrayList = new ArrayList(deferredArr.length); for (Deferred<T> deferred : deferredArr) { arrayList.add(deferred.getCompleted()); } Result.Companion companion = Result.Companion; cancellableContinuation.resumeWith(Result.m242constructorimpl(arrayList)); } } } /* JADX DEBUG: Multi-variable search result rejected for r1v0, resolved type: kotlinx.coroutines.Deferred<? extends T>[] */ /* JADX WARN: Multi-variable type inference failed */ public b(@NotNull Deferred<? extends T>[] deferredArr) { this.a = deferredArr; this.notCompletedCount = deferredArr.length; } @Nullable public final Object a(@NotNull Continuation<? super List<? extends T>> continuation) { CancellableContinuationImpl cancellableContinuationImpl = new CancellableContinuationImpl(IntrinsicsKt__IntrinsicsJvmKt.intercepted(continuation), 1); cancellableContinuationImpl.initCancellability(); int length = this.a.length; a[] aVarArr = new a[length]; for (int i = 0; i < length; i++) { Deferred<T> deferred = this.a[Boxing.boxInt(i).intValue()]; deferred.start(); a aVar = new a(cancellableContinuationImpl, deferred); aVar.d = deferred.invokeOnCompletion(aVar); aVarArr[i] = aVar; } C0687b bVar = new C0687b(this, aVarArr); for (int i2 = 0; i2 < length; i2++) { aVarArr[i2]._disposer = bVar; } if (cancellableContinuationImpl.isCompleted()) { bVar.a(); } else { cancellableContinuationImpl.invokeOnCancellation(bVar); } Object result = cancellableContinuationImpl.getResult(); if (result == t6.p.a.a.getCOROUTINE_SUSPENDED()) { DebugProbesKt.probeCoroutineSuspended(continuation); } return result; } /* renamed from: u6.a.b$b reason: collision with other inner class name */ public final class C0687b extends CancelHandler { public final b<T>.a[] a; public C0687b(@NotNull b bVar, b<T>.a[] aVarArr) { this.a = aVarArr; } public final void a() { for (b<T>.a aVar : this.a) { DisposableHandle disposableHandle = aVar.d; if (disposableHandle == null) { Intrinsics.throwUninitializedPropertyAccessException("handle"); } disposableHandle.dispose(); } } /* Return type fixed from 'java.lang.Object' to match base method */ /* JADX DEBUG: Method arguments types fixed to match base method, original types: [java.lang.Object] */ @Override // kotlin.jvm.functions.Function1 public Unit invoke(Throwable th) { a(); return Unit.INSTANCE; } @NotNull public String toString() { StringBuilder L = a2.b.a.a.a.L("DisposeHandlersOnCancel["); L.append(this.a); L.append(']'); return L.toString(); } @Override // kotlinx.coroutines.CancelHandlerBase public void invoke(@Nullable Throwable th) { a(); } } }
a29524e596e86bff8156dbbef79a415ec6a5eea5
1f19aec2ecfd756934898cf0ad2758ee18d9eca2
/u-1/u-11/u-11-111/u-11-111-1112/u-11-111-1112-11113-111111/u-11-111-1112-11113-111111-f1527.java
188bbdc4a85897969465a7fab2ebf3b48bfcb44b
[]
no_license
apertureatf/perftest
f6c6e69efad59265197f43af5072aa7af8393a34
584257a0c1ada22e5486052c11395858a87b20d5
refs/heads/master
2020-06-07T17:52:51.172890
2019-06-21T18:53:01
2019-06-21T18:53:01
193,039,805
0
0
null
null
null
null
UTF-8
Java
false
false
106
java
mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117 3814552702307
372fecbbfd9f10f01f3321174c17cf3c6269c19c
fe84169d6a1b66884aa8a4baf8609fa3eb0625e6
/app/src/main/java/com/spring/start/springProjekt/user/UserService.java
72281be4ecffde5790e3d21f1452270d7c0dd743
[]
no_license
EwaGrabowska/SpringProjekt
f2e0ce2657bbc06f48485aa39decf81d62bd397d
e4eadf3bcf8544d3d6a800187b2181038e537968
refs/heads/main
2023-03-01T06:11:22.776406
2023-02-16T17:12:14
2023-02-16T17:12:14
328,454,890
0
0
null
null
null
null
UTF-8
Java
false
false
723
java
package com.spring.start.springProjekt.user; import com.spring.start.springProjekt.netcdfFfile.vo.ArgoFileEvent; import com.spring.start.springProjekt.user.DTO.UserDTO; import org.springframework.transaction.annotation.Transactional; interface UserService { UserDTO findUserByEmail(String email); void saveNewUser(UserDTO user, String roleName); void updateUserPassword(String newPassword, String email); void updateUserProfile(String newName, String newLastName, String newEmail, int id); void updateUserActivation(int activeCode, String activationCode); UserDTO findUserById(int id); void addEvent(ArgoFileEvent argoFileEvent); @Transactional int deleteUser(String email); }
f5808d953f66f52b8c77aea105d8da77bca9e810
9a47c430a1ff9b91a0bf64621fd19081a586ce68
/GreenLadle/src/exousia/greenladlemain/DishDetail.java
0189dcbfdeaa9caff63eb8ffd8a7222316d4e624
[]
no_license
EX-AK/EclipseProject
8bf67f41e5bfb07e1b6df96db590484f5aa01ed6
d423d4b54441c54162d00a592c819748fd4d47e3
refs/heads/master
2021-01-10T17:08:08.505023
2016-03-01T04:21:42
2016-03-01T04:21:42
52,847,672
1
0
null
null
null
null
UTF-8
Java
false
false
845
java
package exousia.greenladlemain; public class DishDetail { private String dishName; private int dishCount=1; private int _id; private String wheatOrWhite; private int mealFor2Or4; public void setDishName(String dishName) { this.dishName=dishName; } public String getDishName() { return dishName; } public void setDishCount(int dishCount) { this.dishCount=dishCount; } public int getDishCount() { return dishCount; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public String getWheatOrWhite() { return wheatOrWhite; } public void setWheatOrWhite(String wheatOrWhite) { this.wheatOrWhite = wheatOrWhite; } public int getMealFor2Or4() { return mealFor2Or4; } public void setMealFor2Or4(int mealFor2Or4) { this.mealFor2Or4 = mealFor2Or4; } }
e55c000b41d2a81a4f247daf47fd9529ab65f398
62510fa67d0ca78082109a861b6948206252c885
/hihope_neptune-oh_hid/00_src/v0.1/third_party/icu/ohos_icu4j/src/main/java/ohos/global/icu/text/EscapeTransliterator.java
c3986435ee54254c4378b6dd56a385d28ac0f46c
[ "LicenseRef-scancode-unicode", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "ICU", "Apache-2.0" ]
permissive
dawmlight/vendor_oh_fun
a869e7efb761e54a62f509b25921e019e237219b
bc9fb50920f06cd4c27399f60076f5793043c77d
refs/heads/master
2023-08-05T09:25:33.485332
2021-09-10T10:57:48
2021-09-10T10:57:48
406,236,565
1
0
null
null
null
null
UTF-8
Java
false
false
9,509
java
/* GENERATED SOURCE. DO NOT MODIFY. */ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* ********************************************************************** * Copyright (c) 2001-2011, International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * Date Name Description * 11/19/2001 aliu Creation. ********************************************************************** */ package ohos.global.icu.text; import ohos.global.icu.impl.Utility; /** * A transliterator that converts Unicode characters to an escape * form. Examples of escape forms are "U+4E01" and "&#x10FFFF;". * Escape forms have a prefix and suffix, either of which may be * empty, a radix, typically 16 or 10, a minimum digit count, * typically 1, 4, or 8, and a boolean that specifies whether * supplemental characters are handled as 32-bit code points or as two * 16-bit code units. Most escape forms handle 32-bit code points, * but some, such as the Java form, intentionally break them into two * surrogate pairs, for backward compatibility. * * <p>Some escape forms actually have two different patterns, one for * BMP characters (0..FFFF) and one for supplements (>FFFF). To * handle this, a second EscapeTransliterator may be defined that * specifies the pattern to be produced for supplementals. An example * of a form that requires this is the C form, which uses "\\uFFFF" * for BMP characters and "\\U0010FFFF" for supplementals. * * <p>This class is package private. It registers several standard * variants with the system which are then accessed via their IDs. * * @author Alan Liu */ class EscapeTransliterator extends Transliterator { /** * The prefix of the escape form; may be empty, but usually isn't. * May not be null. */ private String prefix; /** * The prefix of the escape form; often empty. May not be null. */ private String suffix; /** * The radix to display the number in. Typically 16 or 10. Must * be in the range 2 to 36. */ private int radix; /** * The minimum number of digits. Typically 1, 4, or 8. Values * less than 1 are equivalent to 1. */ private int minDigits; /** * If true, supplementals are handled as 32-bit code points. If * false, they are handled as two 16-bit code units. */ private boolean grokSupplementals; /** * The form to be used for supplementals. If this is null then * the same form is used for BMP characters and supplementals. If * this is not null and if grokSupplementals is true then the * prefix, suffix, radix, and minDigits of this object are used * for supplementals. */ private EscapeTransliterator supplementalHandler; /** * Registers standard variants with the system. Called by * Transliterator during initialization. */ static void register() { // Unicode: "U+10FFFF" hex, min=4, max=6 Transliterator.registerFactory("Any-Hex/Unicode", new Transliterator.Factory() { @Override public Transliterator getInstance(String ID) { return new EscapeTransliterator("Any-Hex/Unicode", "U+", "", 16, 4, true, null); } }); // Java: "\\uFFFF" hex, min=4, max=4 Transliterator.registerFactory("Any-Hex/Java", new Transliterator.Factory() { @Override public Transliterator getInstance(String ID) { return new EscapeTransliterator("Any-Hex/Java", "\\u", "", 16, 4, false, null); } }); // C: "\\uFFFF" hex, min=4, max=4; \\U0010FFFF hex, min=8, max=8 Transliterator.registerFactory("Any-Hex/C", new Transliterator.Factory() { @Override public Transliterator getInstance(String ID) { return new EscapeTransliterator("Any-Hex/C", "\\u", "", 16, 4, true, new EscapeTransliterator("", "\\U", "", 16, 8, true, null)); } }); // XML: "&#x10FFFF;" hex, min=1, max=6 Transliterator.registerFactory("Any-Hex/XML", new Transliterator.Factory() { @Override public Transliterator getInstance(String ID) { return new EscapeTransliterator("Any-Hex/XML", "&#x", ";", 16, 1, true, null); } }); // XML10: "&1114111;" dec, min=1, max=7 (not really "Any-Hex") Transliterator.registerFactory("Any-Hex/XML10", new Transliterator.Factory() { @Override public Transliterator getInstance(String ID) { return new EscapeTransliterator("Any-Hex/XML10", "&#", ";", 10, 1, true, null); } }); // Perl: "\\x{263A}" hex, min=1, max=6 Transliterator.registerFactory("Any-Hex/Perl", new Transliterator.Factory() { @Override public Transliterator getInstance(String ID) { return new EscapeTransliterator("Any-Hex/Perl", "\\x{", "}", 16, 1, true, null); } }); // Plain: "FFFF" hex, min=4, max=6 Transliterator.registerFactory("Any-Hex/Plain", new Transliterator.Factory() { @Override public Transliterator getInstance(String ID) { return new EscapeTransliterator("Any-Hex/Plain", "", "", 16, 4, true, null); } }); // Generic Transliterator.registerFactory("Any-Hex", new Transliterator.Factory() { @Override public Transliterator getInstance(String ID) { return new EscapeTransliterator("Any-Hex", "\\u", "", 16, 4, false, null); } }); } /** * Constructs an escape transliterator with the given ID and * parameters. See the class member documentation for details. */ EscapeTransliterator(String ID, String prefix, String suffix, int radix, int minDigits, boolean grokSupplementals, EscapeTransliterator supplementalHandler) { super(ID, null); this.prefix = prefix; this.suffix = suffix; this.radix = radix; this.minDigits = minDigits; this.grokSupplementals = grokSupplementals; this.supplementalHandler = supplementalHandler; } /** * Implements {@link Transliterator#handleTransliterate}. */ @Override protected void handleTransliterate(Replaceable text, Position pos, boolean incremental) { int start = pos.start; int limit = pos.limit; StringBuilder buf = new StringBuilder(prefix); int prefixLen = prefix.length(); boolean redoPrefix = false; while (start < limit) { int c = grokSupplementals ? text.char32At(start) : text.charAt(start); int charLen = grokSupplementals ? UTF16.getCharCount(c) : 1; if ((c & 0xFFFF0000) != 0 && supplementalHandler != null) { buf.setLength(0); buf.append(supplementalHandler.prefix); Utility.appendNumber(buf, c, supplementalHandler.radix, supplementalHandler.minDigits); buf.append(supplementalHandler.suffix); redoPrefix = true; } else { if (redoPrefix) { buf.setLength(0); buf.append(prefix); redoPrefix = false; } else { buf.setLength(prefixLen); } Utility.appendNumber(buf, c, radix, minDigits); buf.append(suffix); } text.replace(start, start + charLen, buf.toString()); start += buf.length(); limit += buf.length() - charLen; } pos.contextLimit += limit - pos.limit; pos.limit = limit; pos.start = start; } /* (non-Javadoc) * @see ohos.global.icu.text.Transliterator#addSourceTargetSet(ohos.global.icu.text.UnicodeSet, ohos.global.icu.text.UnicodeSet, ohos.global.icu.text.UnicodeSet) */ @Override public void addSourceTargetSet(UnicodeSet inputFilter, UnicodeSet sourceSet, UnicodeSet targetSet) { sourceSet.addAll(getFilterAsUnicodeSet(inputFilter)); for (EscapeTransliterator it = this; it != null ; it = it.supplementalHandler) { if (inputFilter.size() != 0) { targetSet.addAll(it.prefix); targetSet.addAll(it.suffix); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < it.radix; ++i) { Utility.appendNumber(buffer, i, it.radix, it.minDigits); } targetSet.addAll(buffer.toString()); // TODO drop once String is changed to CharSequence in UnicodeSet } } } }
8e2253a424d4aa2127a6bd0b84108fafb01a8881
648f22cd3b57ad176a841b594567107995b77897
/ApplyMaskRegex/src/solver/Doc.java
7cc361125d2abc7220989765e0399fa7d964d705
[]
no_license
chrislucas/kotlin-regex-samples
f26e9354c729f48f5995166ed9d3b24ba36df38c
3ac1246b4258fb4fbfa898b860011dab3a40ed2b
refs/heads/master
2020-05-17T15:46:10.850676
2020-05-15T20:29:31
2020-05-15T20:29:31
183,800,712
0
0
null
null
null
null
UTF-8
Java
false
false
585
java
package solver; import java.util.regex.Pattern; import static java.lang.System.*; public class Doc { private static String aplicarFormatacao(String doc) { if (doc.length() == 11) { return doc.replaceAll("(\\d{3})(\\d{3})(\\d{3})(\\d{2})", "$1.$2.$3-$4"); } else { return doc.replaceFirst("(\\d{2,3})(\\d{3})(\\d{3})(\\d{4})(\\d{2})", "$1.$2.$3/$4-$5"); } } public static void main(String[] args) { out.println(aplicarFormatacao("39714145830")); out.println(aplicarFormatacao("45997418000153")); } }
95056498a977a2b7aa3561acff56fde34625a3a8
f275c71514db10b47ced924021b36608f42150bf
/src/br/ufrn/imd/utravel/dto/VeiculoDTO.java
0268b628c51296f038be85ae3cd5226a88e42b2f
[]
no_license
mrayanealves/utravel-api
4209896b8ce0b211932f2406128f76f77a2c2df2
692b6efa2662b6ba81665e7cb2483df96d685235
refs/heads/master
2020-08-29T18:15:09.441434
2019-11-26T13:20:20
2019-11-26T13:20:20
218,124,338
0
0
null
2019-11-25T19:41:23
2019-10-28T19:04:36
Java
UTF-8
Java
false
false
1,051
java
package br.ufrn.imd.utravel.dto; import br.ufrn.imd.utravel.enums.EnumTipoTransporte; public class VeiculoDTO { private long idVeiculo; private String placa; private String cor; private String modelo; private String marca; private EnumTipoTransporte tipoTransporte; public long getIdVeiculo() { return idVeiculo; } public void setIdVeiculo(long idVeiculo) { this.idVeiculo = idVeiculo; } public String getPlaca() { return placa; } public void setPlaca(String placa) { this.placa = placa; } public String getCor() { return cor; } public void setCor(String cor) { this.cor = cor; } public String getModelo() { return modelo; } public void setModelo(String modelo) { this.modelo = modelo; } public String getMarca() { return marca; } public void setMarca(String marca) { this.marca = marca; } public EnumTipoTransporte getTipoTransporte() { return tipoTransporte; } public void setTipoTransporte(EnumTipoTransporte tipoTransporte) { this.tipoTransporte = tipoTransporte; } }
582e089f8a52d34ade3f05c528ff78f4d909c5ab
f908e8f99d09c24471454f1b9e124063799694dd
/src/main/java/nl/piq/realworldjavaee/domain/AuthenticationProvider.java
cbdea5a57bcc5124ccea622130acdbd04f482127
[]
no_license
pkuijpers/realworld-java-ee
282f9ac358eab7d65ad912c5026d1106d749989b
99ea57836fcbc1d8a231259dedd96a8dabcb13f1
refs/heads/master
2021-04-03T10:25:11.861912
2018-11-16T18:30:10
2018-11-16T18:30:10
125,232,833
1
0
null
null
null
null
UTF-8
Java
false
false
999
java
package nl.piq.realworldjavaee.domain; class AuthenticationProvider { private final UserRepository userRepo; AuthenticationProvider(UserRepository userRepo) { this.userRepo = userRepo; } private User loggedInUser; User login(String username, String password) { User user = userRepo.find(username); if (user != null && user.hasPassword(password)) { this.loggedInUser = user; return user; } throw new UnauthorizedException(); } User registerUser(String username, String email, String password) { User user = new User(username, email, password); userRepo.save(user); return user; } /** * @return the currently logged in user * @throws UnauthorizedException when not logged in */ public User currentUser() { if (loggedInUser == null) { throw new UnauthorizedException("Not logged in"); } return loggedInUser; } }
75558c6e4549f54922b3e229294d79ad1a81e5d7
5afa38d12579305ba9c2db1e448623677f7d1e2d
/app/src/main/java/com/example/tunecloud/PlayMusic.java
dd2f16f9e053f54acc77a5c43fd2d3d7e91191c8
[]
no_license
SamimKamruzzaman/TuneCloud
09294706772f67a5be8f68c7453979510a99ff87
f08cf99ff60013ed9c6ee1551ba6765902048a24
refs/heads/master
2023-02-13T01:03:09.549881
2020-12-30T10:37:55
2020-12-30T10:37:55
325,522,912
0
0
null
null
null
null
UTF-8
Java
false
false
5,713
java
package com.example.tunecloud; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.PorterDuff; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import java.io.File; import java.util.ArrayList; public class PlayMusic extends AppCompatActivity { Button previousButton,pauseButton,nextButton; TextView songnameTextview; SeekBar seekBar; static MediaPlayer mediaPlayer; int position; ArrayList<File> songs; Thread threadSeekBar; String songName; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_music); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setTitle("Now Playing"); previousButton = (Button)findViewById(R.id.previousBtn); pauseButton = (Button)findViewById(R.id.pauseBtn); nextButton = (Button)findViewById(R.id.nextBtn); songnameTextview = (TextView) findViewById(R.id.txtSongLabel); seekBar = (SeekBar)findViewById(R.id.seekBar); threadSeekBar=new Thread(){ @Override public void run() { int duration=mediaPlayer.getDuration(); int position=0; while (position<duration){ try{ sleep(500); position=mediaPlayer.getCurrentPosition(); seekBar.setProgress(position); } catch (InterruptedException e){ e.printStackTrace(); } } } }; if(mediaPlayer != null){ mediaPlayer.stop(); mediaPlayer.release(); } Intent i = getIntent(); Bundle b = i.getExtras(); songs = (ArrayList) b.getParcelableArrayList("songs"); songName = songs.get(position).getName().toString(); String SongName = i.getStringExtra("songname"); songnameTextview.setText(SongName); songnameTextview.setSelected(true); position = b.getInt("pos",0); Uri u = Uri.parse(songs.get(position).toString()); mediaPlayer = MediaPlayer.create(getApplicationContext(),u); mediaPlayer.start(); seekBar.setMax(mediaPlayer.getDuration()); threadSeekBar.start(); seekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY); seekBar.getThumb().setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_IN); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { mediaPlayer.seekTo(seekBar.getProgress()); } }); pauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { seekBar.setMax(mediaPlayer.getDuration()); if(mediaPlayer.isPlaying()){ pauseButton.setBackgroundResource(R.drawable.playred); mediaPlayer.pause(); } else { pauseButton.setBackgroundResource(R.drawable.pausered); mediaPlayer.start(); } } }); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.stop(); mediaPlayer.release(); position=((position+1)%songs.size()); Uri u = Uri.parse(songs.get( position).toString()); // songNameText.setText(getSongName); mediaPlayer = MediaPlayer.create(getApplicationContext(),u); songName = songs.get(position).getName().toString(); songnameTextview.setText(songName); try{ mediaPlayer.start(); }catch(Exception e){} } }); previousButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //songNameText.setText(getSongName); mediaPlayer.stop(); mediaPlayer.release(); position=((position-1)<0)?(songs.size()-1):(position-1); Uri u = Uri.parse(songs.get(position).toString()); mediaPlayer = MediaPlayer.create(getApplicationContext(),u); songName = songs.get(position).getName().toString(); songnameTextview.setText(songName); mediaPlayer.start(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==android.R.id.home){ onBackPressed(); } return super.onOptionsItemSelected(item); } }
3b2e13228276ad4f04848fe66064c55cbacf96b6
06922b9af842db75f2099437a9051c271a7d8896
/SessionManagement/src/model/Product.java
0870a3cf4b6e42422b648c4a27239904041d620f
[]
no_license
myrmidon8000/Servlets
0d01e5b6c7b5681dd496afa102480d0c47f6077a
f91d7aaad0c55a9ebadff66d39932a61db2da1e8
refs/heads/master
2020-04-13T15:07:06.927037
2019-01-04T07:07:40
2019-01-04T07:07:40
163,282,105
1
1
null
null
null
null
UTF-8
Java
false
false
795
java
package model; public class Product { private int prodid; private String prodname; private int rate; public Product() { super(); // TODO Auto-generated constructor stub } public Product(int prodid, String prodname, int rate) { super(); this.prodid = prodid; this.prodname = prodname; this.rate = rate; } @Override public String toString() { return "Product [prodid=" + prodid + ", prodname=" + prodname + ", rate=" + rate + "]"; } public int getProdid() { return prodid; } public void setProdid(int prodid) { this.prodid = prodid; } public String getProdname() { return prodname; } public void setProdname(String prodname) { this.prodname = prodname; } public int getRate() { return rate; } public void setRate(int rate) { this.rate = rate; } }
d9aed0bb81ec373f47b04b36754d8ac6f07c8714
d65d408b75b64929e7f323459cb61779b63d1f5a
/LeetcodeBinarySearch/src/GuessGame.java
9aa89b86012f5d2b1b23245ee1b6c02d18bdbb3f
[]
no_license
AssumptionXiaohan/leetcode
fc4e4311396c79e868e5a518093bc0318b6a2191
69ec4025cbad937c11c95c761f221ea6dcf50810
refs/heads/master
2020-06-05T04:52:49.489265
2019-10-27T07:07:39
2019-10-27T07:07:39
192,319,420
0
0
null
null
null
null
UTF-8
Java
false
false
117
java
/** * Created by 79300 on 2019/10/8. */ public class GuessGame { int guess(int num){ return 0; } }
3e1b1bbcf63ff980831b47de98fa102ccd343266
51155d668c66b286e9786bcf1047251d80fc4bcf
/src/main/java/com/xujialin/Handler/CustomizeAuthenticationSuccessHandler.java
59a4e6362bb4f082d036b6a1d0eedc40e8072058
[]
no_license
Jolly-Xu/ShoppingMall
679a573a6836c1adce0a951b22b0e27029fbc600
128249066856071c9c43da95ac37f2ba4d4fff5a
refs/heads/master
2023-08-28T12:50:47.480831
2021-10-02T03:51:42
2021-10-02T03:51:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,632
java
package com.xujialin.Handler; import com.alibaba.fastjson.JSON; import com.xujialin.CommonReturnResult.ReturnResult; import com.xujialin.CommonReturnResult.ReturnResultCode; import com.xujialin.SafetyVerification.MyUserDetails; import com.xujialin.entity.Userinfo; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author XuJiaLin * @date 2021/9/13 21:56 */ @Slf4j @Component public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { httpServletResponse.setContentType("text/json;charset=utf-8"); MyUserDetails principal = (MyUserDetails)authentication.getPrincipal(); Userinfo user = principal.getUser(); user.setPassword(null); user.setAuthorityId(null); user.setUpdatatime(null); user.setCreatetime(null); user.setIsLogicDelete(null); ReturnResult returnResult = new ReturnResult(ReturnResultCode.LOGIN_SUCCESS.getCode(),true, user); httpServletResponse.getWriter().write(JSON.toJSONString(returnResult)); } }
3989e46871908924d8bd3a67d75f65869b153353
67b49f5204f8f661b9f5ce89d5eb45e25b1cad50
/Sum/Backtrack/Java/Permutation2.java
01b44eff1540b3cc2b5deed802a2b07d8877a9fc
[]
no_license
aaaYaaa2/Algorithm
eb851a201b327ff929687a545ae67848cc50708c
7a34f0854d189b2a699303e72e94b61ab08e37b8
refs/heads/master
2021-06-09T08:59:07.405756
2016-11-19T20:41:30
2016-11-19T20:41:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,130
java
package AlgoFolder; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Solution { public static List<List<Integer>> permute(int[] nums){ List<List<Integer>> fres = new ArrayList<List<Integer>>(); if(nums==null || nums.length==0) return fres; boolean[] flags = new boolean[nums.length]; Arrays.fill(flags, false); Arrays.sort(nums); permuteHelper(nums, new ArrayList<Integer>(), fres, flags ); return fres; } private static void permuteHelper(int[] nums, List<Integer> subres, List<List<Integer>> res, boolean[] flags){ if(subres.size()==nums.length) { res.add(new ArrayList<Integer>(subres)); return; } for(int i=0; i<nums.length; i++){ if(i>0 && nums[i]==nums[i-1] && !flags[i-1]) continue; if(!flags[i]){ subres.add(nums[i]); flags[i] = true; permuteHelper(nums, subres, res, flags); subres.remove(subres.size()-1); flags[i] = false; } } } public static void main(String[] args){ int[] input = {1,2,3}; List<List<Integer>> result = permute(input); System.out.println(result); } }
cc2bb5fef5d8973eb11aae2fc5bc1daf0ad2bac5
5d7e4135a19a3d05a8fd5b7beff19c0f5cb7d738
/app/src/main/java/com/qlckh/purifier/http/exception/ApiException.java
de49f82a44bdd4ff3223be83eedcb4a19ab6458f
[]
no_license
AndyAls/baojieyuan
56765fb2c4b228137303b311fbe228c8218eca37
ce5bb72dd0b74a504acc02e982a768f5fa267be7
refs/heads/master
2020-03-19T05:47:54.289337
2019-09-18T06:28:52
2019-09-18T06:28:52
135,962,800
0
0
null
null
null
null
UTF-8
Java
false
false
4,543
java
package com.qlckh.purifier.http.exception; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializer; import com.google.gson.JsonSyntaxException; import org.apache.http.conn.ConnectTimeoutException; import org.json.JSONException; import java.io.IOException; import java.io.NotSerializableException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.text.ParseException; import retrofit2.HttpException; /** * @author Andy * @date 2018/5/15 18:42 * Desc: ApiException.java */ public class ApiException extends Exception { private final int code; private String message; public ApiException(Throwable throwable, int code) { super(throwable); this.code = code; this.message = throwable.getMessage(); } public int getCode() { return code; } @Override public String getMessage() { return message; } public static ApiException handleException(Throwable e) { ApiException ex; if (e instanceof HttpException) { HttpException httpException = (HttpException) e; ex = new ApiException(httpException, httpException.code()); try { ex.message = httpException.response().errorBody().string(); } catch (IOException e1) { e1.printStackTrace(); ex.message = e1.getMessage(); } return ex; } else if (e instanceof SocketTimeoutException) { ex = new ApiException(e, ERROR.TIMEOUT_ERROR); ex.message = "网络连接超时,请检查您的网络状态,稍后重试!"; return ex; } else if (e instanceof ConnectException) { ex = new ApiException(e, ERROR.TIMEOUT_ERROR); ex.message = "服务器连接异常,稍后重试!"; return ex; } else if (e instanceof ConnectTimeoutException) { ex = new ApiException(e, ERROR.TIMEOUT_ERROR); ex.message = "网络连接超时,请检查您的网络状态,稍后重试!"; return ex; } else if (e instanceof UnknownHostException) { ex = new ApiException(e, ERROR.TIMEOUT_ERROR); ex.message = "网络连接异常,请检查您的网络状态,稍后重试!"; return ex; } else if (e instanceof NullPointerException) { ex = new ApiException(e, ERROR.NULL_POINTER_EXCEPTION); ex.message = "空指针异常"; return ex; } else if (e instanceof javax.net.ssl.SSLHandshakeException) { ex = new ApiException(e, ERROR.SSL_ERROR); ex.message = "证书验证失败"; return ex; } else if (e instanceof ClassCastException) { ex = new ApiException(e, ERROR.CAST_ERROR); ex.message = "类型转换错误"; return ex; } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof JsonSyntaxException || e instanceof JsonSerializer || e instanceof NotSerializableException || e instanceof ParseException) { ex = new ApiException(e, ERROR.PARSE_ERROR); ex.message = "解析错误"; return ex; } else if (e instanceof IllegalStateException) { ex = new ApiException(e, ERROR.ILLEGAL_STATE_ERROR); ex.message = e.getMessage(); return ex; } else { ex = new ApiException(e, ERROR.UNKNOWN); ex.message = "未知错误"; return ex; } } /** * 约定异常 */ public static class ERROR { /** * 未知错误 */ public static final int UNKNOWN = 1000; /** * 连接超时 */ public static final int TIMEOUT_ERROR = 1001; /** * 空指针错误 */ public static final int NULL_POINTER_EXCEPTION = 1002; /** * 证书出错 */ public static final int SSL_ERROR = 1003; /** * 类转换错误 */ public static final int CAST_ERROR = 1004; /** * 解析错误 */ public static final int PARSE_ERROR = 1005; /** * 非法数据异常 */ public static final int ILLEGAL_STATE_ERROR = 1006; } }
cc60dd9f041f4c83615aa78bd369ec58f0ecf2d2
897bb08cdc27dc5631b7f64384808c835360b9ae
/src/main/java/br/com/zupacademy/natalia/mercadolivre/mercadolivre/dto/LoginRequest.java
e5ee919732cd9dad814712c7755a1d58ad01be35
[ "Apache-2.0" ]
permissive
natyff/orange-talents-05-template-mercado-livre
3180b5d351b315226edc8e05b48a47883ff35d68
3632533eae0527e205df7f43083a89fa21280a2a
refs/heads/main
2023-05-09T01:27:05.029160
2021-06-03T00:47:12
2021-06-03T00:47:12
370,774,034
0
0
Apache-2.0
2021-05-25T17:22:01
2021-05-25T17:22:00
null
UTF-8
Java
false
false
496
java
package br.com.zupacademy.natalia.mercadolivre.mercadolivre.dto; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; public class LoginRequest { private String login; private String senha; public String getLogin() { return login; } public String getSenha() { return senha; } public UsernamePasswordAuthenticationToken converter() { return new UsernamePasswordAuthenticationToken(login, senha); } }
f0227a2f9de886fc02109f65a4ba1c4d1e03fc3a
a2156434bb25806c7b23e9404541bcdda6a66fc2
/APS-APIs/src/main/java/se/natusoft/osgi/aps/activator/annotation/Schedule.java
bffad5f496d84e38f41cce86d36464c9041b6873
[ "Apache-2.0" ]
permissive
tombensve/APS
1fcac378f2d1ac1ad1cd34fc4ac7e853ef44b38e
67d6ba32e4598d6649f55c6560303431f06eab02
refs/heads/master
2023-04-28T18:28:23.346965
2023-01-04T17:49:40
2023-01-04T17:49:40
7,192,240
4
1
Apache-2.0
2023-04-15T00:45:35
2012-12-16T16:06:14
Java
UTF-8
Java
false
false
2,231
java
/* * * PROJECT * Name * APS APIs * * Code Version * 1.0.0 * * Description * Provides the APIs for the application platform services. * * COPYRIGHTS * Copyright (C) 2012 by Natusoft AB All rights reserved. * * LICENSE * Apache 2.0 (Open Source) * * 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. * * AUTHORS * Tommy Svensson ([email protected]) * Changes: * 2012-08-19: Created! * */ package se.natusoft.osgi.aps.activator.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.concurrent.TimeUnit; /** * Fields annotated with this should be of type Runnable, and will be scheduled * on an ServiceExecutor whose name matches the name specified in "on=...". */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Schedule { /** * The defined executor service to schedule this on. This should be the name of it. If left blank an internal * ScheduledExecutorService will be used. */ String on() default ""; /** The amount of time to wait for the (first) execution. */ long delay(); /** If specified how long to wait between runs. */ long repeat() default 0; /** The time unit used for the above values. Defaults to seconds. */ TimeUnit timeUnit() default TimeUnit.SECONDS; /** Possibility to affect the size of the thread pool when such is created internally for this (on="..." not provided!). */ int poolSize() default 2; }
1378e56b8b9227c5dc8860be166ce63108e8a30f
59325db5c0f257c836ce2f27c9409a33342ceafc
/StreamsFilesAndDirectories/MergeTwoFiles.java
5b2c5d1382ff748e333b19a67aaec8a162a76f56
[]
no_license
vladimiruzunov/Java-Advanced
c61985011e7ac12900a13645e5727978e9106a20
081bede4979ff34c5f1b83a137358811538beff9
refs/heads/master
2023-04-08T23:21:25.095069
2021-04-14T18:58:58
2021-04-14T18:58:58
337,795,653
0
0
null
null
null
null
UTF-8
Java
false
false
1,208
java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class MergeTwoFiles { private static final String FIRST_INPUT_PATH = "src\\Resources\\inputOne.txt"; private static final String SECOND_INPUT_PATH = "src\\Resources\\inputTwo.txt"; private static final String OUTPUT_PATH = "src\\Resources\\output.txt"; public static void main(String[] args) throws IOException { try (BufferedReader firstReader = new BufferedReader(new FileReader(FIRST_INPUT_PATH)); BufferedReader secondReader = new BufferedReader(new FileReader(SECOND_INPUT_PATH)); PrintWriter writer = new PrintWriter(OUTPUT_PATH)) { String line = firstReader.readLine(); while (line != null){ writer.println(line); line=firstReader.readLine(); } line = secondReader.readLine(); while (line != null){ writer.println(line); line = secondReader.readLine(); } }catch (IOException ioe){ ioe.printStackTrace(); } } }
0d550ee8769720f5d00aed1af69f8cdcda1c58a0
90af8b95923b2bd0bb9c623cb659e089310d338c
/arkspot/src/main/java/com/shanchain/shandata/widgets/pickerimage/utils/AttachmentStore.java
93f8eef00d28f5d9c50aa792bfad14e421ac4433
[]
no_license
ShanChain/AndroidShanchain
80dd77bb2af861bb20aa8ebb1f0a30af9cc87e43
c58a862e1b3c3cb5a552ffc2fe5a621e82df863a
refs/heads/shanchain2.0
2023-07-24T03:33:22.435978
2019-06-10T02:52:14
2019-06-10T02:52:14
149,384,698
0
1
null
2023-07-11T21:14:51
2018-09-19T03:05:13
Java
UTF-8
Java
false
false
9,414
java
package com.shanchain.shandata.widgets.pickerimage.utils; import android.graphics.Bitmap; import android.text.TextUtils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * 用于把附件保存到文件系统中 */ public class AttachmentStore { public static long copy(String srcPath, String dstPath) { if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) { return -1; } File source = new File(srcPath); if (!source.exists()) { return -1; } if (srcPath.equals(dstPath)) { return source.length(); } FileChannel fcin = null; FileChannel fcout = null; try { fcin = new FileInputStream(source).getChannel(); fcout = new FileOutputStream(create(dstPath)).getChannel(); ByteBuffer tmpBuffer = ByteBuffer.allocateDirect(4096); while (fcin.read(tmpBuffer) != -1) { tmpBuffer.flip(); fcout.write(tmpBuffer); tmpBuffer.clear(); } return source.length(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } } catch (IOException e) { e.printStackTrace(); } } return -1; } public static long getFileLength(String srcPath) { if (TextUtils.isEmpty(srcPath)) { return -1; } File srcFile = new File(srcPath); if (!srcFile.exists()) { return -1; } return srcFile.length(); } public static long save(String path, String content) { return save(content.getBytes(), path); } /** * 把数据保存到文件系统中,并且返回其大小 * * @param data * @param filePath * @return 如果保存失败, 则返回-1 */ public static long save(byte[] data, String filePath) { if (TextUtils.isEmpty(filePath)) { return -1; } File f = new File(filePath); if (f.getParentFile() == null) { return -1; } if (!f.getParentFile().exists()) {// 如果不存在上级文件夹 f.getParentFile().mkdirs(); } try { f.createNewFile(); FileOutputStream fout = new FileOutputStream(f); fout.write(data); fout.close(); } catch (IOException e) { e.printStackTrace(); return -1; } return f.length(); } public static boolean move(String srcFilePath, String dstFilePath) { if (TextUtils.isEmpty(srcFilePath) || TextUtils.isEmpty(dstFilePath)) { return false; } File srcFile = new File(srcFilePath); if (!srcFile.exists() || !srcFile.isFile()) { return false; } File dstFile = new File(dstFilePath); if (dstFile.getParentFile() == null) { return false; } if (!dstFile.getParentFile().exists()) {// 如果不存在上级文件夹 dstFile.getParentFile().mkdirs(); } return srcFile.renameTo(dstFile); } public static File create(String filePath) { if (TextUtils.isEmpty(filePath)) { return null; } File f = new File(filePath); if (!f.getParentFile().exists()) {// 如果不存在上级文件夹 f.getParentFile().mkdirs(); } try { boolean newFile = f.createNewFile(); return f; } catch (IOException e) { if (f != null && f.exists()) { f.delete(); } return null; } } /** * @param is * @param filePath * @return 保存失败,返回-1 */ public static long save(InputStream is, String filePath) { File f = new File(filePath); if (!f.getParentFile().exists()) {// 如果不存在上级文件夹 f.getParentFile().mkdirs(); } FileOutputStream fos = null; try { f.createNewFile(); fos = new FileOutputStream(f); int read = 0; byte[] bytes = new byte[8091]; while ((read = is.read(bytes)) != -1) { fos.write(bytes, 0, read); } return f.length(); } catch (IOException e) { if (f != null && f.exists()) { f.delete(); } return -1; } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 把文件从文件系统中读取出来 * * @param path * @return 如果无法读取, 则返回null */ public static byte[] load(String path) { try { File f = new File(path); int unread = (int) f.length(); int read = 0; byte[] buf = new byte[unread]; // 读取文件长度 FileInputStream fin = new FileInputStream(f); do { int count = fin.read(buf, read, unread); read += count; unread -= count; } while (unread != 0); fin.close(); return buf; } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } } public static String loadAsString(String path) { if (isFileExist(path)) { byte[] content = load(path); return new String(content); } else { return null; } } /** * 删除指定路径文件 * * @param path */ public static boolean delete(String path) { if (TextUtils.isEmpty(path)) { return false; } File f = new File(path); if (f.exists()) { f = renameOnDelete(f); return f.delete(); } else { return false; } } public static void deleteOnExit(String path) { if (TextUtils.isEmpty(path)) { return; } File f = new File(path); if (f.exists()) { f.deleteOnExit(); } } public static boolean deleteDir(String path) { return deleteDir(path, true); } private static boolean deleteDir(String path, boolean rename) { boolean success = true; File file = new File(path); if (file.exists()) { if (rename) { file = renameOnDelete(file); } File[] list = file.listFiles(); if (list != null) { int len = list.length; for (int i = 0; i < len; ++i) { if (list[i].isDirectory()) { deleteDir(list[i].getPath(), false); } else { boolean ret = list[i].delete(); if (!ret) { success = false; } } } } } else { success = false; } if (success) { file.delete(); } return success; } // rename before delete to avoid lingering filesystem lock of android private static File renameOnDelete(File file) { String tmpPath = file.getParent() + "/" + System.currentTimeMillis() + "_tmp"; File tmpFile = new File(tmpPath); if (file.renameTo(tmpFile)) { return tmpFile; } else { return file; } } public static boolean isFileExist(String path) { if (!TextUtils.isEmpty(path) && new File(path).exists()) { return true; } else { return false; } } public static boolean saveBitmap(Bitmap bitmap, String path, boolean recyle) { if (bitmap == null || TextUtils.isEmpty(path)) { return false; } BufferedOutputStream bos = null; try { FileOutputStream fos = new FileOutputStream(path); bos = new BufferedOutputStream(fos); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); return true; } catch (FileNotFoundException e) { return false; } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { } } if (recyle) { bitmap.recycle(); } } } }
29fb84234167ca455bfb436aaabf56e6440eb809
0db7d7a7dba705d958c9db5f4e26728fda631950
/app/src/main/java/com/vcontrol/vcontroliot/fragment/CameraFragment.java
f0d027993d9ed88cf7fd180f8db7431ea4609caf
[]
no_license
heybody/vcontrolPT
8273e9eece693ecbf7c4bad0f0affac06f1a1ab0
0a842c13e01dc0867a3f7b3c1d89292be6c9a532
refs/heads/master
2021-10-19T11:10:22.065239
2019-02-20T14:06:40
2019-02-20T14:06:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,201
java
package com.vcontrol.vcontroliot.fragment; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import com.vcontrol.vcontroliot.R; import com.vcontrol.vcontroliot.util.ConfigParams; import com.vcontrol.vcontroliot.util.EventNotifyHelper; import com.vcontrol.vcontroliot.util.SocketUtil; import com.vcontrol.vcontroliot.util.ToastUtil; import com.vcontrol.vcontroliot.util.UiEventEntry; import com.vcontrol.vcontroliot.view.MyRadioGroup; /** * 摄像头 * Created by Vcontrol on 2016/11/23. */ public class CameraFragment extends BaseFragment implements EventNotifyHelper.NotificationCenterDelegate, View.OnClickListener { private Button cameraNumButton; private EditText cameraNumEdittext; private MyRadioGroup companyGroup; private RadioGroup typeGroup; private RadioGroup cameraGroup; private RadioGroup sendModelGroup; @Override public int getLayoutView() { return R.layout.fragment_sensor_camera; } @Override public void onDestroy() { super.onDestroy(); EventNotifyHelper.getInstance().removeObserver(this, UiEventEntry.READ_DATA); } @Override public void initComponentViews(View view) { EventNotifyHelper.getInstance().addObserver(this, UiEventEntry.READ_DATA); final View viewq = view; typeGroup = (RadioGroup) view.findViewById(R.id.type_group); companyGroup = (MyRadioGroup) view.findViewById(R.id.company_group); cameraGroup = (RadioGroup) view.findViewById(R.id.camera_group); sendModelGroup = (RadioGroup) view.findViewById(R.id.send_model_group); cameraNumButton = (Button) view.findViewById(R.id.camera_num_button); cameraNumEdittext = (EditText) view.findViewById(R.id.camera_num_edittext); companyGroup.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(MyRadioGroup group, int checkedId) { View checkView = viewq.findViewById(checkedId); if (!checkView.isPressed()) { return; } String content = ConfigParams.SetCameraManuf; if (checkedId == R.id.company_button) { SocketUtil.getSocketUtil().sendContent(content + "01"); } else if (checkedId == R.id.company_button2) { SocketUtil.getSocketUtil().sendContent(content + "02"); } else if (checkedId == R.id.company_button3) { SocketUtil.getSocketUtil().sendContent(content + "03"); } else if (checkedId == R.id.company_button4) { SocketUtil.getSocketUtil().sendContent(content + "04"); } else if (checkedId == R.id.company_button5) { SocketUtil.getSocketUtil().sendContent(content + "05"); } else if (checkedId == R.id.company_button6) { SocketUtil.getSocketUtil().sendContent(content + "06"); } } }); typeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { View checkView = viewq.findViewById(checkedId); if (!checkView.isPressed()) { return; } String content = ConfigParams.SetCameraType; if (checkedId == R.id.type_button) { SocketUtil.getSocketUtil().sendContent(content + "1"); } else if (checkedId == R.id.type_button2) { SocketUtil.getSocketUtil().sendContent(content + "2"); } else if (checkedId == R.id.type_button3) { SocketUtil.getSocketUtil().sendContent(content + "3"); } } }); sendModelGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { View checkView = viewq.findViewById(checkedId); if (!checkView.isPressed()) { return; } String content = ConfigParams.SetPicSendMode; if (checkedId == R.id.Single_packet_reply_button) { SocketUtil.getSocketUtil().sendContent(content + "1"); } else if (checkedId == R.id.Multi_packet_reply_button) { SocketUtil.getSocketUtil().sendContent(content + "2"); } } }); cameraGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { View checkView = viewq.findViewById(checkedId); if (!checkView.isPressed()) { return; } String content = ConfigParams.SetPIC_Resolution; if (checkedId == R.id.camera_button) { SocketUtil.getSocketUtil().sendContent(content + "0"); } else if (checkedId == R.id.camera_button2) { SocketUtil.getSocketUtil().sendContent(content + "1"); } else if (checkedId == R.id.camera_button3) { SocketUtil.getSocketUtil().sendContent(content + "2"); } } }); } @Override public void initData() { SocketUtil.getSocketUtil().sendContent(ConfigParams.ReadSensorPara2); } @Override public void setListener() { cameraNumButton.setOnClickListener(this); } @Override public void didReceivedNotification(int id, Object... args) { String result = (String) args[0]; String content = (String) args[1]; if (TextUtils.isEmpty(result) || TextUtils.isEmpty(content)) { return; } setData(result); } private void setData(String result) { String data = ""; if (result.contains(ConfigParams.SetCameraType)) { data = result.replaceAll(ConfigParams.SetCameraType, "").trim(); if ("1".equals(data)) { typeGroup.check(R.id.type_button); } else if ("2".equals(data)) { typeGroup.check(R.id.type_button2); } else if ("3".equals(data)) { typeGroup.check(R.id.type_button3); } } else if (result.contains(ConfigParams.SetPIC_Resolution)) { data = result.replaceAll(ConfigParams.SetPIC_Resolution, "").trim(); if ("0".equals(data)) { cameraGroup.check(R.id.camera_button); } else if ("1".equals(data)) { cameraGroup.check(R.id.camera_button2); } else if ("2".equals(data)) { cameraGroup.check(R.id.camera_button3); } } else if (result.contains(ConfigParams.SetCameraManuf)) { data = result.replaceAll(ConfigParams.SetCameraManuf, "").trim(); if ("1".equals(data)) { companyGroup.check(R.id.company_button); } else if ("2".equals(data)) { companyGroup.check(R.id.company_button2); } else if ("3".equals(data)) { companyGroup.check(R.id.company_button3); } else if ("4".equals(data)) { companyGroup.check(R.id.company_button4); } else if ("5".equals(data)) { companyGroup.check(R.id.company_button5); } else if ("6".equals(data)) { companyGroup.check(R.id.company_button6); } } else if (result.contains(ConfigParams.SetPicSendMode)) { data = result.replaceAll(ConfigParams.SetPicSendMode, "").trim(); if ("1".equals(data)) { sendModelGroup.check(R.id.Single_packet_reply_button); } else { sendModelGroup.check(R.id.Multi_packet_reply_button); } } else if (result.contains(ConfigParams.SetCamNum)) { data = result.replaceAll(ConfigParams.SetCamNum, "").trim(); cameraNumEdittext.setText(data); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.camera_num_button: String water = cameraNumEdittext.getText().toString(); if (TextUtils.isEmpty(water)) { ToastUtil.showToastLong(getString(R.string.cameras_number_empty)); return; } int planNum = Integer.parseInt(water); if (planNum < 0 || planNum > 9) { ToastUtil.showToastLong(getString(R.string.cameras_enter)); return; } String content = ConfigParams.SetCamNum + planNum; SocketUtil.getSocketUtil().sendContent(content); break; default: break; } } }
1d93de06f468ff8ab311ad968abd5422456c520b
8834f4b2893f0610226eb5067c5c5325fe642bde
/LambdasWorkshop/src/mx/javaday/lambda/exercise1/LambdaHello.java
bb0f20ad0e33da559a67a1801277bc81bf4182f0
[]
no_license
taurus2819/lambdas
8b3f11632fa2150a11d481f8d5681fda72a75fa8
f5a22818c58af1dc935ee2433762ff95f892fbef
refs/heads/master
2021-01-11T21:22:27.187566
2015-05-01T21:20:34
2015-05-01T21:20:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
622
java
package mx.javaday.lambda.exercise1; /** * * @author jgmnx */ public class LambdaHello { static void speak(SayHello sayhello) { System.out.println(sayhello.salute()); } public static void main(String... args) { SayHello sayHelloInEnglish = null; //TODO: lambda expression for english message LambdaHello.speak(sayHelloInEnglish); SayHello sayHelloInSpanish = null; //TODO: lambda expression for spanish message LambdaHello.speak(sayHelloInSpanish); LambdaHello.speak(null); //TODO: lambda expression for french message } }
2a6748e44943b4c1786f2807d586cf40b4955e5d
a91e44554dc55cc0de99627d9d6376dee0c99083
/baseproject/src/main/java/com/zhiyicx/baseproject/utils/GlideCachUtils.java
047dda00c6f734bb2a81e8784c4dea317c76119b
[]
no_license
laoshaoguo/Rapid
dc90feee1a588771aa4c7ed23ccd67e6b2a6484e
bc62c0ac09b751c6e21c45d74ecc9f9ea9a7c30f
refs/heads/master
2020-08-02T07:43:40.835923
2019-10-09T06:00:22
2019-10-09T06:00:22
211,277,835
3
0
null
null
null
null
UTF-8
Java
false
false
4,975
java
package com.zhiyicx.baseproject.utils; import android.content.Context; import android.os.Looper; import com.bumptech.glide.Glide; import com.bumptech.glide.module.GlideModule; import com.zhiyicx.common.utils.FileUtils; import java.io.File; import java.math.BigDecimal; /** * @author Jungle68 * @describe Glide缓存工具类 * @date 2018/4/14 * @contact [email protected] */ public class GlideCachUtils { public static final String GLIDE_CACHE_PATH = "glide_cache"; private static GlideCachUtils instance; private Context mContext; private GlideCachUtils(Context context) { mContext = context.getApplicationContext(); } public static GlideCachUtils getInstance(Context context) { if (null == instance) { instance = new GlideCachUtils(context); } return instance; } // 获取Glide磁盘缓存大小 public String getCacheSize() { try { return getFormatSize(getFolderSize(new File(FileUtils.getCacheFile(mContext, false).getAbsolutePath() + File.separator + GLIDE_CACHE_PATH))); } catch (Exception e) { e.printStackTrace(); return "0"; } } // 清除Glide磁盘缓存,自己获取缓存文件夹并删除方法 public boolean cleanCatchDisk() { return deleteFolderFile(FileUtils.getCacheFile(mContext, false).getAbsolutePath() + File.separator + GLIDE_CACHE_PATH, true); } // 清除图片磁盘缓存,调用Glide自带方法 public boolean clearCacheDiskSelf() { try { if (Looper.myLooper() == Looper.getMainLooper()) { new Thread(new Runnable() { @Override public void run() { Glide.get(mContext).clearDiskCache(); } }).start(); } else { Glide.get(mContext).clearDiskCache(); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } // 清除Glide内存缓存 public boolean clearCacheMemory() { try { if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行 Glide.get(mContext).clearMemory(); return true; } } catch (Exception e) { e.printStackTrace(); } return false; } // 获取指定文件夹内所有文件大小的和 private long getFolderSize(File file) throws Exception { long size = 0; try { File[] fileList = file.listFiles(); for (File aFileList : fileList) { if (aFileList.isDirectory()) { size = size + getFolderSize(aFileList); } else { size = size + aFileList.length(); } } } catch (Exception e) { e.printStackTrace(); } return size; } // 格式化单位 private static String getFormatSize(double size) { double kiloByte = size / 1024; if (kiloByte < 1) { return size + "Byte"; } double megaByte = kiloByte / 1024; if (megaByte < 1) { BigDecimal result1 = new BigDecimal(Double.toString(kiloByte)); return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB"; } double gigaByte = megaByte / 1024; if (gigaByte < 1) { BigDecimal result2 = new BigDecimal(Double.toString(megaByte)); return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB"; } double teraBytes = gigaByte / 1024; if (teraBytes < 1) { BigDecimal result3 = new BigDecimal(Double.toString(gigaByte)); return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB"; } BigDecimal result4 = new BigDecimal(teraBytes); return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB"; } // 按目录删除文件夹文件方法 private boolean deleteFolderFile(String filePath, boolean deleteThisPath) { try { File file = new File(filePath); if (file.isDirectory()) { File files[] = file.listFiles(); for (File file1 : files) { deleteFolderFile(file1.getAbsolutePath(), true); } } if (deleteThisPath) { if (!file.isDirectory()) { file.delete(); } else { if (file.listFiles().length == 0) { file.delete(); } } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } }
[ "gaoquanyue" ]
gaoquanyue
f614ffc6a7d8bbdfd2be3ff2f1b7eca8d6710889
55033e61f7ddae9eb63e7183650151fb7787f01b
/kraken-model-dsl/src/test/java/kraken/model/dsl/KrakenModelDSLParserContextTest.java
9585bcea77949a383be039f0b85afd95f97d1333
[ "Apache-2.0" ]
permissive
cothong/kraken-rules
7e53a47a44cbd4ecdb940542f0b44d3daaf3035b
920a5a23492b8bc0a1c4621f674a145c53dea5c6
refs/heads/main
2023-08-30T00:50:14.186463
2021-11-15T16:12:36
2021-11-15T16:12:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,591
java
/* * Copyright 2018 EIS Ltd and/or one of its affiliates. * * 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 kraken.model.dsl; import kraken.model.context.Cardinality; import kraken.model.context.PrimitiveFieldDataType; import kraken.model.context.SystemDataTypes; import kraken.model.context.ContextDefinition; import kraken.model.context.ContextField; import kraken.model.context.ContextNavigation; import kraken.model.resource.Resource; import org.junit.Test; import static kraken.model.dsl.KrakenDSLModelParser.parseResource; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase; import static org.junit.Assert.assertThat; /** * Context parsing test for {@link KrakenDSLModelParser} that verifies if {@link ContextDefinition} are parsed correctly * * @author mulevicius */ public class KrakenModelDSLParserContextTest { @Test public void shouldParseRootContext() { Resource model = parseResource("Namespace Foo Include Bar Contexts { Root Context Policy{} }"); assertThat(model.getContextDefinitions(), hasSize(1)); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.getName(), equalTo("Policy")); assertThat(contextDefinition.isStrict(), is(true)); assertThat(contextDefinition.isRoot(), is(true)); assertThat(contextDefinition.getChildren().values(), empty()); assertThat(contextDefinition.getContextFields().values(), empty()); assertThat(contextDefinition.getParentDefinitions(), empty()); } @Test public void shouldParseEmptyContext() { Resource model = parseResource("Namespace Foo Include Bar Contexts{Context Policy{}}"); assertThat(model.getContextDefinitions(), hasSize(1)); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.getName(), equalTo("Policy")); assertThat(contextDefinition.isStrict(), is(true)); assertThat(contextDefinition.getChildren().values(), empty()); assertThat(contextDefinition.getContextFields().values(), empty()); assertThat(contextDefinition.getParentDefinitions(), empty()); } @Test public void shouldParseMultipleContexts() { Resource model = parseResource("Contexts{Context Policy{} Context RiskItem {}}"); assertThat(model.getContextDefinitions(), hasSize(2)); assertThat(model.getContextDefinitions().get(0).getName(), equalTo("Policy")); assertThat(model.getContextDefinitions().get(1).getName(), equalTo("RiskItem")); } @Test public void shouldParseContextField() { Resource model = parseResource("Contexts{Context Policy { String name Integer *ages : path.to.ages }}"); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.getContextFields().values(), hasSize(2)); ContextField name = contextDefinition.getContextFields().get("name"); assertThat(name.getName(), equalTo("name")); assertThat(name.getCardinality(), is(Cardinality.SINGLE)); assertThat(name.getFieldPath(), equalTo("name")); assertThat(name.getFieldType(), is(PrimitiveFieldDataType.STRING.toString())); ContextField ages = contextDefinition.getContextFields().get("ages"); assertThat(ages.getName(), equalTo("ages")); assertThat(ages.getCardinality(), is(Cardinality.MULTIPLE)); assertThat(ages.getFieldPath(), equalTo("path.to.ages")); assertThat(ages.getFieldType(), is(PrimitiveFieldDataType.INTEGER.toString())); } @Test public void shouldParseAllDataTypesFromContextField() { Resource model = parseResource("Contexts{Context Policy { " + "String string Integer integer Decimal decimal Date date DateTime dateTime Boolean boolean Money money }}"); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.getContextFields().values(), hasSize(7)); assertThat(contextDefinition.getContextFields().get("string").getFieldType(), is(PrimitiveFieldDataType.STRING.toString())); assertThat(contextDefinition.getContextFields().get("integer").getFieldType(), is(PrimitiveFieldDataType.INTEGER.toString())); assertThat(contextDefinition.getContextFields().get("decimal").getFieldType(), is(PrimitiveFieldDataType.DECIMAL.toString())); assertThat(contextDefinition.getContextFields().get("date").getFieldType(), is(PrimitiveFieldDataType.DATE.toString())); assertThat(contextDefinition.getContextFields().get("dateTime").getFieldType(), is(PrimitiveFieldDataType.DATETIME.toString())); assertThat(contextDefinition.getContextFields().get("boolean").getFieldType(), is(PrimitiveFieldDataType.BOOLEAN.toString())); assertThat(contextDefinition.getContextFields().get("money").getFieldType(), is(PrimitiveFieldDataType.MONEY.toString())); } @Test public void shouldParseComplexContextFieldType() { Resource model = parseResource("Context RiskItem { " + "Coverage *coverage }"); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.getContextFields().values(), hasSize(1)); ContextField coverageField = contextDefinition.getContextFields().get("coverage"); assertThat(coverageField.getCardinality(), is(Cardinality.MULTIPLE)); assertThat(coverageField.getFieldPath(), is("coverage")); assertThat(coverageField.getName(), is("coverage")); assertThat(coverageField.getFieldType(), is("Coverage")); } @Test public void shouldParseContextChild() { Resource model = parseResource("Contexts{Context Policy { " + "Child *Coverage : all.my.coverages Child RiskItem}}"); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.getChildren().values(), hasSize(2)); ContextNavigation coverage = contextDefinition.getChildren().get("Coverage"); assertThat(coverage.getTargetName(), equalTo("Coverage")); assertThat(coverage.getCardinality(), is(Cardinality.MULTIPLE)); assertThat(coverage.getNavigationExpression(), equalTo("all.my.coverages")); ContextNavigation riskItem = contextDefinition.getChildren().get("RiskItem"); assertThat(riskItem.getTargetName(), equalTo("RiskItem")); assertThat(riskItem.getCardinality(), is(Cardinality.SINGLE)); assertThat(riskItem.getNavigationExpression(), equalTo("riskItem")); } @Test public void shouldParseNotStrictContext() { Resource model = parseResource("Contexts{@NotStrict Context Policy {}}"); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.isStrict(), is(false)); } @Test public void shouldParseContextParentDefinitions() { Resource model = parseResource("Contexts{Context Policy Is RootEntity, AbstractPolicy{}}"); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.getParentDefinitions(), hasItems("RootEntity", "AbstractPolicy")); } @Test public void shouldParseNonPropertyAttributeToUnknownDataType() { Resource model = parseResource("Contexts{" + "Context Policy {" + "Unknown fieldName" + "}}"); final String fieldType = model.getContextDefinitions() .get(0) .getContextFields() .values() .iterator().next() .getFieldType(); assertThat(fieldType, equalToIgnoringCase(SystemDataTypes.UNKNOWN.toString())); } @Test public void shouldParseExternalContextField() { Resource model = parseResource("Contexts{" + "Context Policy {" + "External String externalPrimitive " + "External Coverage externalComplex " + "Coverage notExternalComplex " + "Integer notExternalPrimitive" + "}}"); ContextDefinition contextDefinition = model.getContextDefinitions().get(0); assertThat(contextDefinition.getContextFields().get("externalPrimitive").isExternal(), is(true)); assertThat(contextDefinition.getContextFields().get("externalComplex").isExternal(), is(true)); assertThat(contextDefinition.getContextFields().get("notExternalComplex").isExternal(), is(false)); assertThat(contextDefinition.getContextFields().get("notExternalPrimitive").isExternal(), is(false)); } }
36f01f9fa24814622026cf51dbc34cfaf2eeb872
ee5610148237c2a0d44ddfa8d8054ea05143105e
/src/com/warsys/geraclasse/classes/LeXMLFrm.java
2cf682def5eab84309138a7a2b9d4c2200ec5e8d
[]
no_license
adilsonguerra/GeraClasse
83071bb3f9a3ca3166fb602789d483b6c546f38d
97e5de1c989924474ccfb562deb41672f7eb3e59
refs/heads/master
2021-01-02T09:39:14.992798
2020-10-16T09:37:57
2020-10-16T09:37:57
99,172,044
1
0
null
null
null
null
ISO-8859-1
Java
false
false
3,864
java
package com.warsys.geraclasse.classes; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Sample application using Frame. * * @author * @version 1.00 06/03/06 */ public class LeXMLFrm extends JFrame { JTextField txtCaminhoXml = new JTextField(40); public LeXMLFrm() { ImageIcon iconXML = new ImageIcon("F:/sony/Guerra/prjs_java/GeraClasse/img/dir.gif"); JButton btnLerXml = new JButton("OK"); JButton btnOpenFile = new JButton(iconXML); JLabel lblCaminhoXml = new JLabel("Arquivo Xml:"); JPanel pTxts = new JPanel(); JPanel pBotoes = new JPanel(); JPanel pLabels = new JPanel(); JPanel pBotoes2 = new JPanel(); Container c = getContentPane(); c.setLayout(new BorderLayout()); pTxts.setLayout(new GridLayout(1,1)); pTxts.add(txtCaminhoXml); pBotoes2.add(btnOpenFile); pLabels.setLayout(new GridLayout(1,1)); pLabels.add(lblCaminhoXml); pBotoes.add(btnLerXml); c.add(pBotoes2, BorderLayout.EAST); c.add(pLabels, BorderLayout.NORTH); c.add(pTxts, BorderLayout.WEST); c.add(pBotoes, BorderLayout.SOUTH); // btnLerXml.addActionListener(btnLerXmlClick); btnOpenFile.addActionListener(btnOpenFileClick); btnLerXml.addActionListener(btnLerXmlClick); setTitle("Pesquisar XML"); //setSize(new Dimension(400, 400)); this.pack(); this.show(); // Add window listener. this.addWindowListener ( new WindowAdapter() { public void windowClosing(WindowEvent e) { LeXMLFrm.this.windowClosed(); } } ); } /** * Shutdown procedure when run as an application. */ protected void windowClosed() { this.disable(); } private ActionListener btnOpenFileClick = new ActionListener(){ public void actionPerformed(ActionEvent ae){ try{ FileDialog fileDialog=null; Frame frame = new Frame("Procura o XML..."); center(frame); if (fileDialog == null) { fileDialog = new FileDialog(frame, "Informe o arquivo XML"); } fileDialog.setMode(FileDialog.LOAD); fileDialog.show(); String dir = fileDialog.getDirectory(); String file = fileDialog.getFile(); if (dir!=null){ txtCaminhoXml.setText(dir + file); } } catch (Exception e) { System.out.println("Ocorreu o seguinte erro: " + e.getMessage()); } } }; private ActionListener btnLerXmlClick = new ActionListener(){ public void actionPerformed(ActionEvent ae){ try{ //GeraClasse.txtCaminhoXml.setText(txtCaminhoXml.getText()); GeraClasse.LerXml(txtCaminhoXml.getText()); } catch (Exception e) { System.out.println("Ocorreu o seguinte erro: " + e.getMessage()); } } }; public static void center(Component componente) { // Centraliza a janela de abertura no centro do desktop. Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle r = componente.getBounds(); // Dimensões da janela int widthSplash = r.width ; int heightSplash = r.height; // calculo para encontrar as cooredenadas X e Y para a centralização da janela. int posX = (screen.width / 2) - ( widthSplash / 2 ); int posY = (screen.height / 2) - ( heightSplash / 2 ); componente.setBounds(posX,posY,widthSplash,heightSplash); } }
ecbf0110ca8651d0fb0b7adc4e1282ea17ccbf9c
10b554295b00a55ce92711779e3c11c0bc01c1f1
/src/com/px/tilepuzzle/GamePlay.java
a5d38cdd24ee422bcfcd4f11cf2b1785811a0cd8
[]
no_license
PXMYH/TilePuzzle
5f1374fdb8aa1dc7bbfab770888e3ed76a4cdcde
985212d0d2ac3d0db07c7e39fa5f9fa331f88a5b
refs/heads/master
2021-01-18T15:17:16.580694
2013-08-27T07:29:22
2013-08-27T07:29:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
328
java
package com.px.tilepuzzle; import android.app.Activity; import android.os.Bundle; public class GamePlay extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO Auto-generated method stub } }
add8bab747da7e4ea4615c8dde71787639b26df1
350da4a8e39ae7a70fcbed0e775014f5e1a3cec6
/server/src/main/java/es/us/chatbot/server/config/LoggingConfiguration.java
40db9e55d85c6a4e38d2d060d312afb2602df669
[]
no_license
BulkSecurityGeneratorProject/Chatbot-Watson-Java-Angular
4343849b709e4219759feb9774bbf9ed7fa6e05e
f38d5182d3d8235e2f4f08ad86b03aa61f2b2113
refs/heads/master
2022-12-12T05:48:32.914678
2019-05-19T22:40:00
2019-05-19T21:40:00
296,648,650
0
0
null
null
null
null
UTF-8
Java
false
false
12,507
java
package es.us.chatbot.server.config; import java.net.InetSocketAddress; import java.util.Iterator; import io.github.jhipster.config.JHipsterProperties; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.boolex.OnMarkerEvaluator; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.Appender; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.filter.EvaluatorFilter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterReply; import net.logstash.logback.appender.LogstashTcpSocketAppender; import net.logstash.logback.composite.ContextJsonProvider; import net.logstash.logback.composite.GlobalCustomFieldsJsonProvider; import net.logstash.logback.composite.loggingevent.ArgumentsJsonProvider; import net.logstash.logback.composite.loggingevent.LogLevelJsonProvider; import net.logstash.logback.composite.loggingevent.LoggerNameJsonProvider; import net.logstash.logback.composite.loggingevent.LoggingEventFormattedTimestampJsonProvider; import net.logstash.logback.composite.loggingevent.LoggingEventJsonProviders; import net.logstash.logback.composite.loggingevent.LoggingEventPatternJsonProvider; import net.logstash.logback.composite.loggingevent.MdcJsonProvider; import net.logstash.logback.composite.loggingevent.MessageJsonProvider; import net.logstash.logback.composite.loggingevent.StackTraceJsonProvider; import net.logstash.logback.composite.loggingevent.ThreadNameJsonProvider; import net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder; import net.logstash.logback.encoder.LogstashEncoder; import net.logstash.logback.stacktrace.ShortenedThrowableConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration public class LoggingConfiguration { private static final String CONSOLE_APPENDER_NAME = "CONSOLE"; private static final String LOGSTASH_APPENDER_NAME = "LOGSTASH"; private static final String ASYNC_LOGSTASH_APPENDER_NAME = "ASYNC_LOGSTASH"; private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class); private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); private final String appName; private final String serverPort; private final JHipsterProperties jHipsterProperties; public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort, JHipsterProperties jHipsterProperties) { this.appName = appName; this.serverPort = serverPort; this.jHipsterProperties = jHipsterProperties; if (this.jHipsterProperties.getLogging().isUseJsonFormat()) { addJsonConsoleAppender(context); } if (this.jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashTcpSocketAppender(context); } if (this.jHipsterProperties.getLogging().isUseJsonFormat() || this.jHipsterProperties.getLogging().getLogstash().isEnabled()) { addContextListener(context); } if (this.jHipsterProperties.getMetrics().getLogs().isEnabled()) { setMetricsMarkerLogbackFilter(context); } } private void addJsonConsoleAppender(LoggerContext context) { log.info("Initializing Console logging"); // More documentation is available at: https://github.com/logstash/logstash-logback-encoder ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>(); consoleAppender.setContext(context); consoleAppender.setEncoder(compositeJsonEncoder(context)); consoleAppender.setName(CONSOLE_APPENDER_NAME); consoleAppender.start(); context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).detachAppender(CONSOLE_APPENDER_NAME); context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(consoleAppender); } private void addLogstashTcpSocketAppender(LoggerContext context) { log.info("Initializing Logstash logging"); // More documentation is available at: https://github.com/logstash/logstash-logback-encoder LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender(); logstashAppender.addDestinations(new InetSocketAddress(this.jHipsterProperties.getLogging().getLogstash().getHost(), this.jHipsterProperties.getLogging().getLogstash().getPort())); logstashAppender.setContext(context); logstashAppender.setEncoder(logstashEncoder()); logstashAppender.setName(LOGSTASH_APPENDER_NAME); logstashAppender.start(); // Wrap the appender in an Async appender for performance AsyncAppender asyncLogstashAppender = new AsyncAppender(); asyncLogstashAppender.setContext(context); asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME); asyncLogstashAppender.setQueueSize(this.jHipsterProperties.getLogging().getLogstash().getQueueSize()); asyncLogstashAppender.addAppender(logstashAppender); asyncLogstashAppender.start(); context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME).addAppender(asyncLogstashAppender); } private LoggingEventCompositeJsonEncoder compositeJsonEncoder(LoggerContext context) { final LoggingEventCompositeJsonEncoder compositeJsonEncoder = new LoggingEventCompositeJsonEncoder(); compositeJsonEncoder.setContext(context); compositeJsonEncoder.setProviders(jsonProviders(context)); compositeJsonEncoder.start(); return compositeJsonEncoder; } private LogstashEncoder logstashEncoder() { final LogstashEncoder logstashEncoder = new LogstashEncoder(); logstashEncoder.setThrowableConverter(throwableConverter()); logstashEncoder.setCustomFields(customFields()); return logstashEncoder; } private LoggingEventJsonProviders jsonProviders(LoggerContext context) { final LoggingEventJsonProviders jsonProviders = new LoggingEventJsonProviders(); jsonProviders.addArguments(new ArgumentsJsonProvider()); jsonProviders.addContext(new ContextJsonProvider<>()); jsonProviders.addGlobalCustomFields(customFieldsJsonProvider()); jsonProviders.addLogLevel(new LogLevelJsonProvider()); jsonProviders.addLoggerName(loggerNameJsonProvider()); jsonProviders.addMdc(new MdcJsonProvider()); jsonProviders.addMessage(new MessageJsonProvider()); jsonProviders.addPattern(new LoggingEventPatternJsonProvider()); jsonProviders.addStackTrace(stackTraceJsonProvider()); jsonProviders.addThreadName(new ThreadNameJsonProvider()); jsonProviders.addTimestamp(timestampJsonProvider()); jsonProviders.setContext(context); return jsonProviders; } private GlobalCustomFieldsJsonProvider<ILoggingEvent> customFieldsJsonProvider() { final GlobalCustomFieldsJsonProvider<ILoggingEvent> customFieldsJsonProvider = new GlobalCustomFieldsJsonProvider<>(); customFieldsJsonProvider.setCustomFields(customFields()); return customFieldsJsonProvider; } private String customFields () { StringBuilder customFields = new StringBuilder(); customFields.append("{"); customFields.append("\"app_name\":\"").append(this.appName).append("\""); customFields.append(",").append("\"app_port\":\"").append(this.serverPort).append("\""); customFields.append("}"); return customFields.toString(); } private LoggerNameJsonProvider loggerNameJsonProvider() { final LoggerNameJsonProvider loggerNameJsonProvider = new LoggerNameJsonProvider(); loggerNameJsonProvider.setShortenedLoggerNameLength(20); return loggerNameJsonProvider; } private StackTraceJsonProvider stackTraceJsonProvider() { StackTraceJsonProvider stackTraceJsonProvider = new StackTraceJsonProvider(); stackTraceJsonProvider.setThrowableConverter(throwableConverter()); return stackTraceJsonProvider; } private ShortenedThrowableConverter throwableConverter() { final ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setRootCauseFirst(true); return throwableConverter; } private LoggingEventFormattedTimestampJsonProvider timestampJsonProvider() { final LoggingEventFormattedTimestampJsonProvider timestampJsonProvider = new LoggingEventFormattedTimestampJsonProvider(); timestampJsonProvider.setTimeZone("UTC"); timestampJsonProvider.setFieldName("timestamp"); return timestampJsonProvider; } private void addContextListener(LoggerContext context) { LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener(this.jHipsterProperties); loggerContextListener.setContext(context); context.addListener(loggerContextListener); } // Configure a log filter to remove "metrics" logs from all appenders except the "LOGSTASH" appender private void setMetricsMarkerLogbackFilter(LoggerContext context) { log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME); OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator(); onMarkerMetricsEvaluator.setContext(context); onMarkerMetricsEvaluator.addMarker("metrics"); onMarkerMetricsEvaluator.start(); EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>(); metricsFilter.setContext(context); metricsFilter.setEvaluator(onMarkerMetricsEvaluator); metricsFilter.setOnMatch(FilterReply.DENY); metricsFilter.start(); context.getLoggerList().forEach((logger) -> { for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) { Appender<ILoggingEvent> appender = it.next(); if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME) && !(appender.getName().equals(CONSOLE_APPENDER_NAME) && this.jHipsterProperties.getLogging().isUseJsonFormat())) { log.debug("Filter metrics logs from the {} appender", appender.getName()); appender.setContext(context); appender.addFilter(metricsFilter); appender.start(); } } }); } /** * Logback configuration is achieved by configuration file and API. * When configuration file change is detected, the configuration is reset. * This listener ensures that the programmatic configuration is also re-applied after reset. */ class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener { private final JHipsterProperties jHipsterProperties; private LogbackLoggerContextListener(JHipsterProperties jHipsterProperties) { this.jHipsterProperties = jHipsterProperties; } @Override public boolean isResetResistant() { return true; } @Override public void onStart(LoggerContext context) { if (this.jHipsterProperties.getLogging().isUseJsonFormat()) { addJsonConsoleAppender(context); } if (this.jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashTcpSocketAppender(context); } } @Override public void onReset(LoggerContext context) { if (this.jHipsterProperties.getLogging().isUseJsonFormat()) { addJsonConsoleAppender(context); } if (this.jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashTcpSocketAppender(context); } } @Override public void onStop(LoggerContext context) { // Nothing to do. } @Override public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) { // Nothing to do. } } }
f16a7a7f09fd379074844f2f3b892458a0cfa43e
dd09e3d765187b9e3138f186d8273753fd3fd737
/lvqibin-oa/lvqibin-oa-web/src/main/java/com/lvqibin/oa/sys/controller/SysPermissionController.java
4528a0bddae21b64d97bb2cf1c950311f2699868
[ "BSD-2-Clause" ]
permissive
lvqibin123/oa-server
86f45a696088bbd9956d55b4f11a8a51c870ef36
95444466f79e2759e346d32b4de5250002b2a0ae
refs/heads/master
2023-03-05T15:52:24.834388
2020-04-13T01:32:31
2020-04-13T01:32:31
234,206,637
0
0
BSD-2-Clause
2023-02-22T08:25:32
2020-01-16T01:17:31
TSQL
UTF-8
Java
false
false
6,345
java
package com.lvqibin.oa.sys.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.reflect.TypeToken; import com.lvqibin.oa.common.CheckToken; import com.lvqibin.oa.common.Message; import com.lvqibin.oa.sys.model.SysPermission; import com.lvqibin.oa.sys.service.SysPermissionService; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; /** * <p> * 权限表 前端控制器 * </p> * * @author lvqibin * @since 2019-12-02 */ @RestController @RequestMapping("/sysPermission") @Slf4j public class SysPermissionController { /** * @apiDefine sysPermissionGroup 权限管理 */ @Autowired private SysPermissionService service; /** * 根据角色id获取授权的菜单 * date 2019-12-14 * * @author lvqibin * @param roleId 角色id 不能为空 * @return Message */ /** * @api {get} /sysPermission/getPermissionByRoleId 根据角色id获取授权的菜单 * @apiDescription 根据角色id获取授权的菜单 * @apiName getPermissionByRoleId * @apiVersion 1.0.0 * @apiGroup sysPermissionGroup * * @apiHeader {String} token * * @apiParam {String} roleId 角色id 不能为空 * * * @apiSampleRequest /sysPermission/getPermissionByRoleId * @apiSuccess (success 200) {String} res.status 标识码 200 成功 否则失败 * @apiSuccess (success 200) {String} res.message 消息 * @apiSuccess (success 200) {String} res.data.id 主键id * @apiSuccess (success 200) {String} res.data.roleId 所属角色 * @apiSuccess (success 200) {String} res.data.description 描述 * @apiSuccess (success 200) {Integer} res.data.sequence 序号 * @apiSuccess (success 200) {String} res.data.validState 可用状态 * @apiSuccess (success 200) {Integer} res.data.version 版本 * @apiSuccess (success 200) {String} res.data.menuId 菜单ID * */ @RequestMapping("/getPermissionByRoleId") @ResponseBody @CheckToken public Message getPermissionByRoleId(@RequestParam Map<String, String> params) { log.debug("SysPermissionController.getPermissionByRoleId >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" ); Message mes = new Message(); String roleId = ""; JsonArray dataList = new JsonArray(); List<SysPermission> list = new ArrayList<SysPermission>(); if(StringUtils.isNotEmpty(params.get("roleId"))){ roleId = params.get("roleId"); log.debug("Param : roleId = " + roleId ); QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<SysPermission>(); queryWrapper.eq(true, "role_id", roleId); list = service.list(queryWrapper); if ( list.size() > 0 ) { dataList = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJsonTree(list, new TypeToken<List<SysPermission>>() {}.getType()).getAsJsonArray(); } mes.setStatus(200); mes.setData(dataList); mes.setMessage("获取数据成功!"); }else { mes.setStatus(-200); mes.setMessage("获取 roleId 失败!"); } log.debug("mes = " , mes.toString()); log.debug("action : query dataList = " + list!=null&&list.size()>0 ? dataList.toString() : "null"); log.debug("SysPermissionController.getPermissionByRoleId <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" ); return mes; } /** * 根据角色ID和菜单列表 对角色批量授权 * date 2019-12-14 *@author lvqibin *@param roleId 角色Id 不能为空 *@param menuList 菜单Id 的通过英文的,拼接 可以为空 */ /** * @api {get} /sysPermission/getPermissionByRoleId 根据角色ID和菜单列表 对角色批量授权 * @apiDescription 根据角色ID和菜单列表 对角色批量授权 * @apiName getPermissionByRoleId * @apiVersion 1.0.0 * @apiGroup sysPermissionGroup * * @apiHeader {String} token * * @apiParam {String} roleId 角色id 不能为空 * @apiParam {String} menuList 菜单Id 的通过英文的,拼接 可以为空 * * * @apiSampleRequest /sysPermission/getPermissionByRoleId * @apiSuccess (success 200) {String} res.status 标识码 200 成功 否则失败 * @apiSuccess (success 200) {String} res.message 消息 * */ @RequestMapping("/addMenu") @ResponseBody @CheckToken public Message addMenu(@RequestParam Map<String, String> params) throws Exception { log.debug("SysPermissionController.addMenu >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" ); Message mes = new Message(); String roleId = ""; String menuList = ""; if(StringUtils.isNotEmpty(params.get("roleId"))){ roleId = params.get("roleId"); log.debug("Param : roleId = " + roleId ); menuList = params.get("menuList"); log.debug("Param : menuList = " + menuList ); if ( StringUtils.isNotEmpty(params.get("menuList")) ) { List<String> dataList = Arrays.asList(menuList.split(",")); long insterSum = service.insertbatch(roleId, dataList); log.debug("action : inster insterSum = " + insterSum ); if(insterSum>0) { mes.setStatus(200); mes.setMessage("分配菜单成功!"); }else { mes.setStatus(-200); mes.setMessage("分配菜单失败!"); } } else { long insterSum = service.insertbatch(roleId, null ); log.debug("action : inster insterSum = " + insterSum ); if(insterSum != -1 ) { mes.setStatus(200); mes.setMessage("分配菜单成功!"); }else { mes.setStatus(-200); mes.setMessage("分配菜单失败!"); } } }else { mes.setStatus(-200); mes.setMessage("获取 roleID 失败!"); } log.debug("mes = " , mes.toString()); log.debug("SysPermissionController.addMenu <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" ); return mes; } }
a8eb34b38c205305b0dfaf11266d2d653312f14a
47cf461856c90c237025d1ac733a4c8f7f7a316b
/Yawei_AppFrame/app/src/main/java/com/android/yawei/jhoa/fingerprint/MyAuthCallback.java
c9e3933206e7548a77df998e2dcee6acf45c31d3
[]
no_license
qiuqing927583/AppFrame_1
62c950ee8735b8a216fc140033f1a94093eac12e
edd1bbca96f1e58781c3e0079c1c917c1804d9d6
refs/heads/master
2020-04-22T02:42:30.254287
2019-02-12T03:03:51
2019-02-12T03:03:51
170,060,289
0
0
null
null
null
null
UTF-8
Java
false
false
2,113
java
package com.android.yawei.jhoa.fingerprint; import android.os.Handler; import android.support.v4.hardware.fingerprint.FingerprintManagerCompat; /** * Created by baniel on 7/21/16. */ public class MyAuthCallback extends FingerprintManagerCompat.AuthenticationCallback { private Handler handler = null; public MyAuthCallback(Handler handler) { super(); // Log.d("指纹码", "aaaaaaaaaaaaaaaaaaaaaaaaaa"); this.handler = handler; } /** * 验证错误信息 * @param errMsgId * @param errString */ @Override public void onAuthenticationError(int errMsgId, CharSequence errString) { super.onAuthenticationError(errMsgId, errString); if (handler != null) { handler.obtainMessage(FingerprintConstant.MSG_AUTH_ERROR, errMsgId, 0).sendToTarget(); } // Log.d("指纹码", "bbbbbbbbbbbbbbbbbbbbbbbbbb"); } /** * 身份验证帮助 * @param helpMsgId * @param helpString */ @Override public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { super.onAuthenticationHelp(helpMsgId, helpString); if (handler != null) { handler.obtainMessage(FingerprintConstant.MSG_AUTH_HELP, helpMsgId, 0).sendToTarget(); } // Log.d("指纹码", "ccccccccccccccccccccccccccc"); } /** * 验证成功 * @param result */ @Override public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) { super.onAuthenticationSucceeded(result); if (handler != null) { handler.obtainMessage(FingerprintConstant.MSG_AUTH_SUCCESS).sendToTarget(); } // Log.d("指纹码", "dddddddddddddddddddddddd"); } /** * 验证失败 */ @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); if (handler != null) { handler.obtainMessage(FingerprintConstant.MSG_AUTH_FAILED).sendToTarget(); } // Log.d("指纹码", "eeeeeeeeeeeeeeeeeeeeeeeee"); } }
907835aefbd002dd8a6d05ea25926daa4a2221fa
b78f4e4fb8689c0c3b71a1562a7ee4228a116cda
/JFramework/crypto/src/main/java/org/bouncycastle/math/ec/custom/sec/SecT233FieldElement.java
da572201f169bf8d045ba63ef33ebad8965882d4
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
richkmeli/JFramework
94c6888a6bb9af8cbff924e8a1525e6ec4765902
54250a32b196bb9408fb5715e1c677a26255bc29
refs/heads/master
2023-07-24T23:59:19.077417
2023-05-05T22:52:14
2023-05-05T22:52:14
176,379,860
5
6
Apache-2.0
2023-07-13T22:58:27
2019-03-18T22:32:12
Java
UTF-8
Java
false
false
5,048
java
package org.bouncycastle.math.ec.custom.sec; import org.bouncycastle.math.ec.ECFieldElement; import org.bouncycastle.math.raw.Nat256; import org.bouncycastle.util.Arrays; import java.math.BigInteger; public class SecT233FieldElement extends ECFieldElement.AbstractF2m { protected long[] x; public SecT233FieldElement(BigInteger x) { if (x == null || x.signum() < 0 || x.bitLength() > 233) { throw new IllegalArgumentException("x value invalid for SecT233FieldElement"); } this.x = SecT233Field.fromBigInteger(x); } public SecT233FieldElement() { this.x = Nat256.create64(); } protected SecT233FieldElement(long[] x) { this.x = x; } // public int bitLength() // { // return x.degree(); // } public boolean isOne() { return Nat256.isOne64(x); } public boolean isZero() { return Nat256.isZero64(x); } public boolean testBitZero() { return (x[0] & 1L) != 0L; } public BigInteger toBigInteger() { return Nat256.toBigInteger64(x); } public String getFieldName() { return "SecT233Field"; } public int getFieldSize() { return 233; } public ECFieldElement add(ECFieldElement b) { long[] z = Nat256.create64(); SecT233Field.add(x, ((SecT233FieldElement) b).x, z); return new SecT233FieldElement(z); } public ECFieldElement addOne() { long[] z = Nat256.create64(); SecT233Field.addOne(x, z); return new SecT233FieldElement(z); } public ECFieldElement subtract(ECFieldElement b) { // Addition and subtraction are the same in F2m return add(b); } public ECFieldElement multiply(ECFieldElement b) { long[] z = Nat256.create64(); SecT233Field.multiply(x, ((SecT233FieldElement) b).x, z); return new SecT233FieldElement(z); } public ECFieldElement multiplyMinusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y) { return multiplyPlusProduct(b, x, y); } public ECFieldElement multiplyPlusProduct(ECFieldElement b, ECFieldElement x, ECFieldElement y) { long[] ax = this.x, bx = ((SecT233FieldElement) b).x; long[] xx = ((SecT233FieldElement) x).x, yx = ((SecT233FieldElement) y).x; long[] tt = Nat256.createExt64(); SecT233Field.multiplyAddToExt(ax, bx, tt); SecT233Field.multiplyAddToExt(xx, yx, tt); long[] z = Nat256.create64(); SecT233Field.reduce(tt, z); return new SecT233FieldElement(z); } public ECFieldElement divide(ECFieldElement b) { return multiply(b.invert()); } public ECFieldElement negate() { return this; } public ECFieldElement square() { long[] z = Nat256.create64(); SecT233Field.square(x, z); return new SecT233FieldElement(z); } public ECFieldElement squareMinusProduct(ECFieldElement x, ECFieldElement y) { return squarePlusProduct(x, y); } public ECFieldElement squarePlusProduct(ECFieldElement x, ECFieldElement y) { long[] ax = this.x; long[] xx = ((SecT233FieldElement) x).x, yx = ((SecT233FieldElement) y).x; long[] tt = Nat256.createExt64(); SecT233Field.squareAddToExt(ax, tt); SecT233Field.multiplyAddToExt(xx, yx, tt); long[] z = Nat256.create64(); SecT233Field.reduce(tt, z); return new SecT233FieldElement(z); } public ECFieldElement squarePow(int pow) { if (pow < 1) { return this; } long[] z = Nat256.create64(); SecT233Field.squareN(x, pow, z); return new SecT233FieldElement(z); } public ECFieldElement halfTrace() { long[] z = Nat256.create64(); SecT233Field.halfTrace(x, z); return new SecT233FieldElement(z); } public boolean hasFastTrace() { return true; } public int trace() { return SecT233Field.trace(x); } public ECFieldElement invert() { long[] z = Nat256.create64(); SecT233Field.invert(x, z); return new SecT233FieldElement(z); } public ECFieldElement sqrt() { long[] z = Nat256.create64(); SecT233Field.sqrt(x, z); return new SecT233FieldElement(z); } public int getRepresentation() { return ECFieldElement.F2m.TPB; } public int getM() { return 233; } public int getK1() { return 74; } public int getK2() { return 0; } public int getK3() { return 0; } public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof SecT233FieldElement)) { return false; } SecT233FieldElement o = (SecT233FieldElement) other; return Nat256.eq64(x, o.x); } public int hashCode() { return 2330074 ^ Arrays.hashCode(x, 0, 4); } }
658816d1b8994632a2bbd4e585239c595de1da7a
7f190ba82048a3d5ae0e5ade6844fa3bdf5f2ba9
/src/main/java/com/jeesite/modules/mc/entity/Category.java
0f87aca7344d6acde34811c01db0d9f6cabe6cf0
[ "Apache-2.0" ]
permissive
Thatpot/jeesite-web
8097dc01a511514945befcdd25046027979218e2
8d6cef28de156fb434bae1c2d552858688e895f8
refs/heads/master
2020-03-26T13:46:51.078754
2018-08-31T08:38:05
2018-08-31T08:38:05
144,956,408
0
0
null
null
null
null
UTF-8
Java
false
false
6,545
java
/** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.mc.entity; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import com.jeesite.common.entity.DataEntity; import com.jeesite.common.entity.TreeEntity; import com.jeesite.common.mybatis.annotation.Column; import com.jeesite.common.mybatis.annotation.JoinTable; import com.jeesite.common.mybatis.annotation.JoinTable.Type; import com.jeesite.common.mybatis.annotation.Table; import com.jeesite.common.mybatis.mapper.query.QueryType; import com.jeesite.modules.sys.entity.Office; /** * 栏目Entity * @author xuyuxiang * @version 2018-07-28 */ @Table(name="${_prefix}mc_category", alias="a", columns={ @Column(name="category_code", attrName="categoryCode", label="栏目编码", isPK=true), @Column(name="category_name", attrName="categoryName", label="栏目名称", queryType=QueryType.LIKE, isTreeName=true), @Column(name="office_code", attrName="office.officeCode", label="归属机构"), @Column(name="module", attrName="module", label="栏目模型"), @Column(name="image", attrName="image", label="栏目图片"), @Column(name="href", attrName="href", label="链接"), @Column(name="target", attrName="target", label="目标"), @Column(name="description", attrName="description", label="描述"), @Column(name="keywords", attrName="keywords", label="关键字"), @Column(name="in_menu", attrName="inMenu", label="在导航中显示"), @Column(name="in_list", attrName="inList", label="在分类页中显示列表"), @Column(name="show_modes", attrName="showModes", label="展现方式"), @Column(name="allow_comment", attrName="allowComment", label="是否允许评论"), @Column(name="is_audit", attrName="isAudit", label="是否需要审核"), @Column(includeEntity=TreeEntity.class), @Column(includeEntity=DataEntity.class), @Column(name="site_id", attrName="site.id", label="所属站点"), }, joinTable={ @JoinTable(type=Type.LEFT_JOIN, entity=Office.class, attrName="office", alias="u3", on="u3.office_code = a.office_code", columns={ @Column(name="office_code", label="机构编码", isPK=true), @Column(name="office_name", label="机构名称", isQuery=false), }) }, orderBy="a.tree_sorts, a.category_code" ) public class Category extends TreeEntity<Category> { public static final String ARTICLE_MODULE = "article"; public static final String PARETNT_CODE = "0"; private static final long serialVersionUID = 1L; private String categoryCode; // 栏目编码 private String categoryName; // 栏目名称 private Office office; // 归属机构 private String module; // 栏目模型 private String image; // 栏目图片 private String href; // 链接 private String target; // 目标 private String description; // 描述 private String keywords; // 关键字 private String inMenu; // 在导航中显示 private String inList; // 在分类页中显示列表 private String showModes; // 展现方式 private String allowComment; // 是否允许评论 private String isAudit; // 是否需要审核 private Site site; // 所属站点 public Category() { super(null); } public Category(String id){ super(id); } public Category(String id, Site site){ this(); this.id = id; this.setSite(site); } @Override public Category getParent() { return parent; } @Override public void setParent(Category parent) { this.parent = parent; } public String getCategoryCode() { return categoryCode; } public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; } @NotBlank(message="栏目名称不能为空") @Length(min=0, max=200, message="栏目名称长度不能超过 200 个字符") public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } @NotNull(message="归属机构不能为空") public Office getOffice() { return office; } public void setOffice(Office office) { this.office = office; } @Length(min=0, max=20, message="栏目模型长度不能超过 20 个字符") public String getModule() { return module; } public void setModule(String module) { this.module = module; } @Length(min=0, max=255, message="栏目图片长度不能超过 255 个字符") public String getImage() { return image; } public void setImage(String image) { this.image = image; } @Length(min=0, max=255, message="链接长度不能超过 255 个字符") public String getHref() { return href; } public void setHref(String href) { this.href = href; } @Length(min=0, max=20, message="目标长度不能超过 20 个字符") public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } @Length(min=0, max=255, message="描述长度不能超过 255 个字符") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Length(min=0, max=255, message="关键字长度不能超过 255 个字符") public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } @Length(min=0, max=1, message="在导航中显示长度不能超过 1 个字符") public String getInMenu() { return inMenu; } public void setInMenu(String inMenu) { this.inMenu = inMenu; } @Length(min=0, max=1, message="在分类页中显示列表长度不能超过 1 个字符") public String getInList() { return inList; } public void setInList(String inList) { this.inList = inList; } @Length(min=0, max=1, message="展现方式长度不能超过 1 个字符") public String getShowModes() { return showModes; } public void setShowModes(String showModes) { this.showModes = showModes; } @Length(min=0, max=1, message="是否允许评论长度不能超过 1 个字符") public String getAllowComment() { return allowComment; } public void setAllowComment(String allowComment) { this.allowComment = allowComment; } @Length(min=0, max=1, message="是否需要审核长度不能超过 1 个字符") public String getIsAudit() { return isAudit; } public void setIsAudit(String isAudit) { this.isAudit = isAudit; } public Site getSite() { return site; } public void setSite(Site site) { this.site = site; } }
fde065fa912234b7194811ecb35ef4e4b384d4b0
a88bd8c8d16dc5c141996bce8aefeb6b385d3261
/serwer/src/main/java/pl/nakicompany/ewzwierzat/controller/dto/utworzAdopcje/UtworzAdopcjeResponseDTO.java
e5dda5a2a6151b9fd61d7c49654fbad3640b9a85
[]
no_license
MateuszNakielski/Ewidencja-Zwierzat
5e6443d64a217fcaad965ef798dc714c85083245
d9e00b768ea723152736d010d996cfcb5b371276
refs/heads/master
2021-09-04T11:45:51.871294
2018-01-18T11:55:47
2018-01-18T11:55:47
115,532,714
0
1
null
null
null
null
UTF-8
Java
false
false
236
java
package pl.nakicompany.ewzwierzat.controller.dto.utworzAdopcje; import lombok.Data; import pl.nakicompany.ewzwierzat.controller.dto.common.AdopcjaDTO; @Data public class UtworzAdopcjeResponseDTO { private AdopcjaDTO adopcjaDTO; }
[ "kot@DESKTOP-RNHST0K" ]
kot@DESKTOP-RNHST0K
2cc13aecb923d1463e4a48c26b20a97ee758dca2
7810ee083e1e73211535c49ce995a7d73a943a52
/insurance-web/src/main/java/com/born/insurance/web/interceptor/LoginInterceptorAdapter.java
125433d186c55bcd366f24019cacf73ad932e6a1
[]
no_license
robben766/insuranceSystem
702013b8ad83a596404c7718bff8097ac8a255fa
852acf72136b560a4a3cdf890eae02a55d4e2995
refs/heads/master
2023-03-15T08:15:26.434405
2018-01-31T08:03:35
2018-01-31T08:03:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,119
java
package com.born.insurance.web.interceptor; /** * www.yiji.com Inc. * Copyright (c) 2012 All Rights Reserved. */ import java.io.IOException; import java.net.URLEncoder; import java.util.Enumeration; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.born.insurance.biz.exception.ExceptionFactory; import com.born.insurance.integration.bpm.user.LoginService; import com.born.insurance.integration.bpm.user.PermissionService; import com.born.insurance.integration.bpm.user.PermissionUtil; import com.born.insurance.integration.result.LoginResult; import com.born.insurance.integration.util.SessionLocal; import com.born.insurance.integration.util.ShiroSessionUtils; import com.born.insurance.util.MD5Util; import com.born.insurance.ws.enums.BooleanEnum; import com.born.insurance.ws.enums.base.InsuranceResultEnum; import com.born.insurance.ws.info.common.SysWebAccessTokenInfo; import com.born.insurance.ws.order.LoginOrder; import com.born.insurance.ws.service.common.SysWebAccessTokenService; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONObject; import com.born.insurance.web.util.SpringUtil; import com.born.insurance.web.util.WebSessionUtil; import com.yjf.common.lang.util.StringUtil; import com.yjf.common.log.Logger; import com.yjf.common.log.LoggerFactory; public class LoginInterceptorAdapter implements HandlerInterceptor { String ignoreUrlStr = ""; protected final Logger logger = LoggerFactory.getLogger(getClass()); private static SysWebAccessTokenService sysWebAccessTokenService; private static LoginService loginService; private static PermissionService permissionService; static { sysWebAccessTokenService = SpringUtil.getBean("sysWebAccessTokenService"); loginService = SpringUtil.getBean("loginService"); permissionService = SpringUtil.getBean("permissionService"); } /** * 正则${:} */ protected static Pattern pattern = Pattern .compile("\\$\\{[a-zA-Z0-9.]{1,}:[a-zA-Z0-9.]{1,}\\}"); /** * @param request * @param response * @param handler * @return * @throws Exception * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String uri = request.getServletPath(); SessionLocal sessionLocal = ShiroSessionUtils.getSessionLocal(); //不需要权限检查的访问密钥 SysWebAccessTokenInfo token = (SysWebAccessTokenInfo) request.getAttribute("accessToken"); if (token != null) { //当前登陆用户不是访问用户 if (sessionLocal != null && token.getUserId() != sessionLocal.getUserId()) { if (isAjaxRequest(request)) { JSONObject json = new JSONObject(); json.put("success", false); json.put("message", "无权访问"); printHttpResponse(response, json); } else { String redirect = "/login/login.htm?code=0&message=" + URLEncoder.encode("您无权访问当前数据,请重新登陆", "utf-8") + "&redirect=" + request.getRequestURI(); response.sendRedirect(redirect); } return false; } if (sessionLocal == null && token.getIsValid() == BooleanEnum.IS) { try { //自动登陆 LoginOrder loginData = new LoginOrder(); loginData.setUserName(token.getUserAccount()); String password = token.getUserAccount() + "trust" + "6IG0MVB5QOKRH4XPLE3FW8AJCZ79NTDUSY12"; password = MD5Util.getMD5_32(password); loginData.setPassword(password); LoginResult loginResult = loginService.login(loginData); if (loginResult.isSuccess()) { sysWebAccessTokenService.use(token.getAccessToken()); String loadMenu = request.getParameter("loadMenu"); if (loadMenu == null || !loadMenu.equals("NO")) { permissionService.loadSystemPermission(uri.split("/")[1]); } } } catch (Exception e) { logger.error("自动登陆出错:{}", e); } return true; } else if (sessionLocal == null && token.getIsValid() == BooleanEnum.NO) { if (isAjaxRequest(request)) { JSONObject json = new JSONObject(); json.put("success", false); json.put("message", "访问已失效"); printHttpResponse(response, json); } else { String redirect = "/login/login.htm?code=0&message=" + URLEncoder.encode("访问已失效,请重新登陆", "utf-8") + "&redirect=" + request.getRequestURI(); Enumeration<String> params = request.getParameterNames(); while (params.hasMoreElements()) { String paramName = params.nextElement(); redirect += "&" + paramName + "=" + request.getParameter(paramName); } response.sendRedirect(redirect); } return false; } else { return true; } } else { if (PermissionUtil.checkPermission(uri)) { return true; } else { if (isAjaxRequest(request)) { JSONObject json = new JSONObject(); json.put("success", false); json.put("message", "未授权的资源:" + uri); printHttpResponse(response, json); return false; } else { throw ExceptionFactory .newFcsException(InsuranceResultEnum.NO_ACCESS, "未授权的资源:" + uri); } } } } /** * 是否ajax请求 * @param request * @return */ private boolean isAjaxRequest(HttpServletRequest request) { String requestType = request.getHeader("X-Requested-With"); //是否签报的请求 String isFormChangeApply = request.getParameter("isFormChangeApply"); if (StringUtil.isNotBlank(requestType) || "IS".equals(isFormChangeApply)) return true; return false; } /** * @param request * @param response * @param handler * @param modelAndView * @throws Exception * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.web.servlet.ModelAndView) */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { try { if (modelAndView != null && modelAndView.getModelMap() != null) { modelAndView.getModelMap().put("sessionLocal", ShiroSessionUtils.getSessionLocal()); modelAndView.getModelMap().put("sessionID", request.getSession().getId()); modelAndView.getModelMap().put("webSessionUtil", new WebSessionUtil(ShiroSessionUtils.getSessionLocal())); modelAndView.getModelMap().put("sessionScope", ShiroSessionUtils.getSessionLocal()); } // response.setHeader("Pragma", "no-cache"); // response.addHeader("Cache-Control", "must-revalidate"); // response.addHeader("Cache-Control", "no-cache"); // response.addHeader("Cache-Control", "no-store"); // response.setDateHeader("Expires", 0); } catch (Exception e) { logger.error(e.getMessage(), e); } } /** * @param request * @param response * @param handler * @param ex * @throws Exception * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * java.lang.Exception) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } public void setIgnoreUrlStr(String ignoreUrlStr) { this.ignoreUrlStr = ignoreUrlStr; } protected void printHttpResponse(HttpServletResponse response, com.alibaba.fastjson.JSONAware json) { try { response.setContentType("json"); response.setCharacterEncoding("UTF-8"); response.getWriter().println(json.toJSONString()); } catch (IOException e) { logger.error("response. getWriter print error ", e); } } }
1c29350675fedd48f2be70cf26ed9708892081ab
37506249d96e24906cd79544dfd932002be0ca00
/sky-system/sky-sys/src/main/java/com/yanyu/sky/sys/dao/RoleMapper.java
9af2fd4c36c57564ca11307021e817a591a8084c
[ "Apache-2.0" ]
permissive
MRgzhen/sky-admin
039c90a4a61f956bb7cc9b8ed109188f95820a37
dbdcce3e00ad4a43643080bfb4d849d87cca3453
refs/heads/master
2023-03-03T07:54:24.363984
2021-02-19T08:12:01
2021-02-19T08:12:01
339,978,337
1
0
null
null
null
null
UTF-8
Java
false
false
732
java
package com.yanyu.sky.sys.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.yanyu.sky.sys.bean.po.Role; import com.yanyu.sky.sys.bean.vo.role.RoleInfoVo; import com.yanyu.sky.sys.bean.vo.role.RoleSearchVo; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 系统角色 Mapper 接口 * @author yanyu */ public interface RoleMapper extends BaseMapper<Role> { List<Role> listRolesByUserIdAndTenantCodeNotLogin(@Param("userId") String userId, @Param("tenantCode") String tenantCode); List<Role> listRolesByUserId(String userId); IPage<RoleInfoVo> listRolePage(IPage<RoleInfoVo> page, @Param("vo") RoleSearchVo vo); }
0f0cb75de2d44442963b23c2400865b852c9c06b
ea495cae7042fbfd0df16580d4a2283753731385
/LabEx7.java
6bf91cfcabc92b2378284cbfeedcd04b6f9fa35f
[]
no_license
aafreenbenazir/lab-ex
b4d23d3230359f8236093d52075ca9212b289e9e
d4b5790d371f6ba986dd2f596f7723e376752f8d
refs/heads/master
2023-01-03T12:32:19.366907
2020-10-31T10:22:07
2020-10-31T10:22:07
294,011,467
0
0
null
null
null
null
UTF-8
Java
false
false
1,470
java
//author:K.AAFREEN BENAZIR //initializing 20 elements randomly in an array and calculating sum and avrg //of that 20 elements and storing elements which are of above avrg in list1 //and below avrg in list2 and printing both lists package lab.ex.pkg7; //importing packages import java.util.Scanner; import java.util.ArrayList; //main class public class LabEx7 { public static void main(String[] args) { int a[]=new int[20]; int i,sum=0; for(i=0;i<20;i++) { // initializing elements randomly using Math.random a[i]=((int)(Math.random()*80))+10; //calculating sum sum=sum+a[i]; } //calculating average float avrg=sum/20; ArrayList <Integer> list1=new ArrayList <Integer>(); ArrayList <Integer> list2= new ArrayList <Integer>(); for(i=0;i<20;i++) { if(a[i]>avrg) { list1.add(a[i]); } else if(a[i]<avrg) { list2.add(a[i]); } } //printing the elements below average and above average //elements above average are stored in list1 System.out.println("below average"+list1); //elements below average are stored in list2 System.out.println("above average"+list2); } }
01756d625ea28d05c4fafcc43bc496a31d7b7f41
92aba68ccebf23376d5ce48d5657b93553c11d04
/agent/plugins/elasticsearch-plugin/src/test/common/java/org/glowroot/agent/plugin/elasticsearch/SharedSetupRunListener.java
eeda0cd0cade6bfe64491b78e4d3e7cc68f9aa02
[ "Apache-2.0" ]
permissive
marcelogwolff/glowroot
c1d7b0d395fc1a404916d7daa9c45890e369e5f9
c00097f985d948c9c2bb7f7919e75d70578b2e61
refs/heads/master
2020-03-28T00:03:25.948337
2018-09-03T22:34:13
2018-09-04T04:24:17
147,371,262
0
0
Apache-2.0
2018-09-04T15:53:59
2018-09-04T15:53:58
null
UTF-8
Java
false
false
2,446
java
/* * Copyright 2017-2018 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.glowroot.agent.plugin.elasticsearch; import com.google.common.collect.ImmutableList; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.RunListener; import org.glowroot.agent.it.harness.Container; import org.glowroot.agent.it.harness.Containers; import org.glowroot.agent.it.harness.impl.JavaagentContainer; public class SharedSetupRunListener extends RunListener { private static volatile Container sharedContainer; public static Container getContainer() throws Exception { if (sharedContainer == null) { startElasticsearch(); return createContainer(); } return sharedContainer; } public static void close(Container container) throws Exception { if (sharedContainer == null) { container.close(); ElasticsearchWrapper.stop(); } } @Override public void testRunStarted(Description description) throws Exception { startElasticsearch(); sharedContainer = createContainer(); } @Override public void testRunFinished(Result result) throws Exception { sharedContainer.close(); ElasticsearchWrapper.stop(); } private static void startElasticsearch() throws Exception { ElasticsearchWrapper.start(); } private static Container createContainer() throws Exception { if (Containers.useJavaagent()) { // this is needed to avoid exception // see org.elasticsearch.transport.netty4.Netty4Utils.setAvailableProcessors() return JavaagentContainer.createWithExtraJvmArgs( ImmutableList.of("-Des.set.netty.runtime.available.processors=false")); } else { return Containers.createLocal(); } } }
d7a02df2b433999aa7529a96091492a99fd6ed04
601582228575ca0d5f61b4c211fd37f9e4e2564c
/logisoft_revision1/src/com/gp/cong/logisoft/hibernate/dao/lcl/LclUnitSsManifestDAO.java
d0c984c3bda49ea37f997e73eb6fcc21c3560ab2
[]
no_license
omkarziletech/StrutsCode
3ce7c36877f5934168b0b4830cf0bb25aac6bb3d
c9745c81f4ec0169bf7ca455b8854b162d6eea5b
refs/heads/master
2021-01-11T08:48:58.174554
2016-12-17T10:45:19
2016-12-17T10:45:19
76,713,903
1
1
null
null
null
null
UTF-8
Java
false
false
7,223
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.gp.cong.logisoft.hibernate.dao.lcl; import com.gp.cong.common.CommonUtils; import com.gp.cong.hibernate.BaseHibernateDAO; import com.gp.cong.logisoft.beans.ManifestBean; import com.gp.cong.logisoft.domain.User; import com.gp.cong.logisoft.domain.lcl.LclSsHeader; import com.gp.cong.logisoft.domain.lcl.LclUnit; import com.gp.cong.logisoft.domain.lcl.LclUnitSs; import com.gp.cong.logisoft.domain.lcl.LclUnitSsManifest; import java.math.BigDecimal; import java.util.Date; import org.hibernate.Criteria; import org.hibernate.SQLQuery; import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.Order; import org.hibernate.transform.Transformers; import org.hibernate.type.BigDecimalType; import org.hibernate.type.IntegerType; /** * * @author Logiware */ public class LclUnitSsManifestDAO extends BaseHibernateDAO<LclUnitSsManifest> { public LclUnitSsManifestDAO() { super(LclUnitSsManifest.class); } public LclUnitSsManifest getLclUnitSSManifestByHeader(Long unitId, Long headerId) throws Exception { Criteria criteria = getSession().createCriteria(LclUnitSsManifest.class, "lclUnitSsManifest"); criteria.createAlias("lclUnitSsManifest.lclUnit", "lclUnit"); criteria.createAlias("lclUnitSsManifest.lclSsHeader", "lclSsHeader"); if (!CommonUtils.isEmpty(unitId)) { criteria.add(Restrictions.eq("lclUnit.id", unitId)); } if (!CommonUtils.isEmpty(headerId)) { criteria.add(Restrictions.eq("lclSsHeader.id", headerId)); } criteria.addOrder(Order.desc("id")); return (LclUnitSsManifest) criteria.setMaxResults(1).uniqueResult(); } public LclUnitSsManifest insertUnitSsManifest(LclUnitSs lclUnitSs, LclUnit lclUnit, LclSsHeader lclssheader, User user, Date now, boolean isEntryManifest) throws Exception { LclUnitSsManifest lclunitssmanifest = this.getLclUnitSSManifestByHeader(lclUnit.getId(), lclssheader.getId()); if (lclunitssmanifest == null) { lclunitssmanifest = new LclUnitSsManifest(); lclunitssmanifest.setEnteredByUser(user); lclunitssmanifest.setEnteredDatetime(now); } if (isEntryManifest) { BigDecimal bigDecimal = new BigDecimal(0.00); ManifestBean manifestBean = this.entryManifestSSunit(lclUnitSs.getId()); lclunitssmanifest.setCalculatedBlCount(CommonUtils.isNotEmpty(manifestBean.getBlCount()) ? manifestBean.getBlCount() : 0); lclunitssmanifest.setCalculatedDrCount(CommonUtils.isNotEmpty(manifestBean.getDrCount()) ? manifestBean.getDrCount() : 0); lclunitssmanifest.setCalculatedTotalPieces(CommonUtils.isNotEmpty(manifestBean.getTotalPieceCount()) ? manifestBean.getTotalPieceCount() : 0); lclunitssmanifest.setCalculatedVolumeImperial(CommonUtils.isNotEmpty(manifestBean.getBlCft()) ? manifestBean.getBlCft() : bigDecimal); lclunitssmanifest.setCalculatedVolumeMetric(CommonUtils.isNotEmpty(manifestBean.getBlCbm()) ? manifestBean.getBlCbm() : bigDecimal); lclunitssmanifest.setCalculatedWeightImperial(CommonUtils.isNotEmpty(manifestBean.getBlLbs()) ? manifestBean.getBlLbs() : bigDecimal); lclunitssmanifest.setCalculatedWeightMetric(CommonUtils.isNotEmpty(manifestBean.getBlKgs()) ? manifestBean.getBlKgs() : bigDecimal); lclunitssmanifest.setLclUnit(lclUnit); lclunitssmanifest.setLclSsHeader(lclssheader); } lclunitssmanifest.setModifiedByUser(user); lclunitssmanifest.setModifiedDatetime(now); return lclunitssmanifest; } public void updateSsHeaderId(Long oldSsHeaderId, Long newSsHeaderId, Long unitId, Integer userId) throws Exception { StringBuilder queryStr = new StringBuilder(); queryStr.append("UPDATE lcl_unit_ss_manifest set ss_header_id =:newSsHeaderId, "); queryStr.append(" modified_datetime=:dateTime,modified_by_user_id=:userId "); queryStr.append(" WHERE ss_header_id =:oldSsHeaderId and unit_id=:unitId"); SQLQuery queryObject = getSession().createSQLQuery(queryStr.toString()); queryObject.setParameter("newSsHeaderId", newSsHeaderId); queryObject.setParameter("userId", userId); queryObject.setParameter("dateTime", new Date()); queryObject.setParameter("oldSsHeaderId", oldSsHeaderId); queryObject.setParameter("unitId", unitId); queryObject.executeUpdate(); } public void updateUnitId(Long ssHeaderId, Long oldUnitId, Long newUnitId, Integer userId) throws Exception { StringBuilder queryStr = new StringBuilder(); queryStr.append("UPDATE lcl_unit_ss_manifest set unit_id =:newUnitId, "); queryStr.append(" modified_datetime=:dateTime,modified_by_user_id=:userId "); queryStr.append(" WHERE ss_header_id =:ssHeaderId and unit_id=:oldUnitId"); SQLQuery queryObject = getSession().createSQLQuery(queryStr.toString()); queryObject.setParameter("ssHeaderId", ssHeaderId); queryObject.setParameter("oldUnitId", oldUnitId); queryObject.setParameter("newUnitId", newUnitId); queryObject.setParameter("userId", userId); queryObject.setParameter("dateTime", new Date()); queryObject.executeUpdate(); getCurrentSession().getTransaction().commit(); getCurrentSession().getTransaction().begin(); } public ManifestBean entryManifestSSunit(Long unitSSId) throws Exception { StringBuilder queryStr = new StringBuilder(); queryStr.append("SELECT SUM(fn.KGS) AS blKgs,SUM(fn.LBS) AS blLbs,SUM(fn.CBM) AS blCbm,SUM(fn.CFT) AS blCft,SUM(fn.pieces) AS totalPieceCount,"); queryStr.append("SUM(fn.BlCount) AS blCount, SUM(fn.DrCount) AS drCount FROM (SELECT lbp.actual_weight_metric AS KGS,"); queryStr.append("lbp.actual_weight_imperial AS LBS,lbp.actual_volume_metric AS CBM,lbp.actual_volume_imperial AS CFT,"); queryStr.append("lbp.actual_piece_count AS pieces,lcf.state ='BL' AS BlCount,lcf.state ='B' AS DrCount FROM "); queryStr.append("lcl_file_number lcf LEFT JOIN lcl_booking_piece lbp ON lbp.file_number_id = lcf.id "); queryStr.append("LEFT JOIN lcl_booking_piece_unit lbpu ON lbpu.`booking_piece_id` = lbp.id "); queryStr.append("LEFT JOIN `lcl_unit_ss` lus ON lus.id = lbpu.`lcl_unit_ss_id` WHERE lus.id =:unitSSId) fn"); SQLQuery query = getCurrentSession().createSQLQuery(queryStr.toString()); query.setLong("unitSSId", unitSSId); query.setResultTransformer(Transformers.aliasToBean(ManifestBean.class)); query.addScalar("blKgs", BigDecimalType.INSTANCE); query.addScalar("blLbs", BigDecimalType.INSTANCE); query.addScalar("blCbm", BigDecimalType.INSTANCE); query.addScalar("blCft", BigDecimalType.INSTANCE); query.addScalar("totalPieceCount", IntegerType.INSTANCE); query.addScalar("blCount", IntegerType.INSTANCE); query.addScalar("drCount", IntegerType.INSTANCE); return (ManifestBean) query.uniqueResult(); } }
9714feb4027e10c13bbc3fe828ca61228ce3e6db
ba495feb811bc008463165ef336d0940c1e9b2cc
/AtomSuiteModules/GUISuite/NiftyVisualEditor/jme3-gui/src/com/jme3/gde/gui/base/model/attributes/GColor.java
27374fd4b7a92473bed4f173fe2b7d8ef513435f
[]
no_license
atomixgame/atom-game-framework-sdk
a3dce7542eff3bda004c80ef7cab1e26666c3e33
4ac86ff6e469bc1f706ce6e43bdb37048ed22b7b
refs/heads/master
2021-08-02T10:35:13.161474
2015-09-27T02:20:05
2015-09-27T02:20:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
218
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jme3.gde.gui.base.model.attributes; /** * * @author cuong.nguyenmanh2 */ public class GColor { }
6cd1eda02587fe07740cff9a4d2a4b97f372657f
a7908ba24cba1b2912d87dc1d698c519e350cd5f
/game_server/common/src/main/java/network/NetClient.java
048e66e53f357e54b2be9850bbddc28ce3798ca0
[]
no_license
liligege/wz_game
1f776a55a05f7c9b2ac661f747d818f8740ba78f
6715a361ba7dededb870275daa8f645b87e395db
refs/heads/master
2020-03-28T14:05:43.112632
2017-09-18T14:50:59
2017-09-18T14:50:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,916
java
package network; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.InvalidProtocolBufferException; import actor.ICallback; import define.AppId; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import network.codec.MessageDecoder; import network.codec.MessageEncoder; import network.handler.ClientHandler; import packet.CocoPacket; import proto.Common; import proto.creator.CommonCreator; import protocol.c2s.RequestCode; import util.MiscUtil; /** * Created by Administrator on 2017/2/4. */ public class NetClient { private static Logger logger = LoggerFactory.getLogger(NetClient.class); private static final int REQUEST_FLAG = 0x10000000; /** * 多久后重连 */ private static final int RECONNECT_SECOND = 5; private String host; private int port; private List<String> registParam; private ChannelHandlerContext ioSession; private Bootstrap boot; private Map<Integer, TaskNode> nodeMap = new HashMap<>(); private AppId appId; //request handler ============================================= private int appDynamicId; private long connectServerStartTime; private AbstractHandlers handlers = null; private ICallback onSessionCloseCallBack = null; public NetClient(String host, int port) { this.host = host; this.port = port; } public void startConnect(ICallback callback) { boot = new Bootstrap(); boot.group(new NioEventLoopGroup()); boot.channel(NioSocketChannel.class); boot.option(ChannelOption.SO_KEEPALIVE, true); boot.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new MessageDecoder()); socketChannel.pipeline().addLast(new MessageEncoder()); socketChannel.pipeline().addLast(new ClientHandler(NetClient.this)); } }); connectToServer(callback); } public void sessionCreated(ChannelHandlerContext ctx) { this.ioSession = ctx; List<String> param = new ArrayList<>(); param.add(appId.getId() + ""); param.add(appDynamicId + ""); param.add(connectServerStartTime + ""); if (registParam != null) { param.addAll(registParam); } sendRequest(new CocoPacket(RequestCode.CENTER_REGISTER_SERVER , CommonCreator.stringList(param)), e -> { if (e instanceof CocoPacket == false) { return; } CocoPacket packet = (CocoPacket) e; try { Common.PBStringList req = Common.PBStringList.parseFrom(packet.getBytes()); appDynamicId = Integer.valueOf(req.getList(0)); connectServerStartTime = Long.valueOf(req.getList(1)); logger.info("receive the callback message and the result is {} , connectServerStartTime {}", appDynamicId, MiscUtil.getDateStrB(connectServerStartTime)); } catch (InvalidProtocolBufferException e1) { e1.printStackTrace(); } }); } public void sessionInActive(ChannelHandlerContext ctx) { if (onSessionCloseCallBack != null) { onSessionCloseCallBack.onResult(null); } // don't need reconnect is current version if (appId == AppId.GATE || appId == AppId.LOGIN || appId == AppId.LOG) { logger.error("{},serverId={}与center连接断开,{}秒后准备重连.", appId, appDynamicId, RECONNECT_SECOND); ctx.channel().eventLoop().schedule(() -> reconnect(ctx), RECONNECT_SECOND, TimeUnit.SECONDS); } else { logger.error("{},serverid={}与center连接断开,自动结束进程", appId, appDynamicId); System.exit(0); } } private void reconnect(ChannelHandlerContext ctx) { connectToServer(null); } public void messageReceived(ChannelHandlerContext ctx, CocoPacket packet) { int seqId = packet.getSeqId(); if (isRequestMessage(packet)) { handlers.handPacket(ctx, packet); } else { TaskNode node = nodeMap.get(seqId); if (node != null) { node.getCallback().onResult(packet); } } } private boolean isRequestMessage(CocoPacket packet) { if (packet.getReqId() > REQUEST_FLAG) { packet.setReqId(packet.getReqId() - REQUEST_FLAG); return true; } return false; } public void sendRequest(CocoPacket packet) { sendRequest(packet, null); } public void sendRequest(CocoPacket packet, ICallback callback) { if (callback != null) { TaskNode node = new TaskNode(ioSession, packet, callback); nodeMap.put(node.getSeqId(), node); } packet.setReqId(packet.getReqId() + REQUEST_FLAG); ioSession.writeAndFlush(packet); } //同步发送request public void sendRequestSync(CocoPacket packet, ICallback callback) { SyncResponse res = new SyncResponse(callback); sendRequest(packet, res); res.blockUntilResponse(); } public void connectToServer(ICallback callback) { ChannelFuture future = boot.connect(host, port); future.addListener(e -> { if (!e.isSuccess()) { logger.info(" connect to the server un success and reconnect {} sec later ", RECONNECT_SECOND); future.channel().eventLoop().schedule(() -> connectToServer(callback), RECONNECT_SECOND, TimeUnit.SECONDS); } else { if (callback != null) { callback.onResult(null); } } }); } public void setAppId(AppId appId) { this.appId = appId; } public void setRequestHandlers(AbstractHandlers handlers) { this.handlers = handlers; } public void setIoSession(ChannelHandlerContext ioSession) { this.ioSession = ioSession; } public int getServerId() { return appDynamicId; } public void setRegistParam(List<String> registParam) { this.registParam = registParam; } public void setOnSessionCloseCallBack(ICallback onSessionCloseCallBack) { this.onSessionCloseCallBack = onSessionCloseCallBack; } }
3ed985565a9a4c19ea21057a3448ca7311f901ec
99322d3d35d892fd520b502e536698fca8098b81
/src/com/zimnicky/draughts/Board.java
5919d051f6ff4d2ba9f1b172093a6cccd83a871c
[ "MIT" ]
permissive
zimnicky/draughts
9c37bcf275a456f9cabda9d7afa3132e3682f36b
f4c2e1507451d89bb56ed7243bdb700fd34581e9
refs/heads/master
2021-01-19T18:04:02.486124
2014-11-21T20:23:37
2014-11-21T23:24:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,848
java
package com.zimnicky.draughts; public class Board { public enum Cell { EMPTY, INVALID, BLACK, WHITE, BLACK_QUEEN, WHITE_QUEEN; boolean sameColor(Cell other) { return (isWhite() && other.isWhite()) || (isBlack() && other.isBlack()); } boolean sameColor(Player.Color color){ return (isWhite() && color == Player.Color.WHITE) || (isBlack() && color == Player.Color.BLACK); } boolean isQueen() { return this == BLACK_QUEEN || this == WHITE_QUEEN; } boolean isBlack() { return this == BLACK || this == BLACK_QUEEN; } boolean isWhite() { return this == WHITE || this == WHITE_QUEEN; } boolean isEmpty() { return this == EMPTY; } } private final static int defaultSize = 8; private int blackCells; // 0 -- empty or white piece, 1 -- black piece private int whiteCells; // 0 -- empty or black piece, 1 -- whitePiece private int queens; // 0 -- empty or not queen, 1 -- queen private void startPosition() { whiteCells = 0b11111111111100000000000000000000; blackCells = 0b00000000000000000000111111111111; queens = 0; // whiteCells = 0b00000000010000000000000000000000; // blackCells = 0b00000000000000001000000000000000; // queens = 0b00000000000000001000000000000000; // for (int i = 0; i < 8; i++){ // for (int j = 0; j < 8; j++){ // System.out.print(getCell(i, j) + " "); // } // System.out.println(); // } } private int getCellMask(int row, int col){ return 1 << (row*(defaultSize >> 1) + (col >> 1)); } public Board() { startPosition(); } public Board(Board board) { blackCells = board.blackCells; whiteCells = board.whiteCells; queens = board.queens; } public boolean isCorrectCell(int row, int col){ if (row < 0 || col < 0 || row >= defaultSize || col >= defaultSize || ((row*(defaultSize-1) + col) & 1) == 0){ return false; } return true; } public int getSize() { return defaultSize; } synchronized public Cell getCell(int row, int col) { if (!isCorrectCell(row,col)){ return Cell.INVALID; } int mask = getCellMask(row, col); if ((blackCells & mask) != 0){ if ((queens & mask) != 0){ return Cell.BLACK_QUEEN; } return Cell.BLACK; } else if ((whiteCells & mask) != 0){ if ((queens & mask) != 0){ return Cell.WHITE_QUEEN; } return Cell.WHITE; } return Cell.EMPTY; } synchronized public void setCell(int row, int col, Cell cell) { if (isCorrectCell(row,col)){ int mask = getCellMask(row, col); if (cell.isWhite()){ whiteCells |= mask; blackCells &= ~mask; } else if (cell.isBlack()){ blackCells |= mask; whiteCells &= ~mask; } else { blackCells &= ~mask; whiteCells &= ~mask; } if (cell.isQueen()){ queens |= mask; } else { queens &= ~mask; } } } synchronized public int getCountWhite() { return Integer.bitCount(whiteCells); } synchronized public int getCountBlack() { return Integer.bitCount(blackCells); } public int segmentCount(int startR, int startC, int distR, int distC, Cell color) { if (startR == distR || startC == distC){ return 0; } int count = 0; int dr = distR - startR; int dc = distC - startC; dr /= Math.abs(dr); dc /= Math.abs(dc); for (int i = startR, j = startC; i != distR && j != distC; i += dr, j += dc) { if (getCell(i, j).sameColor(color)) { count++; } } return count; } public int segmentCount(int startR, int startC, int distR, int distC, Player.Color color){ if (color == Player.Color.BLACK){ return segmentCount(startR, startC, distR, distC, Cell.BLACK); } return segmentCount(startR, startC, distR, distC, Cell.WHITE); } public int segmentCountOppositeColor(int startR, int startC, int distR, int distC, Cell color){ if (color.isBlack()){ return segmentCount(startR, startC, distR, distC, Cell.WHITE); } return segmentCount(startR, startC, distR, distC, Cell.BLACK); } public int segmentCountOppositeColor(int startR, int startC, int distR, int distC, Player.Color color){ if (color == Player.Color.BLACK){ return segmentCount(startR, startC, distR, distC, Cell.WHITE); } return segmentCount(startR, startC, distR, distC, Cell.BLACK); } public int segmentCountBlack(int startR, int startC,int lenR, int lenC) { return segmentCount(startR, startC, lenR, lenC, Cell.BLACK); } public int segmentCountWhite(int startR, int startC,int lenR, int lenC) { return segmentCount(startR, startC, lenR, lenC, Cell.WHITE); } public int sequenceLength(int startR, int startC, int dr, int dc) { if (Math.abs(dr) != 1 || Math.abs(dc) != 1 || !isCorrectCell(startR, startC)) return 0; int r = startR; int c = startC; Cell et = getCell(r, c); int count = 0; while (getCell(r, c) == et) { r += dr; c += dc; count++; } return count; } }