blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0d507d892adaa42607c7b48cb765fd2a1988a958
|
413439c4805774a051b0380a90bd5201bef4781f
|
/user/src/main/java/com/techsoltrackers/persistance/repository/UserRepository.java
|
f5b1f217852c63d40939282722c536d728c1c63c
|
[] |
no_license
|
sibeswar/LibraryProject
|
6d782a49d8ac6e38aff93415f0859f45e8f8aeef
|
7853591ceda84da000aba6adbaabe5739b8844b7
|
refs/heads/master
| 2020-12-26T10:46:53.542850 | 2020-02-03T17:37:20 | 2020-02-03T17:37:20 | 237,485,983 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 307 |
java
|
package com.techsoltrackers.persistance.repository;
import com.techsoltrackers.domain.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
}
|
[
"[email protected]"
] | |
16b9bf1f7dbe6d400357c48fad1f9502f905eeaa
|
9cf2e19f081b680e93cedc52a1736dddf57cd0fb
|
/src/com/company/工厂方法模式/NYStyleCheesePizza.java
|
84d6ecc19296012ecd96e75c54c67a27d2e1bc78
|
[] |
no_license
|
Yuwenbiao/DesignPattern
|
8632160e5e3ba1842b994720cb6eecbb674e74d8
|
da4722c8b7156ebf998f417fc16d724c379b3879
|
refs/heads/master
| 2021-07-05T05:11:53.205832 | 2017-09-30T01:08:59 | 2017-09-30T01:08:59 | 105,329,712 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 420 |
java
|
package com.company.工厂方法模式;
import com.company.工厂方法模式.Pizza;
/**
* 纽约风味披萨
*/
public class NYStyleCheesePizza extends Pizza {
public NYStyleCheesePizza() {
name="NY Style Sauce and Cheese Pizza";
dough="Thin Crust Dough";
sauce="Marinara Sauce";
toppings.add("Grated Reggiano Cheese");//上面覆盖的是意大利reggiano高级干酪
}
}
|
[
"[email protected]"
] | |
126e50ec69881668e0511728316bcb8b34c4c813
|
fc54621d13ef3b5dbf3f66604a8033bb5fe5f97f
|
/shardis-auth/src/main/java/com/shardis/auth/config/OAuth2AuthorizationConfig.java
|
ce992136b99c2467010bf3230ae3650640e9a966
|
[
"MIT"
] |
permissive
|
earandap/spring-angular2-starter
|
1f2ac7b10c09eeda42b80b599e8620fc03643f77
|
bde9eb42e0d9cfa480a490a68b2f88e0307c41e6
|
refs/heads/master
| 2021-01-21T03:08:08.534067 | 2016-04-21T20:52:02 | 2016-04-21T20:52:02 | 57,259,415 | 1 | 0 | null | 2016-04-28T01:06:16 | 2016-04-28T01:06:16 | null |
UTF-8
|
Java
| false | false | 2,534 |
java
|
package com.shardis.auth.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import java.security.KeyPair;
/**
* Created by Tomasz Kucharzyk
*/
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends
AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource("keystore.jks"), "foobar".toCharArray())
.getKeyPair("test");
converter.setKeyPair(keyPair);
return converter;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("acme")
.secret("acmesecret")
.authorizedGrantTypes("implicit","authorization_code", "refresh_token","password")
.scopes("openid")
.autoApprove(false);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).accessTokenConverter(jwtAccessTokenConverter());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
}
|
[
"[email protected]"
] | |
9be7f160629f746dc04464fcc6f2fa458cb95ee8
|
d8ecf24298e7bd32d0a1d5030d5f38c20230a0d9
|
/distuptor/src/main/java/base/LongEvent.java
|
1709ef4271223827116fa631865fef86c813a4a3
|
[] |
no_license
|
ZqLuo/architect
|
1bf37f5e330854d357e78e0bb1eb338341b850e5
|
16e61eb783038cc2dcd810c3f940c49b056e1e3e
|
refs/heads/master
| 2021-07-13T12:44:06.664789 | 2017-10-18T15:10:32 | 2017-10-18T15:10:32 | 100,600,154 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 255 |
java
|
package base;
/**
* Created by zqLuo
* 生产者生产的对象
*/
public class LongEvent {
private Long value;
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
}
|
[
"[email protected]"
] | |
843a3a4eeb34c2c306385cffde40f8af721ef536
|
4378862daf72958d875217defa4f9b11c3f367c0
|
/app/src/main/java/com/example/aarushi/tootha/ImagesActivity.java
|
8fbb3fa1ea88806215672f76b736dd94dfe43c7f
|
[] |
no_license
|
Aarushi-1/android
|
834cdaa0e7ec7cd47957d189f9fea08268f5fa07
|
7b1734aa22bb90909c420cd9923e71a9d63471fa
|
refs/heads/master
| 2021-07-06T02:27:15.363128 | 2020-09-30T05:20:48 | 2020-09-30T05:20:48 | 180,143,735 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,415 |
java
|
package com.example.aarushi.tootha;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ImagesActivity extends AppCompatActivity {
private RecyclerView mRecyclerview;
private ImageAdapter mAdapter;
private ProgressBar mProgress_circle;
private DatabaseReference mDatabaseRef;
private List<Uploading> mUploads;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fimages);
mRecyclerview =findViewById(R.id.recycler_view);
mRecyclerview.setHasFixedSize(true);
mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
mProgress_circle=findViewById(R.id.progress_circle);
mUploads =new ArrayList<>();
mDatabaseRef= FirebaseDatabase.getInstance().getReference("uploads");
mAdapter=new ImageAdapter(ImagesActivity.this,mUploads);
mRecyclerview.setAdapter(mAdapter);
mDatabaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Uploading uploading = postSnapshot.getValue(Uploading.class);
mUploads.add(uploading);
}
// mAdapter=new ImageAdapter(ImagesActivity.this,mUploads);
//mRecyclerview.setAdapter(mAdapter);
mProgress_circle.setVisibility(View.INVISIBLE);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this,databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgress_circle.setVisibility(View.INVISIBLE);
}
});
}
}
|
[
"[email protected]"
] | |
4385c154627dce9e7a7787c15c9b42ab6c8d83dc
|
7c4477a4bd2f5a3662338893ffdb87edbcce3257
|
/net/minecraft/server/BlockSign.java
|
1c4410cb3ea30f2d78a1d70f3fb86c53b4e09830
|
[] |
no_license
|
Xolsom/mc-dev
|
5921997d1793cf2a0ccc443c1c8b175a7f59ef1f
|
1a792ed860ebe2c6d4c40c52f3bc7b9e0789ca23
|
refs/heads/master
| 2020-12-24T11:17:37.185992 | 2011-07-08T12:23:08 | 2011-07-12T21:28:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,664 |
java
|
package net.minecraft.server;
import java.util.Random;
public class BlockSign extends BlockContainer {
private Class a;
private boolean b;
protected BlockSign(int i, Class oclass, boolean flag) {
super(i, Material.WOOD);
this.b = flag;
this.textureId = 4;
this.a = oclass;
float f = 0.25F;
float f1 = 1.0F;
this.a(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f);
}
public AxisAlignedBB e(World world, int i, int j, int k) {
return null;
}
public void a(IBlockAccess iblockaccess, int i, int j, int k) {
if (!this.b) {
int l = iblockaccess.getData(i, j, k);
float f = 0.28125F;
float f1 = 0.78125F;
float f2 = 0.0F;
float f3 = 1.0F;
float f4 = 0.125F;
this.a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
if (l == 2) {
this.a(f2, f, 1.0F - f4, f3, f1, 1.0F);
}
if (l == 3) {
this.a(f2, f, 0.0F, f3, f1, f4);
}
if (l == 4) {
this.a(1.0F - f4, f, f2, 1.0F, f1, f3);
}
if (l == 5) {
this.a(0.0F, f, f2, f4, f1, f3);
}
}
}
public boolean b() {
return false;
}
public boolean a() {
return false;
}
protected TileEntity a_() {
try {
return (TileEntity) this.a.newInstance();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
public int a(int i, Random random) {
return Item.SIGN.id;
}
public void doPhysics(World world, int i, int j, int k, int l) {
boolean flag = false;
if (this.b) {
if (!world.getMaterial(i, j - 1, k).isBuildable()) {
flag = true;
}
} else {
int i1 = world.getData(i, j, k);
flag = true;
if (i1 == 2 && world.getMaterial(i, j, k + 1).isBuildable()) {
flag = false;
}
if (i1 == 3 && world.getMaterial(i, j, k - 1).isBuildable()) {
flag = false;
}
if (i1 == 4 && world.getMaterial(i + 1, j, k).isBuildable()) {
flag = false;
}
if (i1 == 5 && world.getMaterial(i - 1, j, k).isBuildable()) {
flag = false;
}
}
if (flag) {
this.g(world, i, j, k, world.getData(i, j, k));
world.setTypeId(i, j, k, 0);
}
super.doPhysics(world, i, j, k, l);
}
}
|
[
"[email protected]"
] | |
9cf49c2da903bff7d97eb4274921028ba1ae24d2
|
e727e179e7e18f89b841d4a7e765eb591665fb2a
|
/survey-api/src/main/java/com/surveyapi/lambdahandlers/App.java
|
f81a22ae574c527ec04aba7a3f3f12b34f79bb3e
|
[] |
no_license
|
EswarGeeta/survey-api-java
|
d7223fd07e2ae415797053b9a1869d6b7d19c7e8
|
036f6f0b21223bece7b3c9d468a83544be4d1009
|
refs/heads/master
| 2023-06-14T10:08:38.977747 | 2021-07-12T15:45:48 | 2021-07-12T15:45:48 | 385,190,851 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,882 |
java
|
package com.surveyapi.lambdahandlers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
.withHeaders(headers);
try {
final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);
return response
.withStatusCode(200)
.withBody(output);
} catch (IOException e) {
return response
.withBody("{}")
.withStatusCode(500);
}
}
private String getPageContents(String address) throws IOException{
URL url = new URL(address);
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
}
|
[
"[email protected]"
] | |
24618d7c98cf743d87ecbd76627c4ca8b29a9b81
|
68997877e267f71388a878d37e3380e161f2f1bb
|
/app/src/main/java/com/sy/bottle/view/LineControllerView.java
|
6fc5daf5e9da71b7e85e2174e4d508526bb25c1a
|
[] |
no_license
|
jiangadmin/Bottle
|
1af8555efb6d54a314c500ec8e83fe795c20f796
|
582c7ab0eb216400980cd4aae830a3db131b66f6
|
refs/heads/master
| 2020-03-20T00:53:31.757289 | 2018-07-25T01:22:42 | 2018-07-25T01:22:42 | 137,059,653 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,258 |
java
|
package com.sy.bottle.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.sy.bottle.R;
/**
* 设置等页面条状控制或显示信息的控件
*/
public class LineControllerView extends LinearLayout {
private String name;
private boolean isBottom;
private String substance;
private boolean canNav;
private boolean isSwitch;
public LineControllerView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.view_line_controller, this);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LineControllerView, 0, 0);
try {
name = ta.getString(R.styleable.LineControllerView_name);
substance = ta.getString(R.styleable.LineControllerView_substance);
isBottom = ta.getBoolean(R.styleable.LineControllerView_isBottom, false);
canNav = ta.getBoolean(R.styleable.LineControllerView_canNav, false);
isSwitch = ta.getBoolean(R.styleable.LineControllerView_isSwitch, false);
setUpView();
} finally {
ta.recycle();
}
}
private void setUpView() {
TextView tvName = findViewById(R.id.name);
tvName.setText(name);
TextView tvContent = findViewById(R.id.content);
tvContent.setText(substance);
ImageView navArrow = findViewById(R.id.rightArrow);
navArrow.setVisibility(canNav ? VISIBLE : GONE);
LinearLayout contentPanel = findViewById(R.id.contentText);
contentPanel.setVisibility(isSwitch ? GONE : VISIBLE);
Switch switchPanel = findViewById(R.id.btnSwitch);
switchPanel.setVisibility(isSwitch ? VISIBLE : GONE);
}
/**
* 设置文字内容
*
* @param substance 内容
*/
public void setContent(String substance) {
this.substance = substance;
TextView tvContent = findViewById(R.id.content);
tvContent.setText(substance);
}
/**
* 获取内容
*/
public String getContent() {
TextView tvContent = findViewById(R.id.content);
return tvContent.getText().toString();
}
/**
* 设置是否可以跳转
*
* @param canNav 是否可以跳转
*/
public void setCanNav(boolean canNav) {
this.canNav = canNav;
ImageView navArrow = findViewById(R.id.rightArrow);
navArrow.setVisibility(canNav ? VISIBLE : GONE);
}
/**
* 设置开关状态
*
* @param on 开关
*/
public void setSwitch(boolean on) {
Switch mSwitch = findViewById(R.id.btnSwitch);
mSwitch.setChecked(on);
}
/**
* 设置开关监听
*
* @param listener 监听
*/
public void setCheckListener(CompoundButton.OnCheckedChangeListener listener) {
Switch mSwitch = findViewById(R.id.btnSwitch);
mSwitch.setOnCheckedChangeListener(listener);
}
}
|
[
"[email protected]"
] | |
9144751945c31a457012f7faa76fc4bf6099e433
|
9ab2aafe171e5613321cba8db46f9668817294cf
|
/hazelcast/src/main/java/com/hazelcast/spi/merge/package-info.java
|
6185c8107a190732ebf3653c9d9a077af0ba5986
|
[
"Apache-2.0"
] |
permissive
|
aboluo/hazelcast
|
230fa59932de877457e5b149752383891f2c63da
|
9aa3fb6870f19a48f3773296b774a8912f9082df
|
refs/heads/master
| 2021-05-13T13:04:06.815260 | 2018-01-08T11:58:18 | 2018-01-08T11:58:18 | 116,690,170 | 2 | 0 | null | 2018-01-08T14:56:59 | 2018-01-08T14:56:58 | null |
UTF-8
|
Java
| false | false | 736 |
java
|
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package contains out-of-the-box split brain merge policies.
*/
package com.hazelcast.spi.merge;
|
[
"[email protected]"
] | |
3fe11df0474381deb918631553c4f3860f9a7391
|
b765ff986f0cd8ae206fde13105321838e246a0a
|
/Inspect/app/src/main/java/com/growingio_rewriter/a/a/f/p.java
|
f4b0a3245bfe53affb393915032d61d274fc4eb7
|
[] |
no_license
|
piece-the-world/inspect
|
fe3036409b20ba66343815c3c5c9f4b0b768c355
|
a660dd65d7f40501d95429f8d2b126bd8f59b8db
|
refs/heads/master
| 2020-11-29T15:28:39.406874 | 2016-10-09T06:24:32 | 2016-10-09T06:24:32 | 66,539,462 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,373 |
java
|
/*
* Decompiled with CFR 0_115.
*/
package com.growingio.a.a.f;
import com.growingio.a.a.b.aU;
import com.growingio.a.a.f.a;
import com.growingio.a.a.f.m;
import com.growingio.a.a.f.q;
import com.growingio.a.a.f.r;
import com.growingio.a.a.f.s;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
class p {
private m b;
final Object a;
private final Method c;
private final Executor d;
static p a(m m2, Object object, Method method) {
return p.a(method) ? new p(m2, object, method) : new r(m2, object, method, null);
}
private p(m m2, Object object, Method method) {
this.b = m2;
this.a = aU.a(object);
this.c = method;
method.setAccessible(true);
this.d = m2.b();
}
final void a(Object object) {
this.d.execute(new q(this, object));
}
void b(Object object) throws InvocationTargetException {
try {
this.c.invoke(this.a, aU.a(object));
}
catch (IllegalArgumentException var2_2) {
throw new Error("Method rejected target/argument: " + object, var2_2);
}
catch (IllegalAccessException var2_3) {
throw new Error("Method became inaccessible: " + object, var2_3);
}
catch (InvocationTargetException var2_4) {
if (var2_4.getCause() instanceof Error) {
throw (Error)var2_4.getCause();
}
throw var2_4;
}
}
private s c(Object object) {
return new s(this.b, object, this.a, this.c);
}
public final int hashCode() {
return (31 + this.c.hashCode()) * 31 + System.identityHashCode(this.a);
}
public final boolean equals(Object object) {
if (object instanceof p) {
p p2 = (p)object;
return this.a == p2.a && this.c.equals(p2.c);
}
return false;
}
private static boolean a(Method method) {
return method.getAnnotation(a.class) != null;
}
static /* synthetic */ s a(p p2, Object object) {
return p2.c(object);
}
static /* synthetic */ m a(p p2) {
return p2.b;
}
/* synthetic */ p(m m2, Object object, Method method, q q2) {
this(m2, object, method);
}
}
|
[
"[email protected]"
] | |
522154fd2bf165750c2c1da784a42547f6565a13
|
4184ccc6c63cee6e9a32716ed5f6966b9007a8d3
|
/normalSpringJDBCTxn1/src/com/ddlab/spring/jdbc/txn/User.java
|
683f9e7ea2f6d51c7d51aab7c51bba82ac507234
|
[] |
no_license
|
debjava/OLD-Spring-Projects
|
21230f7551de16889dc891bc4a2826b11537e443
|
a5085bac5ea47c2e6cc9050479fa5cd84a47a276
|
refs/heads/master
| 2020-04-09T04:20:06.996725 | 2018-12-02T06:17:35 | 2018-12-02T06:17:35 | 160,018,704 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 455 |
java
|
package com.ddlab.spring.jdbc.txn;
public class User {
private int id;
private String username;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
[
"[email protected]"
] | |
34eda9ed74e4ca646fe61e25c05764ab5793f7d1
|
26736b2f502752f01f5f10d6789ca2f18f921901
|
/app/src/main/java/com/eleganzit/brightlet/adapters/MyTabAdapter.java
|
954472263f4aecfafb584a47d8d9fb3745d8a65f
|
[] |
no_license
|
ritueleganzit/BrightLET
|
b9fd2b6edb47d5959f82f615e0f30513d776b596
|
612fc391264e50c7b78abd5e55be570b5f61bafb
|
refs/heads/master
| 2020-03-17T23:20:51.516171 | 2018-07-03T11:58:37 | 2018-07-03T11:58:37 | 134,031,584 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,061 |
java
|
package com.eleganzit.brightlet.adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by Uv on 5/20/2018.
*/
public class MyTabAdapter extends FragmentPagerAdapter {
ArrayList<String> titleArrayList=new ArrayList<>();
ArrayList<Fragment> fragmentArrayList=new ArrayList<>();
public MyTabAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
@Override
public int getCount() {
return fragmentArrayList.size();
}
public void addFragment(Fragment fragment,String title)
{
fragmentArrayList.add(fragment);
titleArrayList.add(title);
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public CharSequence getPageTitle(int position)
{
return titleArrayList.get(position);
}
}
|
[
"[email protected]"
] | |
df633d03aae18c4a18a3194c05859ae87d70780a
|
fe78f4df3276378c87dbf20bf987ad7457d43b28
|
/src/main/java/top/momatech/dpdemo/factory/abstractfactory/operations/MinusOperation.java
|
eadf40ef7ddd635dba89af56f84196ccfcc9b46a
|
[] |
no_license
|
moma-tech/design-pattern
|
a764f6042b5ca74678691c0a69488d9b69c54e3e
|
2d73fab0bfd70ff7f11d70daae3c42585396e13d
|
refs/heads/master
| 2021-06-21T04:17:34.059972 | 2021-05-24T03:25:04 | 2021-05-24T03:25:04 | 207,522,054 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 359 |
java
|
package top.momatech.dpdemo.factory.abstractfactory.operations;
import top.momatech.dpdemo.factory.abstractfactory.Operation;
/**
* MinusOperation MInus
*
* @author Ivan
* @version 1.0 Created by Ivan at 2021/3/9.
*/
public class MinusOperation implements Operation {
@Override
public double getResult(double a, double b) {
return a - b;
}
}
|
[
"[email protected]"
] | |
6ed9522a1ff9e96ef2fc0882547a093b67cc52c1
|
279334893f11cfd639d39f266183e2e922ba31e8
|
/app/src/main/java/com/musyqa/android/eighttracks/Mix.java
|
7c7fe4950a2fb10c49a3409b00d9e1356be3dece
|
[] |
no_license
|
MusyqaDeveloper/Musyqa-for-Android
|
3e1e6bfe864e841bb5156d90e7c4a537dc076336
|
b2b9ab258775cfe35dd4c048effd54af8e5b408a
|
refs/heads/master
| 2021-01-18T07:02:30.943758 | 2013-01-28T22:26:24 | 2013-01-28T22:26:24 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,966 |
java
|
package com.musyqa.android.eighttracks;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
/**
* The Class Mix.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Mix extends BaseEntity {
/** The cover urls. */
@JsonProperty(value = "cover_urls")
private CoverUrls coverUrls;
/** The description. */
private String description;
/** The first published at. */
@JsonProperty(value = "first_published_at")
private Date firstPublishedAt;
/** The liked by current user. */
@JsonProperty(value = "liked_by_current_user")
private boolean likedByCurrentUser;
/** The likes count. */
@JsonProperty(value = "likes_count")
private int likesCount;
/** The name. */
private String name;
/** The nsfw. */
private boolean nsfw;
/** The path. */
private String path;
/** The plays count. */
@JsonProperty(value = "plays_count")
private int playsCount;
/** The published. */
private boolean published;
/** The slug. */
private String slug;
/** The tag list cache. */
@JsonProperty(value = "tag_list_cache")
private String tagListCache;
/** The user. */
private User user;
/**
* Gets the cover urls.
*
* @return the cover urls
*/
public CoverUrls getCoverUrls() {
return coverUrls;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Gets the first published at.
*
* @return the first published at
*/
public Date getFirstPublishedAt() {
return firstPublishedAt;
}
/**
* Gets the likes count.
*
* @return the likes count
*/
public int getLikesCount() {
return likesCount;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the path.
*
* @return the path
*/
public String getPath() {
return path;
}
/**
* Gets the plays count.
*
* @return the plays count
*/
public int getPlaysCount() {
return playsCount;
}
/**
* Gets the slug.
*
* @return the slug
*/
public String getSlug() {
return slug;
}
/**
* Gets the tag list cache.
*
* @return the tag list cache
*/
public String getTagListCache() {
return tagListCache;
}
/**
* Gets the user.
*
* @return the user
*/
public User getUser() {
return user;
}
/**
* Checks if is liked by current user.
*
* @return true, if is liked by current user
*/
public boolean isLikedByCurrentUser() {
return likedByCurrentUser;
}
/**
* Checks if is nsfw.
*
* @return true, if is nsfw
*/
public boolean isNsfw() {
return nsfw;
}
/**
* Checks if is published.
*
* @return true, if is published
*/
public boolean isPublished() {
return published;
}
/**
* Sets the cover urls.
*
* @param coverUrls the new cover urls
*/
public void setCoverUrls(CoverUrls coverUrls) {
this.coverUrls = coverUrls;
}
/**
* Sets the description.
*
* @param description the new description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Sets the first published at.
*
* @param firstPublishedAt the new first published at
*/
public void setFirstPublishedAt(Date firstPublishedAt) {
this.firstPublishedAt = firstPublishedAt;
}
/**
* Sets the liked by current user.
*
* @param likedByCurrentUser the new liked by current user
*/
public void setLikedByCurrentUser(boolean likedByCurrentUser) {
this.likedByCurrentUser = likedByCurrentUser;
}
/**
* Sets the likes count.
*
* @param likesCount the new likes count
*/
public void setLikesCount(int likesCount) {
this.likesCount = likesCount;
}
/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the nsfw.
*
* @param nsfw the new nsfw
*/
public void setNsfw(boolean nsfw) {
this.nsfw = nsfw;
}
/**
* Sets the path.
*
* @param path the new path
*/
public void setPath(String path) {
this.path = path;
}
/**
* Sets the plays count.
*
* @param playsCount the new plays count
*/
public void setPlaysCount(int playsCount) {
this.playsCount = playsCount;
}
/**
* Sets the published.
*
* @param published the new published
*/
public void setPublished(boolean published) {
this.published = published;
}
/**
* Sets the slug.
*
* @param slug the new slug
*/
public void setSlug(String slug) {
this.slug = slug;
}
/**
* Sets the tag list cache.
*
* @param tagListCache the new tag list cache
*/
public void setTagListCache(String tagListCache) {
this.tagListCache = tagListCache;
}
/**
* Sets the user.
*
* @param user the new user
*/
public void setUser(User user) {
this.user = user;
}
}
|
[
"[email protected]"
] | |
0b8f2931e446f5ec1b2240211a27528dffc30234
|
e38b108ea0b2f12090ab1aa9e4f26fd82b98aeb1
|
/src/test/java/ru/spsuace/homework2/collections/SymmetricDifferenceTest.java
|
5c16b5b6a3720aa8506a304798a8b509c986f853
|
[] |
no_license
|
raskiri/spsuace--homework2
|
904f71ea307efdea587e04f81322fe5e31cfcc99
|
d7f7e7331b47037417cf9000b1f148a6cf97bcec
|
refs/heads/master
| 2021-02-08T23:13:13.946224 | 2020-05-22T00:28:50 | 2020-05-22T00:28:50 | 244,208,574 | 1 | 0 | null | 2020-03-01T19:15:17 | 2020-03-01T19:15:17 | null |
UTF-8
|
Java
| false | false | 2,403 |
java
|
package ru.spsuace.homework2.collections;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.*;
public class SymmetricDifferenceTest {
@Test
public void symmetricDifference_empty() {
Set<String> a = Collections.emptySet();
Set<String> b = Collections.emptySet();
assertEquals(Collections.emptySet(), SymmetricDifference.symmetricDifference(a, b));
assertEquals(Collections.emptySet(), a);
assertEquals(Collections.emptySet(), b);
}
@Test
public void symmetricDifference_Simple() {
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> b = new HashSet<>(Arrays.asList(0, 1, 2));
Set<Integer> c = new HashSet<>(Arrays.asList(0, 3));
assertEquals(c, SymmetricDifference.symmetricDifference(a, b));
assertEquals(new HashSet<>(Arrays.asList(1, 2, 3)), a);
assertEquals(new HashSet<>(Arrays.asList(0, 1, 2)), b);
}
@Test
public void symmetricDifference_Hard() {
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 3, 6, 7, 9, 10));
Set<Integer> b = new HashSet<>(Arrays.asList(3, 4, 6, 2, 10, 12));
Set<Integer> c = new HashSet<>(Arrays.asList(1, 7, 9, 4, 12));
assertEquals(c, SymmetricDifference.symmetricDifference(a, b));
assertEquals(new HashSet<>(Arrays.asList(1, 2, 3, 6, 7, 9, 10)), a);
assertEquals(new HashSet<>(Arrays.asList(3, 4, 6, 2, 10, 12)), b);
}
@Test
public void symmetricDifference_firstEmpty() {
Set<String> a = Collections.emptySet();
Set<Integer> b = new HashSet<>(Arrays.asList(0, 1, 2));
Set<Integer> c = new HashSet<>(Arrays.asList(0, 1, 2));
assertEquals(new HashSet<>(Arrays.asList(0, 1, 2)), c);
assertEquals(Collections.emptySet(), a);
assertEquals(new HashSet<>(Arrays.asList(0, 1, 2)), b);
}
@Test
public void symmetricDifference_secondEmpty() {
Set<Integer> a = new HashSet<>(Arrays.asList(0, 1, 2));
Set<String> b = Collections.emptySet();
Set<Integer> c = new HashSet<>(Arrays.asList(0, 1, 2));
assertEquals(new HashSet<>(Arrays.asList(0, 1, 2)), c);
assertEquals(Collections.emptySet(), b);
assertEquals(new HashSet<>(Arrays.asList(0, 1, 2)), a);
}
}
|
[
"[email protected]"
] | |
331df51de137fab74b03a82a00bafc1fabed1575
|
c6ce20fabfcf7f4d8343df3572c75dd248a88722
|
/src/main/java/ru/buinovsky/distillers/repository/jpa/JpaOrderRepository.java
|
9ce2620505a3b9761a2262d43495202c84e16721
|
[] |
no_license
|
BuinovskyD/distillers
|
9f45e7bb2527b5895e9f98b5fd2933623ac267f8
|
bab0421be42133ae5a42746bdc5288584bd1df96
|
refs/heads/master
| 2022-12-29T09:59:18.861383 | 2020-10-14T04:44:16 | 2020-10-14T04:44:16 | 301,740,611 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,518 |
java
|
package ru.buinovsky.distillers.repository.jpa;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ru.buinovsky.distillers.model.Order;
import ru.buinovsky.distillers.model.User;
import ru.buinovsky.distillers.repository.OrderRepository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDate;
import java.util.List;
@Repository
@Transactional(readOnly = true)
public class JpaOrderRepository implements OrderRepository {
@PersistenceContext
private EntityManager em;
@Override
public Order get(int id, int userId) {
Order order = em.find(Order.class, id);
if (order != null && order.getUser().getId() == userId) {
return order;
} else {
return null;
}
}
@Override
@Transactional
public Order save(Order order, int userId) {
order.setUser(em.getReference(User.class, userId));
if (order.isNew()) {
em.persist(order);
return order;
} else if (get(order.getId(), userId) == null) {
return null;
}
return em.merge(order);
}
@Override
@Transactional
public void delete(int id, int userId) {
Order order = em.getReference(Order.class, id);
if (order.getUser().getId() == userId) {
em.remove(order);
}
}
@Override
public List<Order> getAll() {
return em.createNamedQuery(Order.ALL_SORTED, Order.class)
.getResultList();
}
@Override
public List<Order> getAllByUser(int userId) {
return em.createNamedQuery(Order.ALL_SORTED_BY_USER, Order.class)
.setParameter("userId", userId)
.getResultList();
}
@Override
public List<Order> getFiltered(LocalDate startDate, LocalDate endDate) {
return em.createNamedQuery(Order.ALL_FILTERED, Order.class)
.setParameter("startDate", startDate)
.setParameter("endDate", endDate)
.getResultList();
}
@Override
public List<Order> getFilteredByUser(LocalDate startDate, LocalDate endDate, int userId) {
return em.createNamedQuery(Order.ALL_FILTERED_BY_USER, Order.class)
.setParameter("userId", userId)
.setParameter("startDate", startDate)
.setParameter("endDate", endDate)
.getResultList();
}
}
|
[
"[email protected]"
] | |
b1b760e0aa71e9338e96761d8e701e39c3eb0762
|
569ea7d1c25afe15d9abe8a94aa95d0a30663854
|
/shogun-lib/src/main/java/de/terrestris/shoguncore/enumeration/PermissionCollectionType.java
|
18d9a5bfbcc1d69b5e1aa13fd7b1bf39ddfc89f6
|
[] |
no_license
|
hwbllmnn/shogun-1
|
a1a1b47f80618c2753fcf35e7f19964b52c91329
|
ef6bd98a675e49b62f6d92fb779975bbad0f0fbe
|
refs/heads/master
| 2021-04-17T08:48:42.472105 | 2020-03-05T08:28:28 | 2020-03-05T08:28:28 | 249,430,626 | 0 | 0 | null | 2020-03-23T12:55:00 | 2020-03-23T12:54:59 | null |
UTF-8
|
Java
| false | false | 655 |
java
|
package de.terrestris.shoguncore.enumeration;
public enum PermissionCollectionType {
CREATE("CREATE"),
CREATE_READ("CREATE_READ"),
CREATE_READ_UPDATE("CREATE_READ_UPDATE"),
CREATE_READ_DELETE("CREATE_READ_DELETE"),
CREATE_UPDATE("CREATE_UPDATE"),
CREATE_UPDATE_DELETE("CREATE_UPDATE_DELETE"),
CREATE_DELETE("CREATE_DELETE"),
READ("READ"),
READ_UPDATE("READ_UPDATE"),
READ_DELETE("READ_DELETE"),
UPDATE("UPDATE"),
UPDATE_DELETE("UPDATE_DELETE"),
DELETE("DELETE"),
ADMIN("ADMIN");
private final String type;
private PermissionCollectionType(String type) {
this.type = type;
}
}
|
[
"[email protected]"
] | |
77e6911e19c49c9992696d7624a5e4c990a8d151
|
61cd8869f439d5d604cd9526b18a7a2c42903c95
|
/src/com/trs/rms/base/page/PageCriterion.java
|
79743334e89d9094697117c145a8f59704ac9765
|
[] |
no_license
|
TRSFinance/rms
|
e81e5d3d324829d19cca8a967bcce2a295794dc5
|
ddbe9fb2983f63a9e42489f1e624f87f84fa1f83
|
refs/heads/master
| 2020-04-14T14:43:35.961132 | 2016-11-01T13:58:17 | 2016-11-01T13:58:17 | 68,164,004 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,270 |
java
|
package com.trs.rms.base.page;
/**
* 分页条件。
* @author wengjing
* @author 邹许红
*
*/
public class PageCriterion {
//fields ---------------------------------------------------------------------
/**
* 每页的记录数。
*/
private int pageSize;
/**
* 页号,从1开始。
*/
private int pageNum;
// methods --------------------------------------------------------------
public PageCriterion(int pageSize, int pageNum) {
super();
this.pageSize = pageSize;
this.pageNum = pageNum;
}
public PageCriterion() {
super();
}
public OffsetLimit toOffsetLimit(){
return new OffsetLimit((pageNum-1)*pageSize, pageSize);
}
//accessors ---------------------------------------------------------------------
/**
* 获取每页的记录数。
*
* @return 每页的记录数
*/
public int getPageSize() {
return pageSize;
}
/**
* 设置每页的记录数。
*
* @param pageSize 每页的记录数
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* 获取页号。
*
* @return 页号
*/
public int getPageNum() {
return pageNum;
}
/**
* 设置页号。
*
* @param pageNum 页号
*/
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
}
|
[
"[email protected]"
] | |
d3fda10c85dc57fc2d1d0f33c82e29579081375a
|
a24184aca11ab7cfce7d290422d25fa2224f9289
|
/app/src/main/java/com/civi/U02916C.java
|
7e74ed715917d587058e3304ed5c91d6a4c263d5
|
[] |
no_license
|
Opendat/U0293C4
|
d325575f397fad14433600ada0f82f64db027807
|
e22474041dd4a956b059cc7008fac390bd1e125e
|
refs/heads/master
| 2021-06-09T12:30:07.790757 | 2016-11-30T19:21:42 | 2016-11-30T19:21:42 | 74,577,259 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 72,789 |
java
|
package com.civi;
import android.app.Activity;
import android.app.Notification;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.civi.Activities.EventsActivity;
import com.civi.Activities.FirstTimeActivity;
import com.civi.Activities.MainActivity;
import com.civi.Activities.MenuAdminActivity;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.MarshalHashtable;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import Opendat.Registro_del_Tiempo.Clases_Genericas.AntecedentesPersona;
import Opendat.Registro_del_Tiempo.Clases_Genericas.Portico;
import Opendat.Registro_del_Tiempo.Clases_Genericas.EventoPuertaMagnetica;
import Opendat.Registro_del_Tiempo.Clases_Genericas.RegistroMarca;
import Opendat.Registro_del_Tiempo.Clases_Genericas.RegistroTransito;
/**
* Clase que representa el webservice a utilizar.
*
* Modificaciones:
* Fecha Autor Descripcion
* -------------------------------------------------------------------------------------------------
* 12.10.2016 Jonathan Vasquez Creacion de Clase
* 25.10.2016 Jonathan Vasquez Creacion de objeto en diccionario y modificacion de nombre de ws a U02916C (Anteriormente U021E30).
* 02.11.2016 Jonathan Vasquez Encriptación de identificadores de las funciones de ws, generacion de Ants_Verificacion.
*/
public class U02916C {
private static final String TAG = "AppMRAT";
private AlertDialog.Builder alertDialog = null;
private ProgressDialog progressDialog = null;
private ProgressBar miBarra = null;
//variable que almacena el URL del Webservice desde los parametros del sistema.
private String URL;
private AsyncTask.Status estadoCall;
private String NAMESPACE = "http://tempuri.org/";
Globals global = Globals.getInstance();
Activity origen; //variable usada en 'CallFechaHora_verificacionWS' cuyo objetivo es diferenciar la logica dependiendo del llamado.
/**
* Constructores.
*/
public U02916C(){}
public U02916C(String pstrURL) {
this.URL = pstrURL;
estadoCall = null;
}
public void configAlertDialog(final Activity activity){
alertDialog = new AlertDialog.Builder(activity);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface alertDialog, int which) {
if(activity instanceof EventsActivity){
//se retorna a MainActivity;
activity.setResult(Activity.RESULT_OK);
activity.finish();
}else if(activity instanceof MainActivity){
//cancelo.
alertDialog.cancel();
}else if(activity instanceof FirstTimeActivity){
alertDialog.cancel();
}else if(activity instanceof MenuAdminActivity){
alertDialog.cancel();
}
}
});
}
//getter and setters
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public AsyncTask.Status getEstadoCall() {
return estadoCall;
}
public AlertDialog.Builder getAlertDialog() {
return alertDialog;
}
public void setAlertDialog(AlertDialog.Builder alertDialog) {
this.alertDialog = alertDialog;
}
public ProgressBar getMiBarra() {
return miBarra;
}
public void setMiBarra(ProgressBar miBarra) {
this.miBarra = miBarra;
}
/**
* Funcion usaba tanto para obtener la hora del servidor como para la verificacion de la existencia del webservice.
*/
public void verificarWS(Activity llamado, String pstrId_Portico){
this.origen = llamado;
configAlertDialog(llamado);
//no hay parametros, no va PropertyInfo.
Log.i(TAG, "Ejecutando hilo llamado a ws...");
new CallFechaHora_verificacionWS().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"U02916D",llamado.getLocalClassName(), pstrId_Portico);
//call.execute("ObtenerFechaHora");
}
public void Buscar_Portico(Activity llamado, String pstrId_Portico){
Log.i(TAG, "Llamado 'Buscar_Portico' realizado");
this.origen = llamado;
//new CallWSDato().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"Buscar_Portico", pstrId_Portico);
new CallWSBuscar_Portico().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Portico);
}
public void Disponibilidad_Puerta_Magnetica(Activity llamado, ProgressBar pb, String pstrId_Portico){
Log.i(TAG, "Llamado 'Disponibilidad chapa' realizada");
this.origen = llamado;
configAlertDialog(llamado);
if(origen instanceof MenuAdminActivity){
miBarra = pb;
}
//new CallWSDato().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"Get_DisponibilidadChapaElectrica", pstrId_Portico);
new CallWSDisponibilidad_Puerta_Magnetica().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Portico);
}
public void Verificar_Portico(Activity llamado, ProgressBar pb, String pstrId_Portico){
Log.i(TAG, "Llamado 'Verificar Disponibilidad Portico' realizada");
this.origen = llamado;
configAlertDialog(llamado);
if(origen instanceof MenuAdminActivity){
miBarra = pb;
}
new CallWSVerificar_Portico().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Portico);
}
public void Credencial_Admin(Activity llamado, ProgressBar pb){
Log.i(TAG, "Llamado 'Credencial_Admin' realizada");
this.origen = llamado;
configAlertDialog(llamado);
if(origen instanceof MenuAdminActivity){
miBarra = pb;
}
new CallWSCredencial_Admin().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void Localizacion_Geografica(Activity llamado, ProgressBar pb, String pstrId_Portico){
Log.i(TAG, "Llamado 'Localizacion_Geografica' realizada");
this.origen = llamado;
configAlertDialog(llamado);
if(origen instanceof MenuAdminActivity){
miBarra = pb;
}
new CallWSLocalizacion_Geografica().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Portico);
}
public void Eventos_Con_Puerta_Magnetica(Activity llamado, String pstrId_Portico){
this.origen = llamado;
new CallWSEventos_Puerta_Magnetica().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Portico);
}
public void Antecedentes_Verificacion(Activity llamado, String pstrId_Credencial, String pstrPortico){
this.origen = llamado;
configAlertDialog(llamado);
new CallWSAnts_VerificacionNoFotoHuella().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Credencial, pstrPortico);
}
public void Antecedentes_Verificacion_SinFoto(Activity llamado, String pstrId_Credencial, String pstrPortico){//usado para actualizar ldv.
this.origen = llamado;
configAlertDialog(llamado);
/*alertDialog = new AlertDialog.Builder(origen);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface alertDialog, int which) {
alertDialog.cancel();
}
});*/
new CallWSAnts_VerificacionNoFoto().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Credencial, pstrPortico);
}
public void Antecedente_Fotografia(Activity llamado, String pstrId_Credencial, String pstrPortico){
this.origen = llamado;
new CallWSAnts_Veri_Foto().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Credencial, pstrPortico);
}
public void Antecedente_Huella(Activity llamado, String pstrId_Credencial, String pstrPortico){
this.origen = llamado;
}
public void Verificar_Reingreso(Activity llamado, String pstrId_Credencial, String pstrEvento, String pstrPortico){
this.origen = llamado;
new CallWSVerificar_Reingreso().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pstrId_Credencial, pstrEvento, pstrPortico);
}
public void InsertMarca(Activity llamado,String mensajeMarca,
String pstrId_Credencial, String pstrEvento, String pstrId_Portico,
int pintId_Verificacion, String pstrId_Persona, String pstrTipo_Credencial, String pstrNivel_Autenti,
String pstrTipo_Transaccion, String pstrEstado_Transaccion, String pstrEstado_Transferencia,
String pstrLocalizacion_Geo, String pstrOrigen_Marca){
this.origen = llamado;
configAlertDialog(llamado);
progressDialog = new ProgressDialog(origen);
progressDialog.setTitle("Registrando Marcaje...");
progressDialog.setMessage(mensajeMarca);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setMax(100);
if(pintId_Verificacion == -1){ //equivalente a que no tiene verificacion.
new CallWSInsertar_Marca(progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
pstrId_Credencial, pstrEvento, pstrId_Portico, null, pstrId_Persona, pstrTipo_Credencial, pstrNivel_Autenti,
pstrTipo_Transaccion, pstrEstado_Transaccion, pstrEstado_Transferencia, pstrLocalizacion_Geo, pstrOrigen_Marca);
}else{
new CallWSInsertar_Marca(progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
pstrId_Credencial, pstrEvento, pstrId_Portico, String.valueOf(pintId_Verificacion), pstrId_Persona, pstrTipo_Credencial,
pstrNivel_Autenti, pstrTipo_Transaccion, pstrEstado_Transaccion, pstrEstado_Transferencia,
pstrLocalizacion_Geo, pstrOrigen_Marca);
}
}
public void InsertTransito(Activity llamado, String pstrId_Portico, String pstrId_Credencial
, String pstrId_Persona){
this.origen = llamado;
configAlertDialog(llamado);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date datenow = new Date(); //solo para desplegar la fecha y hora del dispositivo.
progressDialog = new ProgressDialog(origen);
progressDialog.setTitle("Registrando Transito...");
progressDialog.setMessage("Hora de transito: "+dateFormat.format(datenow));
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setMax(100);
new CallWSInsertar_Marca_Transito(progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
pstrId_Portico, pstrId_Credencial, pstrId_Persona);
}
public void InsertTransitoOffline(Activity llamado, ProgressBar pb, List<RegistroTransito> registrosTransito){
this.origen = llamado;
configAlertDialog(llamado);
this.miBarra = pb;
new CallWSInsertar_Marca_Transito_Offline(registrosTransito).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void InsertMarcaOffline(Activity llamado, ProgressBar pb, List<RegistroMarca> registrosMarca){
this.origen = llamado;
configAlertDialog(llamado);
this.miBarra = pb;
new CallWSInsertar_Marca_Offline(registrosMarca).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
//threads
private class CallFechaHora_verificacionWS extends AsyncTask<String, Void, String[]> {
String idPortico;
@Override
protected String [] doInBackground(String... params){
Log.i(TAG, "CallFechaHora_verificacionWS en backGround...: "+NAMESPACE+params[0]+ "URL: "+URL);
estadoCall = this.getStatus();//obtengo el estado.
String [] result = new String [3];
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, params[0]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try{
transporte.call(NAMESPACE + params[0], envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive)envelope.getResponse();
result[0] = resSoap.toString(); //resultado del llamado (Fecha)
result[1] = params[0]; //nombre de la funcion.
result[2] = params[1]; //nombre de la clase en donde fue llamado. (FirstTimeActivity, MainActivity).
idPortico = params[2]; //id de portico
}catch (SoapFault sf){
String faultString = "FAULT: Code: " + sf.faultcode + "\nString: " +
sf.faultstring;
Log.d(TAG , "fault : " + faultString);
}
catch (IOException e) {//entra aqui cuando no logra realizar la coneccion.
//e.printStackTrace();
Log.e(TAG, "Excepcion de IOE (ws): " + e.getMessage());
result = null;
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
Log.e(TAG, "Excepcion de XmlPullParser");
result = null;
cancel(true);
}
Log.i(TAG, "Saliendo de background...");
return result;
}
@Override
protected void onCancelled(String [] result){
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
Log.i(TAG, "Entra a funcion onCancelled de verificacion ws");
Notificacion("No es posible conectarse a WS");
if(origen instanceof FirstTimeActivity){
((FirstTimeActivity) origen).ConfiguracionSistema_CorteSecuenciaHilo();
}
}
@Override
protected void onPostExecute(String [] resultado){
Log.i(TAG, "Entra a funcion PostExecute de verificacion ws");
estadoCall = this.getStatus();
Log.i(TAG, "Resultado final: "+resultado[0]);
global.setDato(resultado[0]);
//se verifica la existencia del portico.
new CallWSBuscar_Portico().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, idPortico);
//new CallWSDato().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "Get_LocalizacionGeografica", idPortico);
Log.i(TAG, "resto el hilo de verificacion de ws");
global.decrementThread();
if (global.getNumThreads() == 0){
Log.i(TAG, "ultimo hilo: Verificacion WS");
//miBarra.setVisibility(View.INVISIBLE);
if(resultado[2].equals("Activities.FirstTimeActivity")){
//origen.GeneracionConfig();
((FirstTimeActivity)origen).configuracionSistema();
}
}
}
}
private class CallWSVerificar_Portico extends AsyncTask<String, Void, List<Portico>>{
List<Portico> listaPortico;
private String nombreFuncion = "U029170";
@Override
protected List<Portico> doInBackground(String... params) {
Log.i(TAG, "comienzo de ejecucion en background de hilo 'Verificar_portico'");
String result;
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
//parametros.
request.addProperty("pstrCod_Portico", params[0]); //sensible a nombre de parametros.
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapObject resSoap = (SoapObject) envelope.getResponse();
//se interpreta la lista.
listaPortico = new ArrayList<>();
for(int i = 0; i < resSoap.getPropertyCount(); i++){
SoapObject ic = (SoapObject) resSoap.getProperty(i);
Portico p = new Portico();
p.set_ubicacion(ic.getProperty(0).toString());
p.set_descripcion_ubicacion(ic.getProperty(1).toString());
p.set_site(ic.getProperty(2).toString());
p.set_cod_centro_trabajo(ic.getProperty(3).toString());
p.set_descripcion_centro_trabajo(ic.getProperty(4).toString());
p.set_tipo_dependencia(ic.getProperty(5).toString());
p.set_exclusividad_cdt(ic.getProperty(6).toString());
p.set_empresa_exclusiva(ic.getProperty(7).toString());
p.set_cod_portico(ic.getProperty(8).toString());
p.set_descripcion_portico(ic.getProperty(9).toString());
p.set_tipo_portico(ic.getProperty(10).toString());
p.set_coordenadas(ic.getProperty(11).toString());
p.set_tipo_disposicion(ic.getProperty(12).toString());
p.set_clase_credencializacion(ic.getProperty(13).toString());
p.set_tipo_dispositivo(ic.getProperty(14).toString());
p.set_identificacion_dispositivo(ic.getProperty(15).toString());
p.set_direccion_ip(ic.getProperty(16).toString());
p.set_mascara_ip(ic.getProperty(17).toString());
p.set_get_way(ic.getProperty(18).toString());
listaPortico.add(p);
}
} catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
listaPortico = null;
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
listaPortico = null;
cancel(true);
}
return listaPortico;
}
@Override
protected void onCancelled(List<Portico> result) {
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
Log.i(TAG, "Se ha entrado a funcion onCancelled de verificar_portico");
Notificacion("No ha sido posible obtener la informacion sobre el portico");
if(origen instanceof FirstTimeActivity){
((FirstTimeActivity) origen).ConfiguracionSistema_CorteSecuenciaHilo();
}
}
@Override
protected void onPostExecute(List<Portico> respuesta){
Log.i(TAG, "Ingreso a funcion onPOst de verificar_portico");
//asigno a parametro de sistema al tipo de disposisicion del dispositivo.
if(respuesta.size() == 0){
Notificacion("No ha sido posible obtener la informacion sobre el portico");
if(origen instanceof FirstTimeActivity){
((FirstTimeActivity) origen).ConfiguracionSistema_CorteSecuenciaHilo();
}
}else{
global.getParametrosSistema().set_Disposicion(respuesta.get(0).get_tipo_disposicion());
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: verificar_portico");
if(origen instanceof FirstTimeActivity){//se que sera para configuracion.
Log.i(TAG, "retorno a FirstTimeActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
//envio al siguiente bloque logico.
//((FirstTimeActivity)origen).continuacion();
((FirstTimeActivity)origen).generateXML();
}else if(origen instanceof MainActivity){//sin uso, solo como informacion de retorno
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
Log.i(TAG, "retorno a MainActivity");
}else if(origen instanceof MenuAdminActivity){//lamado desde interfaz de administracion.
Log.i(TAG, "Retorno a MenuAdminActivity");
if(miBarra.getProgress() < miBarra.getMax()){
miBarra.setProgress(miBarra.getProgress() +1);
}
((MenuAdminActivity) origen).ProcesoActualizacionParametros_TerminoHilo();
}
}
}
}
}
private class CallWSBuscar_Portico extends AsyncTask<String, Void, String>{
private String nombreFuncion = "U02916E";
@Override
protected String doInBackground(String... params){
Log.i(TAG, "Entro a hilo Buscar_Portico");
String result;
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
//parametros.
request.addProperty("idPortico", params[0]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
result = resSoap.toString();
} catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
result = null;
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
result = null;
cancel(true);
}
return result;
}
@Override
protected void onCancelled(String result){
Log.i(TAG, "Entra a funcion onCancelled de Buscar_portico");
Notificacion("No es posible obtener la informacion del portico ingresado");
if(origen instanceof FirstTimeActivity){
((FirstTimeActivity) origen).ConfiguracionSistema_CorteSecuenciaHilo();
}
}
@Override
protected void onPostExecute(String resultado){
Log.i(TAG, "Entro a funcion onPost de funcion Buscar_Portico, resultado: "+resultado);
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: Buscar_portico");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
if(origen instanceof FirstTimeActivity){//se que sera para configuracion.
Log.i(TAG, "retorno a FirstTimeActivity");
((FirstTimeActivity)origen).configuracionSistema();
}else if(origen instanceof MainActivity){
Log.i(TAG, "retorno a MainActivity");
}
}
}
}
private class CallWSDisponibilidad_Puerta_Magnetica extends AsyncTask<String, Void, String> {
private String nombreFuncion = "U02916F";
private String idPortico;
@Override
protected String doInBackground(String... params){
Log.i(TAG, "Entro al hilo de disponibilidad de puerta magnetica");
String result;
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
//parametros.
//request.addProperty("IdPortico", params[1]);
request.addProperty("idPortico", params[0]);
idPortico = params[0];
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
result = resSoap.toString();
} catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
result = null;
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
result = null;
cancel(true);
}
return result;
}
@Override
protected void onCancelled(String result){
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
Log.i(TAG, "Entra a funcion onCancelled de Get_DisponibilidadChapaElectrica");
Notificacion("No es posible obtener la informacion de la disponibilidad de puerta magnetica");
if(origen instanceof FirstTimeActivity){
((FirstTimeActivity)origen).ConfiguracionSistema_CorteSecuenciaHilo();
}
}
@Override
protected void onPostExecute(String resultado){
Log.i(TAG, "Entro a funcion onPost de funcion Get_DisponibilidadChapaElectrica, resultado: "+resultado);
//asigno a parametros del sistema
global.getParametrosSistema().set_Manipulacion_Puerta(resultado);
if(global.getParametrosSistema().get_Manipulacion_Puerta().equals("Z0B9C4B")){//SI
//se incrementa por la utilizacion de un nuevo hilo
global.incrementThread();
//obtengo los eventos asignados a la manipulacion de puerta magnetica.
new CallWSEventos_Puerta_Magnetica().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, idPortico);
}
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: Disponibilidad_Puerta");
if(origen instanceof FirstTimeActivity){//se que sera para configuracion.
Log.i(TAG, "retorno a FirstTimeActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
//envio a siguiente bloque logico.
((FirstTimeActivity)origen).generateXML();
}else if(origen instanceof MainActivity){//sin uso, solo como informacion de retorno.
Log.i(TAG, "retorno a MainActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
}else if(origen instanceof MenuAdminActivity){//lamado desde la interfaz de administracion.
Log.i(TAG, "Retorno a MenuAdminActivity");
if(miBarra.getProgress() < miBarra.getMax()){
miBarra.setProgress(miBarra.getProgress() +1);
}
((MenuAdminActivity) origen).ProcesoActualizacionParametros_TerminoHilo();
}
}
}
}
private class CallWSCredencial_Admin extends AsyncTask<Void, Void, String>{
private String nombreFuncion = "U029171";
@Override
protected String doInBackground(Void... params) {
Log.i(TAG, "Entro al hilo de Credencial_Admin");
String result;
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
result = resSoap.toString();
} catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
result = null;
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
result = null;
cancel(true);
}
return result;
}
@Override
protected void onCancelled(String result){
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
Log.i(TAG, "Entra a funcion onCancelled de Credencial_Admin");
Notificacion("No es posible obtener la informacion del codigo de la credencial asignada al administrador");
if(origen instanceof FirstTimeActivity){
((FirstTimeActivity)origen).ConfiguracionSistema_CorteSecuenciaHilo();
}
}
@Override
protected void onPostExecute(String resultado){
Log.i(TAG, "Entro a funcion onPost de funcion Credencial_Admin, resultado: "+resultado);
//asigno a parametro del sistema.
global.getParametrosSistema().set_Id_CredencialAdmin(resultado);
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo Hilo: Credencial_Admin");
if(origen instanceof FirstTimeActivity){//se que sera para configuracion.
Log.i(TAG, "retorno a FirstTimeActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
//envio a siguiente bloque logico.
//((FirstTimeActivity)origen).continuacion();
((FirstTimeActivity)origen).generateXML();
}else if(origen instanceof MainActivity){//sin uso, solo como informacion de retorno.
Log.i(TAG, "retorno a MainActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
}else if(origen instanceof MenuAdminActivity){
Log.i(TAG, "Retorno a MenuAdminActivity");
if(miBarra.getProgress() < miBarra.getMax()){
miBarra.setProgress(miBarra.getProgress() +1);
}
((MenuAdminActivity) origen).ProcesoActualizacionParametros_TerminoHilo();
}
}
}
}
private class CallWSLocalizacion_Geografica extends AsyncTask<String, Void, String> {
private String nombreFuncion = "U029172";
@Override
protected String doInBackground(String... params){
Log.i(TAG, "Entro al hilo de localizacion geografica");
String result;
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
//parametros.
request.addProperty("idPortico", params[0]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
result = resSoap.toString();
} catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
result = null;
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
result = null;
cancel(true);
}
return result;
}
@Override
protected void onCancelled(String result){
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
Log.i(TAG, "Entra a funcion onCancelled de Localizacion_Geografica");
Notificacion("No es posible obtener la informacion de la localizacion geografica del dispositivo ingresado. Imposible la configuracion");
if(origen instanceof FirstTimeActivity ){
((FirstTimeActivity) origen).ConfiguracionSistema_CorteSecuenciaHilo();
}
}
@Override
protected void onPostExecute(String resultado){
Log.i(TAG, "Entro a funcion onPost de funcion Localizacion_geografica, resultado: "+resultado);
//asigno como parametro del sistema
global.getParametrosSistema().set_Localizacion_Geografica(resultado);
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: Localizacion_geografica");
if(origen instanceof FirstTimeActivity){//se que sera para configuracion.
Log.i(TAG, "retorno a FirstTimeActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
//envio a siguiente bloque logico.
//((FirstTimeActivity)origen).continuacion();
((FirstTimeActivity)origen).generateXML();
}else if(origen instanceof MainActivity){
Log.i(TAG, "retorno a MainActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
}else if(origen instanceof MenuAdminActivity){
Log.i(TAG, "Retorno a MenuAdminActivity");
if(miBarra.getProgress() < miBarra.getMax()){
miBarra.setProgress(miBarra.getProgress() + 1);
}
((MenuAdminActivity) origen).ProcesoActualizacionParametros_TerminoHilo();
}
}
}
}
private class CallWSEventos_Puerta_Magnetica extends AsyncTask<String, Void, List<EventoPuertaMagnetica>>{
private String nombreFuncion = "U029173";
private String relacion = global.getParametrosSistema().get_Id_Relacion();//nesesario que este aqui.
List<EventoPuertaMagnetica> listaEventos;
@Override
protected List<EventoPuertaMagnetica> doInBackground(String... params) {
Log.i(TAG, "comienzo de ejecucion en background de hilo 'Eventos_Puerta_Magnetica'");
String result;
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
//parametros.
request.addProperty("rel", relacion); //sensible a nombre de parametros.
request.addProperty("cod_Portico", params[0]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapObject resSoap = (SoapObject) envelope.getResponse();
//se interpreta la lista.
listaEventos = new ArrayList<>();
for(int i = 0; i < resSoap.getPropertyCount(); i++){
SoapObject ic = (SoapObject) resSoap.getProperty(i);
EventoPuertaMagnetica evento = new EventoPuertaMagnetica();
//evento.set_U01B3F3(ic.getProperty(2).toString());
evento.set_U01B3F3(ic.getProperty(0).toString());
//evento.set_DESTINO(ic.getProperty(6).toString());
evento.set_DESTINO(ic.getProperty(1).toString());
listaEventos.add(evento);
}
return listaEventos;
} catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
listaEventos = null;
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
listaEventos = null;
cancel(true);
}
return listaEventos;
}
@Override
protected void onCancelled(List<EventoPuertaMagnetica> result) {
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
Log.i(TAG, "Se ha entrado a funcion onCancelled de Eventos_Puerta_Magnetica");
Notificacion("No ha sido posible obtener la informacion sobre los eventos asignados a la manipulacion de puerta magnetica en este dispositivo");
}
@Override
protected void onPostExecute(List<EventoPuertaMagnetica> respuesta){
Log.i(TAG, "Ingreso a funcion onPOst de Eventos_Puerta_Magnetica");
//asigno a parametros del sistema
global.getParametrosSistema().set_Eventos(respuesta);
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: Eventos_Puerta_Magnetica");
if(origen instanceof FirstTimeActivity){//se que sera para configuracion.
Log.i(TAG, "retorno a FirstTimeActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
//envio al siguiente bloque logico.
//((FirstTimeActivity)origen).continuacion();
((FirstTimeActivity)origen).generateXML();
}else if(origen instanceof MainActivity){//sin usu, solo como informacion hacia main activity.
Log.i(TAG, "retorno a MainActivity");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
}else if(origen instanceof MenuAdminActivity){
Log.i(TAG, "Retorno a MenuAdminActivity");
if(miBarra.getProgress() < miBarra.getMax()){
miBarra.setProgress(miBarra.getProgress() +1);
}
((MenuAdminActivity) origen).ProcesoActualizacionParametros_TerminoHilo();
}
}
}
}
private class CallWSAnts_VerificacionNoFoto extends AsyncTask<String, Void, List<AntecedentesPersona>> {
byte [] arrayVacio = new byte[64];
String nombreFuncion = "U029174";
List<AntecedentesPersona> listaAntecedentes = null;
@Override
protected void onPreExecute() {
for(int i=0; i<arrayVacio.length; i++){
arrayVacio[i] = 0;
}
}
@Override
protected List<AntecedentesPersona> doInBackground(String... params) {
Log.i(TAG, "Entro al hilo de Antecedentes de verifiacion");
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
request.addProperty("pstrId_Credencial", params[0]);
request.addProperty("pstrPortico", params[1]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try{
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapObject resSoap = (SoapObject) envelope.getResponse();
listaAntecedentes = new ArrayList<>();
for(int i= 0; i<resSoap.getPropertyCount(); i++){
SoapObject ic = (SoapObject) resSoap.getProperty(i);
AntecedentesPersona ap = new AntecedentesPersona();
ap.set_U0217F1(ic.getProperty(0).toString());
ap.set_U0217F2(ic.getProperty(1).toString());
ap.set_U0217F3(ic.getProperty(2).toString());
ap.set_U0217F4(Integer.parseInt(ic.getProperty(3).toString()));
ap.set_U0217F5(ic.getProperty(4).toString());
ap.set_U0217F6(ic.getProperty(5).toString());
ap.set_U0217F7(Arrays.equals(Base64.decode(ic.getProperty(6).toString().getBytes(),Base64.DEFAULT), arrayVacio) ? null : Base64.decode(ic.getProperty(6).toString().getBytes(),Base64.DEFAULT));
ap.set_U0217F8(ic.getProperty(7).toString().equals("anyType{}") ? null : ic.getProperty(7).toString());
ap.set_U0217F9(ic.getProperty(8).toString());
listaAntecedentes.add(ap);
}
}catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
cancel(true);
}
return listaAntecedentes;
}
@Override
protected void onCancelled(List<AntecedentesPersona> result){
Log.e(TAG, "Se ha cancelado llamado a Ants_Verificacion");
//Notificacion("No ha sido posible obtener los datos de la persona");
}
@Override
protected void onPostExecute(List<AntecedentesPersona> resultado) {
Log.i(TAG, "Ingreso a POST de llamado Ants_Verificacion");
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: Ants_Verificacion_NOHuellaFoto");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
if(origen instanceof MainActivity){//para actualizar la LDV.
//envio a siguiente bloque logico.
((MainActivity)origen).ActualizarLDV_TerminoHilo(resultado);
}else if(origen instanceof MenuAdminActivity){// Actualizacion LDV desde interfaz de adminitracion.
Log.i(TAG, "Retorno a MenuAdminActivity");
((MenuAdminActivity) origen).ProcesoActualizacionLDV_TerminoHilo(resultado);
}
}
}
}
private class CallWSAnts_VerificacionNoFotoHuella extends AsyncTask<String, Void, List<AntecedentesPersona>> {
List<AntecedentesPersona> listaAntecedentes;
String nombreFuncion="U029175";
@Override
protected List<AntecedentesPersona> doInBackground(String... params){
Log.i(TAG, "Entro al hilo de Antecedentes de verifiacion");
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
request.addProperty("pstrId_Credencial", params[0]);
request.addProperty("pstrPortico", params[1]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try{
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapObject resSoap = (SoapObject) envelope.getResponse();
listaAntecedentes = new ArrayList<>();
for(int i= 0; i<resSoap.getPropertyCount(); i++){
SoapObject ic = (SoapObject) resSoap.getProperty(i);
AntecedentesPersona ap = new AntecedentesPersona();
ap.set_U0217F1(ic.getProperty(0).toString());
ap.set_U0217F2(ic.getProperty(1).toString());
ap.set_U0217F3(ic.getProperty(2).toString());
ap.set_U0217F4(Integer.parseInt(ic.getProperty(3).toString()));
ap.set_U0217F5(ic.getProperty(4).toString());
ap.set_U0217F6(ic.getProperty(5).toString());
ap.set_U0217F8(ic.getProperty(6).toString().equals("anyType{}") ? null : ic.getProperty(6).toString());
ap.set_U0217F9(ic.getProperty(7).toString());
listaAntecedentes.add(ap);
}
}catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
cancel(true);
}
return listaAntecedentes;
}
@Override
protected void onCancelled(List<AntecedentesPersona> result){
Log.e(TAG, "Se ha cancelado llamado a Ants_Verificacion");
if(origen instanceof EventsActivity){
Notificacion("No ha sido posible obtener los datos de la persona");
}else if(origen instanceof MenuAdminActivity){
Notificacion("No ha sido posible obtener los antecedentes de la persona");
}
}
@Override
protected void onPostExecute(List<AntecedentesPersona> resultado) {
Log.i(TAG, "Ingreso a POST de llamado Ants_Verificacion");
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: Ants_Verificacion_NOHuellaFoto");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
if(origen instanceof EventsActivity){//se que sera para despliegue de datos de la persona.
Log.i(TAG, "retorno a EventsActivity");
//envio a siguiente bloque logico.
((EventsActivity)origen).DespliegueDatos(resultado);
}
}
}
}
private class CallWSAnts_Veri_Foto extends AsyncTask<String, Void, byte[]> {
byte[] data = null;
String nombreFuncion="U029176";
@Override
protected byte[] doInBackground(String... params){
Log.i(TAG, "Entro al hilo de Antecedentes de verifiacion - Fotografia");
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
request.addProperty("pstrId_Credencial", params[0]);
request.addProperty("pstrPortico", params[1]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try{
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
if(resSoap != null){
//data = (resSoap.toString().getBytes());
data = Base64.decode(resSoap.getValue().toString().getBytes(),Base64.DEFAULT);
//dd = new String(data,"UTF-8");
}else{ // En el caso de que no encontrara informacion... (crede no verificada, persona sin foto asignada).
data=null;
cancel(true);
}
}catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
data = null;
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
data = null;
cancel(true);
}
return data;
}
@Override
protected void onCancelled(byte[] result){
Log.e(TAG, "Se ha cancelado llamado a Ants_Verificacion - Fotografia");
//Notificacion("No ha sido posible obtener los datos de la persona");
if(origen instanceof EventsActivity){
((EventsActivity)origen).AsignacionFotografia(result);
}
}
@Override
protected void onPostExecute(byte[] resultado) {
Log.i(TAG, "Ingreso a POST de llamado Ants_Verificacion - Fotografia");
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: Ants_Verificacion - Fotografia");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
if(origen instanceof EventsActivity){//se que sera para despliegue de datos de la persona.
Log.i(TAG, "retorno a EventsActivity");
//Se asigna a foto a la persona.
((EventsActivity)origen).AsignacionFotografia(resultado);
}
}
}
}
private class CallWSVerificar_Reingreso extends AsyncTask<String, Void, Boolean> {
boolean result = false;
String nombreFuncion = "U029178";
@Override
protected Boolean doInBackground(String... params) {
Log.i(TAG, "Entro al hilo de Verificacion de reingreso");
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
request.addProperty("_idCard", params[0]);
request.addProperty("_typeEvent", params[1]);
request.addProperty("_portico", params[2]);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try{
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
if(resSoap != null){
result = Boolean.parseBoolean(resSoap.toString());
}else{ // En el caso de que no encontrara informacion... (crede no verificada, persona sin foto asignada).
cancel(true);
}
}catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
cancel(true);
}
return result;
}
@Override
protected void onCancelled(Boolean resultado){
Log.i(TAG, "Se ha cancelado el hilo de verificacion de reingreso");
//Notificacion("No es posible verificar el reingreso de la marca"); no importa si no puede.
((EventsActivity)origen).VerificacionReingreso_TerminoHilo(false);
}
@Override
protected void onPostExecute(Boolean resultado){
Log.i(TAG, "Ingreso a POST de llamado Verificacion_reingreso");
global.decrementThread();
if(global.getNumThreads() == 0){
Log.i(TAG, "Ultimo hilo: Verificacion_reingreso");
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
if(origen instanceof EventsActivity){//se que sera para el reingreso antes del marcaje.
Log.i(TAG, "retorno a EventsActivity");
//Se asigna a foto a la persona.
((EventsActivity)origen).VerificacionReingreso_TerminoHilo(resultado);
}
}
}
}
private class CallWSInsertar_Marca extends AsyncTask<String, Integer, Boolean>{
String nombreFuncion = "U029179";
ProgressDialog progressDialog;
String idVerificacion = null;
//constructor para asignacion de progressDialog.
public CallWSInsertar_Marca(ProgressDialog pd){
this.progressDialog = pd;
}
@Override
protected void onPreExecute(){
progressDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
Log.i(TAG, "Entro al hilo de Antecedentes de verifiacion");
Boolean resultMarca = false;
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
request.addProperty("_idCard", params[0]);
request.addProperty("_typeEvent", params[1]);
request.addProperty("_portico", params[2]);
request.addProperty("_idVerificacion", params[3]);
request.addProperty("_idPersona", params[4]);
request.addProperty("_TypeCard", params[5]);
request.addProperty("_levelAuth", params[6]);
request.addProperty("_typeTransaccion", params[7]);
request.addProperty("_stateTransaccion", params[8]);
request.addProperty("_stateTransfer", params[9]);
request.addProperty("_loc_geo", params[10]);
request.addProperty("_originMark", params[11]);
idVerificacion=params[3]; //Para saber si la persona esta verificada o no;
publishProgress(25);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
publishProgress(25);
try{
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
publishProgress(45);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
resultMarca = Boolean.parseBoolean(resSoap.toString());
if(!resultMarca){
cancel(true);
}
publishProgress(5);
}catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
cancel(true);
}
return resultMarca;
}
@Override
protected void onProgressUpdate(Integer... porcentaje){
progressDialog.setProgress(progressDialog.getProgress() + porcentaje[0]);
}
@Override
protected void onPostExecute(Boolean result){
Log.i(TAG, "Se ha realizado la marca a la BD");
try{
Thread.sleep(1000);
if(result){
if(idVerificacion != null){
Globals.getInstance().getSonidos().Reproducir_IngreCorrec(origen);
}else{
Globals.getInstance().getSonidos().Reproducir_IngrePendVerifi(origen);
}
}
}catch (Exception ex){
Log.e(TAG, "Error en POstExecute de hilo de Ingreso de Marca");
}
progressDialog.dismiss();
origen.setResult(Activity.RESULT_OK);
origen.finish();
}
@Override
protected void onCancelled(Boolean res){
Log.e(TAG, "Se ha cancelado llamado a Ingresar_Marca");
Notificacion("No ha sido posible obtener los datos de la persona");
}
}
private class CallWSInsertar_Marca_Transito extends AsyncTask<String, Integer, Boolean> {
String nombreFuncion = "U02917A";
ProgressDialog progressDialog;
//constructor para asignacion de progressDialog.
public CallWSInsertar_Marca_Transito(ProgressDialog pd){
this.progressDialog = pd;
}
@Override
protected void onPreExecute(){
progressDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
Log.i(TAG, "Entro al hilo de Ingreso de Marcas de transito");
Boolean resultMarca = false;
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
request.addProperty("_IdPortico", params[0]);
request.addProperty("_IdCredencial", params[1]);
request.addProperty("_IdPersona", params[2]);
publishProgress(25);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
publishProgress(25);
try{
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
publishProgress(45);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
resultMarca = Boolean.parseBoolean(resSoap.toString());
if(!resultMarca){
cancel(true);
}
}catch (IOException e) {//no encuentra respuesta (No existe o no Existe la direccion a webservice).
//e.printStackTrace();
cancel(true);
} catch (XmlPullParserException e) {
//e.printStackTrace();
cancel(true);
}
publishProgress(5);
return resultMarca;
}
@Override
protected void onPostExecute(Boolean result){
Log.i(TAG, "Se ha realizado la marca de transito a la BD");
try{
//sonido de marca realizada.
Thread.sleep(1000);
Globals.getInstance().getSonidos().Reproducir_IngreCorrec(origen);
}catch (Exception ex){
Log.e(TAG, "Error en POstExecute de hilo de Ingreso de Marca");
}
progressDialog.dismiss();
origen.setResult(Activity.RESULT_OK);
origen.finish();
}
@Override
protected void onCancelled(Boolean res){
Log.e(TAG, "Se ha cancelado llamado a Ingresar_Marca dde transito");
Notificacion("No ha sido posible obtener los datos de la persona");
}
}
private class CallWSInsertar_Marca_Transito_Offline extends AsyncTask<Void, Integer, Integer>{
List<RegistroTransito> registrosTransito = null;
String nombreFuncion = "U02917B";
public CallWSInsertar_Marca_Transito_Offline(List<RegistroTransito> list){
registrosTransito = list;
}
@Override
protected void onPreExecute(){
miBarra.setIndeterminate(false);
miBarra.setVisibility(View.VISIBLE);
miBarra.setMax(registrosTransito.size());
miBarra.setProgress(0);
}
@Override
protected Integer doInBackground(Void... params) {
int resultDelete =-1;
try{
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
for(int i=0; i<registrosTransito.size(); i++){
Boolean resultMarca = false;
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
request.addProperty("_fechaHora", registrosTransito.get(i).get_U0272F5());
request.addProperty("_IdPortico", registrosTransito.get(i).get_U0272F6());
request.addProperty("_IdCredencial", registrosTransito.get(i).get_U0272F7());
request.addProperty("_IdPersona", registrosTransito.get(i).get_U0272F8());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
resultMarca = Boolean.parseBoolean(resSoap.toString());
if(!resultMarca){
cancel(true);
return -1;
}else{
//elimino el registro de la BD local.
resultDelete = Globals.getInstance().getDatabase_manager().EliminarTransito(registrosTransito.get(i).get_U0272F5(),
registrosTransito.get(i).get_U0272F6());
if(resultDelete < 0){
//no fue posible la eliminacion.
cancel(true);
return -1;
}
publishProgress(1);
}
}
}catch (Exception ex){
cancel(true);
}
return resultDelete;
}
@Override
protected void onPostExecute(Integer result){
try{
//Termino de transferencia.
miBarra.setVisibility(View.INVISIBLE);
Notificacion("Registros de historial de transito transferidos exitosamente");
if(origen instanceof MenuAdminActivity){
((MenuAdminActivity) origen).EstadoBotonera(true);
}
}catch (Exception ex){
Log.e(TAG, "Error en PostExecute:: hilo de Transito offline");
}
}
@Override
protected void onCancelled(Integer result){
Notificacion("Error al transferir los datos de transito");
if(origen instanceof MenuAdminActivity){
((MenuAdminActivity) origen).EstadoBotonera(true);
}
}
@Override
protected void onProgressUpdate(Integer... progress){
miBarra.setProgress(miBarra.getProgress()+progress[0]);
}
}
private class CallWSInsertar_Marca_Offline extends AsyncTask<Void, Integer, Integer>{
List<RegistroMarca> registrosMarca = null;
String nombreFuncion = "U02917C";
public CallWSInsertar_Marca_Offline(List<RegistroMarca> listado){
registrosMarca = listado;
}
@Override
protected void onPreExecute(){
miBarra.setIndeterminate(false);
miBarra.setVisibility(View.VISIBLE);
miBarra.setMax(registrosMarca.size());
miBarra.setProgress(0);
}
@Override
protected Integer doInBackground(Void... params) {
int resultDelete =-1;
try{
List<HeaderProperty> headers = new ArrayList<HeaderProperty>();//lista que guarda la autenticacion.
headers.add(new HeaderProperty("Authorization", "Basic dW1icmFsOjEyMzQ=")); //dW1icmFsOjEyMzQ= es encriptacion 64 de umbral:1234. (64 encode).
for(int i=0; i<registrosMarca.size(); i++){
Boolean resultMarca = false;
SoapObject request = new SoapObject(NAMESPACE, nombreFuncion);
request.addProperty("_idCard", registrosMarca.get(i).get_U021DCD());
request.addProperty("_timePorticox", registrosMarca.get(i).get_U021DCE());
request.addProperty("_typeEvent", registrosMarca.get(i).get_U021DCF());
request.addProperty("_portico", registrosMarca.get(i).get_U021DD0());
request.addProperty("_idVerificacion", registrosMarca.get(i).get_U021DD1() == -1 ? null : registrosMarca.get(i).get_U021DD1());
request.addProperty("_idPersona", registrosMarca.get(i).get_U021DD2());
request.addProperty("_TypeCard", registrosMarca.get(i).get_U021DD3());
request.addProperty("_levelAuth", registrosMarca.get(i).get_U021DD4());
request.addProperty("_typeTransaccion", "Z0B99D0"); //Z0B99D0: Batch (fuera de linea)
request.addProperty("_stateTransaccion", registrosMarca.get(i).get_U021DD6());
request.addProperty("_stateTransfer", "Z0B99DC"); //Z0B99DC: Enviada
request.addProperty("_loc_geo", registrosMarca.get(i).get_U021DD8());
request.addProperty("_originMark", registrosMarca.get(i).get_U021DD9());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
transporte.call(NAMESPACE + nombreFuncion, envelope, headers);
SoapPrimitive resSoap = (SoapPrimitive) envelope.getResponse();
resultMarca = Boolean.parseBoolean(resSoap.toString());
if(!resultMarca){
cancel(true);
return -1;
}else{
//elimino el registro de la BD local.
resultDelete = Globals.getInstance().getDatabase_manager().EliminarMarca(registrosMarca.get(i).get_U021DCD(),
registrosMarca.get(i).get_U021DCE(),
registrosMarca.get(i).get_U021DCF(),
registrosMarca.get(i).get_U021DD0());
if(resultDelete < 0){
//no fue posible la eliminacion.
cancel(true);
return -1;
}
publishProgress(1);
}
}
}catch (Exception ex){
cancel(true);
return -1;
}
return resultDelete;
}
@Override
protected void onProgressUpdate(Integer... status){
miBarra.setProgress(miBarra.getProgress() + status[0]);
}
@Override
protected void onCancelled(Integer result){
Notificacion("Error al transferir los datos de marcaje");
if(origen instanceof MenuAdminActivity){
((MenuAdminActivity) origen).EstadoBotonera(true);
}
}
@Override
protected void onPostExecute(Integer result){
try{
//Termino de transferencia.
miBarra.setVisibility(View.INVISIBLE);
Notificacion("Registros de marcas de asistencia transferidos exitosamente");
if(origen instanceof MenuAdminActivity){
((MenuAdminActivity) origen).EstadoBotonera(true);
}
}catch (Exception ex){
Log.e(TAG, "Error en PostExecute:: hilo de ingreso de marcas offline");
}
}
}
private void Notificacion(String message){
try{
alertDialog.setTitle(message);
alertDialog.show();
if(miBarra != null){
miBarra.setVisibility(View.INVISIBLE);
}
}catch (Exception ex){
Log.e(TAG, "Error al enviar mensaje (U02916C -> Notification):: "+ex.getMessage());
}
}
}
|
[
"[email protected]"
] | |
9d36c810f2791b43d4215d84c223a21e87a3b683
|
18e243cc23da3ef57745eda4eee2bcb87e3566a8
|
/app/src/main/java/com/yiliao/chat/fragment/AllOrderFragment.java
|
b0c19a84b23a001001aa4f6d0e7de9da5fbcb922
|
[] |
no_license
|
moonstre/beihe
|
a59a14d58cf5b9432f08e3288751a6d0e19e5375
|
99b5f179356e1041a732a03f828be4e86660671b
|
refs/heads/master
| 2022-11-15T20:55:59.940514 | 2020-07-16T15:25:38 | 2020-07-16T15:25:38 | 280,187,460 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 8,468 |
java
|
package com.yiliao.chat.fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yiliao.chat.R;
import com.yiliao.chat.activity.OrderDetailsActivity;
import com.yiliao.chat.adapter.OrderSortAdapter;
import com.yiliao.chat.base.AppManager;
import com.yiliao.chat.base.BaseBean;
import com.yiliao.chat.base.BaseFragment;
import com.yiliao.chat.base.BaseListResponse;
import com.yiliao.chat.base.BaseResponse;
import com.yiliao.chat.base.LazyFragment;
import com.yiliao.chat.bean.ChatUserInfo;
import com.yiliao.chat.bean.OrderSortBean;
import com.yiliao.chat.bean.PageBean;
import com.yiliao.chat.bean.ShareInformitionBean;
import com.yiliao.chat.constant.ChatApi;
import com.yiliao.chat.constant.Constant;
import com.yiliao.chat.helper.SharedPreferenceHelper;
import com.yiliao.chat.net.AjaxCallback;
import com.yiliao.chat.net.NetCode;
import com.yiliao.chat.util.ParamUtil;
import com.yiliao.chat.util.ToastUtil;
import com.yiliao.chat.view.SpacesItemDecoration;
import com.zhy.http.okhttp.OkHttpUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
@SuppressLint("ValidFragment")
public class AllOrderFragment extends BaseFragment implements View.OnClickListener{
String code_c;
public AllOrderFragment(String code){
code_c=code;
}
private SmartRefreshLayout mRefreshLayout;
private int mCurrentPage = 1;
private RecyclerView content_rv;
private OrderSortAdapter mAdapter;
private List<OrderSortBean> mFocusBeans = new ArrayList<>();
@Override
protected int initLayout() {
return R.layout.order_sort_fragment;
}
@Override
protected void initView(View view, Bundle savedInstanceState) {
content_rv=view.findViewById(R.id.content_rv);
mRefreshLayout = view.findViewById(R.id.refreshLayout);
mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(@NonNull RefreshLayout refreshlayout) {
getQueryOrder(refreshlayout, true, 1,code_c);
}
});
mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore(@NonNull RefreshLayout refreshlayout) {
getQueryOrder(refreshlayout, false, mCurrentPage + 1,code_c);
}
});
LinearLayoutManager gridLayoutManager = new LinearLayoutManager(getContext());
content_rv.setLayoutManager(gridLayoutManager);
mAdapter = new OrderSortAdapter(mContext, false);
content_rv.setAdapter(mAdapter);
if (mRefreshLayout != null) {
mRefreshLayout.autoRefresh();
}
HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
stringIntegerHashMap.put(SpacesItemDecoration.TOP_DECORATION,10);//上下间距
content_rv.addItemDecoration(new SpacesItemDecoration(stringIntegerHashMap));
mAdapter.setOnItemClickListener(new OrderSortAdapter.OnItemClickListener() {
@Override
public void onItemClick(OrderSortBean sortBean) {
int role=getUserRole();
Intent intent=new Intent(getActivity(), OrderDetailsActivity.class);
intent.putExtra("sortBean",(Serializable)sortBean);
intent.putExtra("isSelf",sortBean.isSelf+"");
intent.putExtra("role",role);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
/**
* 获取角色
*/
private int getUserRole() {
if (AppManager.getInstance() != null) {
ChatUserInfo userInfo = AppManager.getInstance().getUserInfo();
if (userInfo != null) {
//1 主播 0 用户
return userInfo.t_role;
} else {
return SharedPreferenceHelper.getAccountInfo(mContext.getApplicationContext()).t_role;
}
}
return 0;
}
@Override
protected void onFirstVisible() {
}
private void getQueryOrder(final RefreshLayout refreshlayout, final boolean isRefresh, int page,String code){
Map<String, String> paramMap = new HashMap<>();
paramMap.put("userId", mContext.getUserId());
paramMap.put("status",code);
paramMap.put("page",String.valueOf(page));
OkHttpUtils.post().url(ChatApi.QUERY_SERVICE_ORDER)
.addParams("param", ParamUtil.getParam(paramMap))
.build().execute(new AjaxCallback<BaseResponse<PageBean<OrderSortBean>>>() {
@Override
public void onResponse(BaseResponse<PageBean<OrderSortBean>> response, int id) {
if (response != null && response.m_istatus == NetCode.SUCCESS) {
PageBean<OrderSortBean> orderSortBean = response.m_object;
if (orderSortBean!=null){
List<OrderSortBean> orderSortBeanList=orderSortBean.data;
if (orderSortBeanList!=null){
int size=orderSortBeanList.size();
if (isRefresh){
mCurrentPage = 1;
mFocusBeans.clear();
mFocusBeans.addAll(orderSortBeanList);
mAdapter.loadData(mFocusBeans);
refreshlayout.finishRefresh();
if (size >= 10) {//如果是刷新,且返回的数据大于等于10条,就可以load more
refreshlayout.setEnableLoadMore(true);
}
} else {
mCurrentPage++;
mFocusBeans.addAll(orderSortBeanList);
mAdapter.loadData(mFocusBeans);
if (size >= 10) {
refreshlayout.finishLoadMore();
}
}
if (size < 10) {//如果数据返回少于10了,那么说明就没数据了
refreshlayout.finishLoadMoreWithNoMoreData();
}
}
}
}else {
ToastUtil.showToast(getContext(),response.m_strMessage);
if (isRefresh) {
refreshlayout.finishRefresh();
} else {
refreshlayout.finishLoadMore();
}
}
}
@Override
public void onError(Call call, Exception e, int id) {
super.onError(call, e, id);
if (isRefresh) {
refreshlayout.finishRefresh();
} else {
refreshlayout.finishLoadMore();
}
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.go_to_detail:
break;
}
}
@Override
public void onResume() {
super.onResume();
if (mRefreshLayout != null) {
mRefreshLayout.autoRefresh();
}
}
@Override
protected void onFirstVisibleToUser() {
Bundle bundle = getArguments();
if (bundle != null) {
// mActorId = bundle.getInt(Constant.ACTOR_ID);
// getIntimateAndGift(mActorId);
// getUserComment(mActorId);
}
mIsDataLoadCompleted = true;
}
}
|
[
"youli"
] |
youli
|
aa9a665898cc503bb3f0ac7d12875b3ffde47741
|
70cb1e4ebf08daa937f9c7ba77be80324cf40d27
|
/src/main/java/org/anzo/MyStart.java
|
81748856025bcea606b9f3379a261faa47e4af6b
|
[] |
no_license
|
Anzo85/HomeTasks10
|
ba289fd86ffdda4a5b9826c3458e58dc3839cb61
|
17aef37c374c0e1608ae40ed933d855be9f6f2e8
|
refs/heads/master
| 2020-04-10T00:46:48.889675 | 2016-09-13T10:11:09 | 2016-09-13T10:11:09 | 68,097,539 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 377 |
java
|
package org.anzo;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import java.io.IOException;
public class MyStart {
public static void main(String[] args) throws IOException {
FibRec frec = new FibRec();
FibWhile fw = new FibWhile();
System.out.println(frec.fibRec(6));
System.out.println(fw.fibWhile(6));
}
}
|
[
"[email protected]"
] | |
04c63339f94911633c1334b7b81a084d9a939eb3
|
31498c4412077e2aa50dbadbb4aa8f7315206191
|
/spring-shopee/src/main/java/com/example/springshopee/repository/SessionRepository.java
|
19542af2628cf48ad16d9e20ff90c4af21fb7f0e
|
[] |
no_license
|
truongquangkhai99/spring-shopee
|
8906f677e4effa1f59201bcbcae0a94e0fa36ce2
|
fb1b793b9f17ba4d95f598bbe74c2a92610c10ff
|
refs/heads/main
| 2023-06-21T08:52:35.320512 | 2021-07-26T15:08:07 | 2021-07-26T15:08:07 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,103 |
java
|
package com.example.springshopee.repository;
import com.example.springshopee.helper.SessionMapper;
import com.example.springshopee.model.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class SessionRepository {
@Autowired
JdbcTemplate jdbcTemplate;
public Boolean createSession(String userId, String token){
String sql = "Insert into Session (userId, token) values (?, ?)";
Integer result = jdbcTemplate.update(sql, new Object[]{userId, token});
if(result == 1){
return true;
}else{
return false;
}
}
public Session getSessionByToken(String token){
String sql = "Select * from Session where token = ? limit 1";
List<Session> sessions = jdbcTemplate.query(sql, new SessionMapper(), new Object[]{token});
if(sessions.size() == 0){
return null;
}else{
return sessions.get(0);
}
}
}
|
[
"[email protected]"
] | |
20593825620bf6f34b868eed4694abb2018d4317
|
383baa73f9c79b1669bd8cf4fff530e79b3fc598
|
/app/src/main/java/com/toprank/computervision/FaceRecognition.java
|
cd7576e21da01a8b80345037789a995aca240b97
|
[] |
no_license
|
johnmwai/ComputerVisionApp
|
33f3906d6664dda10a10fe463ae2469c974165f9
|
e7cbb5c883f0646bbe3b5968a9c4e1554249c409
|
refs/heads/master
| 2021-01-25T05:56:54.943418 | 2017-02-02T09:21:52 | 2017-02-02T09:21:52 | 80,709,598 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 30,737 |
java
|
package com.toprank.computervision;
/**
* Created by john on 8/14/15.
*/
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.FloatPointer;
import org.bytedeco.javacpp.Pointer;
import static org.bytedeco.javacpp.opencv_core.*;
import static org.bytedeco.javacpp.opencv_highgui.*;
import static org.bytedeco.javacpp.opencv_legacy.*;
/** Recognizes faces.
*
* @author reed
*/
public class FaceRecognition {
private Context context;
/** the logger */
private static final Logger LOGGER = Logger.getLogger(FaceRecognition.class.getName());
/** the number of training faces */
private int nTrainFaces = 0;
/** the training face image array */
IplImage[] trainingFaceImgArr;
/** the test face image array */
IplImage[] testFaceImgArr;
/** the person number array */
CvMat personNumTruthMat;
/** the number of persons */
int nPersons;
/** the person names */
final List<String> personNames = new ArrayList<String>();
/** the number of eigenvalues */
int nEigens = 0;
/** eigenvectors */
IplImage[] eigenVectArr;
/** eigenvalues */
CvMat eigenValMat;
/** the average image */
IplImage pAvgTrainImg;
/** the projected training faces */
CvMat projectedTrainFaceMat;
/** Constructs a new FaceRecognition instance. */
public FaceRecognition(Context context) {
this.context = context;
copyAssets();
}
private void copyFile(String filename){
AssetManager assetManager = context.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(context.getExternalFilesDir(null), filename);
File dir = new File(outFile.getParent());
if(!dir.isDirectory()){
dir.mkdirs();
}
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
System.exit(1);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
private void copyFileOrDir(String path){
AssetManager assetManager = context.getAssets();
String[] files = null;
try {
files = assetManager.list(path);
if(files.length == 0){
copyFile(path);
}else{
for(String filename : files) {
File f = new File(path, filename);
copyFileOrDir(f.getPath());
}
}
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
}
private void copyAssets() {
copyFileOrDir("");
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
private String canonize(String name){
File f = new File(context.getExternalFilesDir(null), name);
return f.getAbsolutePath();
}
/** Trains from the data in the given training text index file, and store the trained data into the file 'facedata.xml'.
*
* @param trainingFileName the given training text index file
*/
public void learn(final String trainingFileName) {
final String canonical = canonize(trainingFileName);
int i;
// load training data
LOGGER.info("===========================================");
LOGGER.info("Loading the training images in " + trainingFileName);
trainingFaceImgArr = loadFaceImgArray(canonical);
nTrainFaces = trainingFaceImgArr.length;
LOGGER.info("Got " + nTrainFaces + " training images");
if (nTrainFaces < 3) {
LOGGER.severe("Need 3 or more training faces\n"
+ "Input file contains only " + nTrainFaces);
return;
}
// do Principal Component Analysis on the training faces
doPCA();
LOGGER.info("projecting the training images onto the PCA subspace");
// project the training images onto the PCA subspace
projectedTrainFaceMat = cvCreateMat(
nTrainFaces, // rows
nEigens, // cols
CV_32FC1); // type, 32-bit float, 1 channel
// initialize the training face matrix - for ease of debugging
for (int i1 = 0; i1 < nTrainFaces; i1++) {
for (int j1 = 0; j1 < nEigens; j1++) {
projectedTrainFaceMat.put(i1, j1, 0.0);
}
}
LOGGER.info("created projectedTrainFaceMat with " + nTrainFaces + " (nTrainFaces) rows and " + nEigens + " (nEigens) columns");
if (nTrainFaces < 5) {
LOGGER.info("projectedTrainFaceMat contents:\n" + oneChannelCvMatToString(projectedTrainFaceMat));
}
final FloatPointer floatPointer = new FloatPointer(nEigens);
for (i = 0; i < nTrainFaces; i++) {
cvEigenDecomposite(
trainingFaceImgArr[i], // obj
nEigens, // nEigObjs
eigenVectArr, // eigInput (Pointer)
0, // ioFlags
null, // userData (Pointer)
pAvgTrainImg, // avg
floatPointer); // coeffs (FloatPointer)
if (nTrainFaces < 5) {
LOGGER.info("floatPointer: " + floatPointerToString(floatPointer));
}
for (int j1 = 0; j1 < nEigens; j1++) {
projectedTrainFaceMat.put(i, j1, floatPointer.get(j1));
}
}
if (nTrainFaces < 5) {
LOGGER.info("projectedTrainFaceMat after cvEigenDecomposite:\n" + projectedTrainFaceMat);
}
// store the recognition data as an xml file
storeTrainingData();
// Save all the eigenvectors as images, so that they can be checked.
storeEigenfaceImages();
}
/** Recognizes the face in each of the test images given, and compares the results with the truth.
*
* @param szFileTest the index file of test images
*/
public void recognizeFileList(final String szFileTest) {
LOGGER.info("===========================================");
LOGGER.info("recognizing faces indexed from " + szFileTest);
int i = 0;
int nTestFaces = 0; // the number of test images
CvMat trainPersonNumMat; // the person numbers during training
float[] projectedTestFace;
String answer;
int nCorrect = 0;
int nWrong = 0;
double timeFaceRecognizeStart;
double tallyFaceRecognizeTime;
float confidence = 0.0f;
// load test images and ground truth for person number
testFaceImgArr = loadFaceImgArray(canonize(szFileTest));
nTestFaces = testFaceImgArr.length;
LOGGER.info(nTestFaces + " test faces loaded");
// load the saved training data
trainPersonNumMat = loadTrainingData();
if (trainPersonNumMat == null) {
return;
}
// project the test images onto the PCA subspace
projectedTestFace = new float[nEigens];
timeFaceRecognizeStart = (double) cvGetTickCount(); // Record the timing.
for (i = 0; i < nTestFaces; i++) {
int iNearest;
int nearest;
int truth;
// project the test image onto the PCA subspace
cvEigenDecomposite(
testFaceImgArr[i], // obj
nEigens, // nEigObjs
eigenVectArr, // eigInput (Pointer)
0, // ioFlags
null, // userData
pAvgTrainImg, // avg
projectedTestFace); // coeffs
//LOGGER.info("projectedTestFace\n" + floatArrayToString(projectedTestFace));
final FloatPointer pConfidence = new FloatPointer(confidence);
iNearest = findNearestNeighbor(projectedTestFace, new FloatPointer(pConfidence));
confidence = pConfidence.get();
truth = personNumTruthMat.data_i().get(i);
nearest = trainPersonNumMat.data_i().get(iNearest);
if (nearest == truth) {
answer = "Correct";
nCorrect++;
} else {
answer = "WRONG!";
nWrong++;
}
LOGGER.info("nearest = " + nearest + ", Truth = " + truth + " (" + answer + "). Confidence = " + confidence);
}
tallyFaceRecognizeTime = (double) cvGetTickCount() - timeFaceRecognizeStart;
if (nCorrect + nWrong > 0) {
LOGGER.info("TOTAL ACCURACY: " + (nCorrect * 100 / (nCorrect + nWrong)) + "% out of " + (nCorrect + nWrong) + " tests.");
LOGGER.info("TOTAL TIME: " + (tallyFaceRecognizeTime / (cvGetTickFrequency() * 1000.0 * (nCorrect + nWrong))) + " ms average.");
}
}
/** Reads the names & image filenames of people from a text file, and loads all those images listed.
*
* @param filename the training file name
* @return the face image array
*/
private IplImage[] loadFaceImgArray(final String filename) {
//Intel's Image Processing Library image array
IplImage[] faceImgArr;
BufferedReader imgListFile;
String imgFilename;
int iFace = 0;
int nFaces = 0;
int i;
try {
// open the input file
imgListFile = new BufferedReader(new FileReader(filename));
// count the number of faces
while (true) {
final String line = imgListFile.readLine();
if (line == null || line.isEmpty()) {
break;
}
nFaces++;
}
LOGGER.info("nFaces: " + nFaces);
imgListFile = new BufferedReader(new FileReader(filename));
// allocate the face-image array and person number matrix
faceImgArr = new IplImage[nFaces];
personNumTruthMat = cvCreateMat(
1, // rows
nFaces, // cols
CV_32SC1); // type, 32-bit unsigned, one channel
// initialize the person number matrix - for ease of debugging
for (int j1 = 0; j1 < nFaces; j1++) {
personNumTruthMat.put(0, j1, 0);
}
personNames.clear(); // Make sure it starts as empty.
nPersons = 0;
// store the face images in an array
for (iFace = 0; iFace < nFaces; iFace++) {
String personName;
String sPersonName;
int personNumber;
// read person number (beginning with 1), their name and the image filename.
final String line = imgListFile.readLine();
if (line.isEmpty()) {
break;
}
final String[] tokens = line.split(" ");
personNumber = Integer.parseInt(tokens[0]);
personName = tokens[1];
imgFilename = tokens[2];
sPersonName = personName;
LOGGER.info("Got " + iFace + " " + personNumber + " " + personName + " " + imgFilename);
// Check if a new person is being loaded.
if (personNumber > nPersons) {
// Allocate memory for the extra person (or possibly multiple), using this new person's name.
personNames.add(sPersonName);
nPersons = personNumber;
LOGGER.info("Got new person " + sPersonName + " -> nPersons = " + nPersons + " [" + personNames.size() + "]");
}
// Keep the data
personNumTruthMat.put(
0, // i
iFace, // j
personNumber); // v
// load the face image
faceImgArr[iFace] = cvLoadImage(
canonize(imgFilename), // filename
CV_LOAD_IMAGE_GRAYSCALE); // isColor
if (faceImgArr[iFace] == null) {
throw new RuntimeException("Can't load image from " + imgFilename);
}
}
imgListFile.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
LOGGER.info("Data loaded from '" + filename + "': (" + nFaces + " images of " + nPersons + " people).");
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("People: ");
if (nPersons > 0) {
stringBuilder.append("<").append(personNames.get(0)).append(">");
}
for (i = 1; i < nPersons && i < personNames.size(); i++) {
stringBuilder.append(", <").append(personNames.get(i)).append(">");
}
LOGGER.info(stringBuilder.toString());
return faceImgArr;
}
/** Does the Principal Component Analysis, finding the average image and the eigenfaces that represent any image in the given dataset. */
private void doPCA() {
int i;
CvTermCriteria calcLimit;
CvSize faceImgSize = new CvSize();
// set the number of eigenvalues to use
nEigens = nTrainFaces - 1;
LOGGER.info("allocating images for principal component analysis, using " + nEigens + (nEigens == 1 ? " eigenvalue" : " eigenvalues"));
// allocate the eigenvector images
faceImgSize.width(trainingFaceImgArr[0].width());
faceImgSize.height(trainingFaceImgArr[0].height());
eigenVectArr = new IplImage[nEigens];
for (i = 0; i < nEigens; i++) {
eigenVectArr[i] = cvCreateImage(
faceImgSize, // size
IPL_DEPTH_32F, // depth
1); // channels
}
// allocate the eigenvalue array
eigenValMat = cvCreateMat(
1, // rows
nEigens, // cols
CV_32FC1); // type, 32-bit float, 1 channel
// allocate the averaged image
pAvgTrainImg = cvCreateImage(
faceImgSize, // size
IPL_DEPTH_32F, // depth
1); // channels
// set the PCA termination criterion
calcLimit = cvTermCriteria(
CV_TERMCRIT_ITER, // type
nEigens, // max_iter
1); // epsilon
LOGGER.info("computing average image, eigenvalues and eigenvectors");
// compute average image, eigenvalues, and eigenvectors
cvCalcEigenObjects(
nTrainFaces, // nObjects
trainingFaceImgArr, // input
eigenVectArr, // output
CV_EIGOBJ_NO_CALLBACK, // ioFlags
0, // ioBufSize
null, // userData
calcLimit,
pAvgTrainImg, // avg
eigenValMat.data_fl()); // eigVals
LOGGER.info("normalizing the eigenvectors");
cvNormalize(
eigenValMat, // src (CvArr)
eigenValMat, // dst (CvArr)
1, // a
0, // b
CV_L1, // norm_type
null); // mask
}
/** Stores the training data to the file 'facedata.xml'. */
private void storeTrainingData() {
CvFileStorage fileStorage;
int i;
LOGGER.info("writing facedata.xml");
// create a file-storage interface
fileStorage = cvOpenFileStorage(
canonize("facedata.xml"), // filename
null, // memstorage
CV_STORAGE_WRITE, // flags
null); // encoding
// Store the person names. Added by Shervin.
cvWriteInt(
fileStorage, // fs
"nPersons", // name
nPersons); // value
for (i = 0; i < nPersons; i++) {
String varname = "personName_" + (i + 1);
cvWriteString(
fileStorage, // fs
varname, // name
personNames.get(i), // string
0); // quote
}
// store all the data
cvWriteInt(
fileStorage, // fs
"nEigens", // name
nEigens); // value
cvWriteInt(
fileStorage, // fs
"nTrainFaces", // name
nTrainFaces); // value
cvWrite(
fileStorage, // fs
"trainPersonNumMat", // name
personNumTruthMat); // value
cvWrite(
fileStorage, // fs
"eigenValMat", // name
eigenValMat); // value
cvWrite(
fileStorage, // fs
"projectedTrainFaceMat", // name
projectedTrainFaceMat);
cvWrite(fileStorage, // fs
"avgTrainImg", // name
pAvgTrainImg); // value
for (i = 0; i < nEigens; i++) {
String varname = "eigenVect_" + i;
cvWrite(
fileStorage, // fs
varname, // name
eigenVectArr[i]); // value
}
// release the file-storage interface
cvReleaseFileStorage(fileStorage);
}
/** Opens the training data from the file 'facedata.xml'.
*
* @param pTrainPersonNumMat
* @return the person numbers during training, or null if not successful
*/
private CvMat loadTrainingData() {
LOGGER.info("loading training data");
CvMat pTrainPersonNumMat = null; // the person numbers during training
CvFileStorage fileStorage;
int i;
// create a file-storage interface
fileStorage = cvOpenFileStorage(
canonize("facedata.xml"), // filename
null, // memstorage
CV_STORAGE_READ, // flags
null); // encoding
if (fileStorage == null) {
LOGGER.severe("Can't open training database file 'facedata.xml'.");
return null;
}
// Load the person names.
personNames.clear(); // Make sure it starts as empty.
nPersons = cvReadIntByName(
fileStorage, // fs
null, // map
"nPersons", // name
0); // default_value
if (nPersons == 0) {
LOGGER.severe("No people found in the training database 'facedata.xml'.");
return null;
} else {
LOGGER.info(nPersons + " persons read from the training database");
}
// Load each person's name.
for (i = 0; i < nPersons; i++) {
String sPersonName;
String varname = "personName_" + (i + 1);
sPersonName = cvReadStringByName(
fileStorage, // fs
null, // map
varname,
"");
personNames.add(sPersonName);
}
LOGGER.info("person names: " + personNames);
// Load the data
nEigens = cvReadIntByName(
fileStorage, // fs
null, // map
"nEigens",
0); // default_value
nTrainFaces = cvReadIntByName(
fileStorage,
null, // map
"nTrainFaces",
0); // default_value
Pointer pointer = cvReadByName(
fileStorage, // fs
null, // map
"trainPersonNumMat"); // name
pTrainPersonNumMat = new CvMat(pointer);
pointer = cvReadByName(
fileStorage, // fs
null, // map
"eigenValMat"); // name
eigenValMat = new CvMat(pointer);
pointer = cvReadByName(
fileStorage, // fs
null, // map
"projectedTrainFaceMat"); // name
projectedTrainFaceMat = new CvMat(pointer);
pointer = cvReadByName(
fileStorage,
null, // map
"avgTrainImg");
pAvgTrainImg = new IplImage(pointer);
eigenVectArr = new IplImage[nTrainFaces];
for (i = 0; i <= nEigens; i++) {
String varname = "eigenVect_" + i;
pointer = cvReadByName(
fileStorage,
null, // map
varname);
eigenVectArr[i] = new IplImage(pointer);
}
// release the file-storage interface
cvReleaseFileStorage(fileStorage);
LOGGER.info("Training data loaded (" + nTrainFaces + " training images of " + nPersons + " people)");
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("People: ");
if (nPersons > 0) {
stringBuilder.append("<").append(personNames.get(0)).append(">");
}
for (i = 1; i < nPersons; i++) {
stringBuilder.append(", <").append(personNames.get(i)).append(">");
}
LOGGER.info(stringBuilder.toString());
return pTrainPersonNumMat;
}
/** Saves all the eigenvectors as images, so that they can be checked. */
private void storeEigenfaceImages() {
// Store the average image to a file
LOGGER.info("Saving the image of the average face as 'out_averageImage.bmp'");
cvSaveImage("out_averageImage.bmp", pAvgTrainImg);
// Create a large image made of many eigenface images.
// Must also convert each eigenface image to a normal 8-bit UCHAR image instead of a 32-bit float image.
LOGGER.info("Saving the " + nEigens + " eigenvector images as 'out_eigenfaces.bmp'");
if (nEigens > 0) {
// Put all the eigenfaces next to each other.
int COLUMNS = 8; // Put upto 8 images on a row.
int nCols = Math.min(nEigens, COLUMNS);
int nRows = 1 + (nEigens / COLUMNS); // Put the rest on new rows.
int w = eigenVectArr[0].width();
int h = eigenVectArr[0].height();
CvSize size = cvSize(nCols * w, nRows * h);
final IplImage bigImg = cvCreateImage(
size,
IPL_DEPTH_8U, // depth, 8-bit Greyscale UCHAR image
1); // channels
for (int i = 0; i < nEigens; i++) {
// Get the eigenface image.
IplImage byteImg = convertFloatImageToUcharImage(eigenVectArr[i]);
// Paste it into the correct position.
int x = w * (i % COLUMNS);
int y = h * (i / COLUMNS);
CvRect ROI = cvRect(x, y, w, h);
cvSetImageROI(
bigImg, // image
ROI); // rect
cvCopy(
byteImg, // src
bigImg, // dst
null); // mask
cvResetImageROI(bigImg);
cvReleaseImage(byteImg);
}
cvSaveImage(
canonize("out_eigenfaces.bmp"), // filename
bigImg); // image
cvReleaseImage(bigImg);
}
}
/** Converts the given float image to an unsigned character image.
*
* @param srcImg the given float image
* @return the unsigned character image
*/
private IplImage convertFloatImageToUcharImage(IplImage srcImg) {
IplImage dstImg;
if ((srcImg != null) && (srcImg.width() > 0 && srcImg.height() > 0)) {
// Spread the 32bit floating point pixels to fit within 8bit pixel range.
double[] minVal = new double[1];
double[] maxVal = new double[1];
cvMinMaxLoc(srcImg, minVal, maxVal);
// Deal with NaN and extreme values, since the DFT seems to give some NaN results.
if (minVal[0] < -1e30) {
minVal[0] = -1e30;
}
if (maxVal[0] > 1e30) {
maxVal[0] = 1e30;
}
if (maxVal[0] - minVal[0] == 0.0f) {
maxVal[0] = minVal[0] + 0.001; // remove potential divide by zero errors.
} // Convert the format
dstImg = cvCreateImage(cvSize(srcImg.width(), srcImg.height()), 8, 1);
cvConvertScale(srcImg, dstImg, 255.0 / (maxVal[0] - minVal[0]), -minVal[0] * 255.0 / (maxVal[0] - minVal[0]));
return dstImg;
}
return null;
}
/** Find the most likely person based on a detection. Returns the index, and stores the confidence value into pConfidence.
*
* @param projectedTestFace the projected test face
* @param pConfidencePointer a pointer containing the confidence value
* @param iTestFace the test face index
* @return the index
*/
private int findNearestNeighbor(float projectedTestFace[], FloatPointer pConfidencePointer) {
double leastDistSq = Double.MAX_VALUE;
int i = 0;
int iTrain = 0;
int iNearest = 0;
LOGGER.info("................");
LOGGER.info("find nearest neighbor from " + nTrainFaces + " training faces");
for (iTrain = 0; iTrain < nTrainFaces; iTrain++) {
//LOGGER.info("considering training face " + (iTrain + 1));
double distSq = 0;
for (i = 0; i < nEigens; i++) {
//LOGGER.debug(" projected test face distance from eigenface " + (i + 1) + " is " + projectedTestFace[i]);
float projectedTrainFaceDistance = (float) projectedTrainFaceMat.get(iTrain, i);
float d_i = projectedTestFace[i] - projectedTrainFaceDistance;
distSq += d_i * d_i; // / eigenValMat.data_fl().get(i); // Mahalanobis distance (might give better results than Eucalidean distance)
// if (iTrain < 5) {
// LOGGER.info(" ** projected training face " + (iTrain + 1) + " distance from eigenface " + (i + 1) + " is " + projectedTrainFaceDistance);
// LOGGER.info(" distance between them " + d_i);
// LOGGER.info(" distance squared " + distSq);
// }
}
if (distSq < leastDistSq) {
leastDistSq = distSq;
iNearest = iTrain;
LOGGER.info(" training face " + (iTrain + 1) + " is the new best match, least squared distance: " + leastDistSq);
}
}
// Return the confidence level based on the Euclidean distance,
// so that similar images should give a confidence between 0.5 to 1.0,
// and very different images should give a confidence between 0.0 to 0.5.
float pConfidence = (float) (1.0f - Math.sqrt(leastDistSq / (float) (nTrainFaces * nEigens)) / 255.0f);
pConfidencePointer.put(pConfidence);
LOGGER.info("training face " + (iNearest + 1) + " is the final best match, confidence " + pConfidence);
return iNearest;
}
/** Returns a string representation of the given float array.
*
* @param floatArray the given float array
* @return a string representation of the given float array
*/
private String floatArrayToString(final float[] floatArray) {
final StringBuilder stringBuilder = new StringBuilder();
boolean isFirst = true;
stringBuilder.append('[');
for (int i = 0; i < floatArray.length; i++) {
if (isFirst) {
isFirst = false;
} else {
stringBuilder.append(", ");
}
stringBuilder.append(floatArray[i]);
}
stringBuilder.append(']');
return stringBuilder.toString();
}
/** Returns a string representation of the given float pointer.
*
* @param floatPointer the given float pointer
* @return a string representation of the given float pointer
*/
private String floatPointerToString(final FloatPointer floatPointer) {
final StringBuilder stringBuilder = new StringBuilder();
boolean isFirst = true;
stringBuilder.append('[');
for (int i = 0; i < floatPointer.capacity(); i++) {
if (isFirst) {
isFirst = false;
} else {
stringBuilder.append(", ");
}
stringBuilder.append(floatPointer.get(i));
}
stringBuilder.append(']');
return stringBuilder.toString();
}
/** Returns a string representation of the given one-channel CvMat object.
*
* @param cvMat the given CvMat object
* @return a string representation of the given CvMat object
*/
public String oneChannelCvMatToString(final CvMat cvMat) {
//Preconditions
if (cvMat.channels() != 1) {
throw new RuntimeException("illegal argument - CvMat must have one channel");
}
final int type = cvMat.type();
StringBuilder s = new StringBuilder("[ ");
for (int i = 0; i < cvMat.rows(); i++) {
for (int j = 0; j < cvMat.cols(); j++) {
if (type == CV_32FC1 || type == CV_32SC1) {
s.append(cvMat.get(i, j));
} else {
throw new RuntimeException("illegal argument - CvMat must have one channel and type of float or signed integer");
}
if (j < cvMat.cols() - 1) {
s.append(", ");
}
}
if (i < cvMat.rows() - 1) {
s.append("\n ");
}
}
s.append(" ]");
return s.toString();
}
}
|
[
"[email protected]"
] | |
2902539d5611e4d82e4693ac9b6d0e6fafa6a1ef
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/35/35_685cec96fb5477fb38661dbcc8b6275fd2b30693/_Suite/35_685cec96fb5477fb38661dbcc8b6275fd2b30693__Suite_t.java
|
c5e51d1d838c383d6eacf81cd78a5b0a9bbd59b3
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null |
UTF-8
|
Java
| false | false | 9,676 |
java
|
/*
Derby - Class org.apache.derbyTesting.functionTests.tests.lang._Suite
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.derbyTesting.functionTests.tests.lang;
import org.apache.derbyTesting.functionTests.suites.XMLSuite;
import org.apache.derbyTesting.functionTests.tests.nist.NistScripts;
import org.apache.derbyTesting.junit.BaseTestCase;
import org.apache.derbyTesting.junit.JDBC;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* Suite to run all JUnit tests in this package:
* org.apache.derbyTesting.functionTests.tests.lang
* <P>
* All tests are run "as-is", just as if they were run
* individually. Thus this test is just a collection
* of all the JUNit tests in this package (excluding itself).
* While the old test harness is in use, some use of decorators
* may be required.
*
*/
public class _Suite extends BaseTestCase {
/**
* Use suite method instead.
*/
private _Suite(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite("lang");
// DERBY-1315 and DERBY-1735 need to be addressed
// before re-enabling this test as it's memory use is
// different on different vms leading to failures in
// the nightly runs.
// suite.addTest(largeCodeGen.suite());
suite.addTest(CheckConstraintTest.suite());
suite.addTest(AnsiTrimTest.suite());
suite.addTest(AlterTableTest.suite());
suite.addTest(CreateTableFromQueryTest.suite());
suite.addTest(ColumnDefaultsTest.suite());
suite.addTest(CompressTableTest.suite());
suite.addTest(DatabaseClassLoadingTest.suite());
suite.addTest(DropTableTest.suite());
suite.addTest(DynamicLikeOptimizationTest.suite());
suite.addTest(ExistsWithSubqueriesTest.suite());
suite.addTest(FloatTypesTest.suite());
suite.addTest(GrantRevokeTest.suite());
suite.addTest(GroupByExpressionTest.suite());
suite.addTest(InbetweenTest.suite());
suite.addTest(InsertTest.suite());
suite.addTest(JoinTest.suite());
suite.addTest(LangScripts.suite());
suite.addTest(MathTrigFunctionsTest.suite());
suite.addTest(PredicateTest.suite());
suite.addTest(PrepareExecuteDDL.suite());
suite.addTest(ReferentialActionsTest.suite());
suite.addTest(RolesTest.suite());
suite.addTest(RolesConferredPrivilegesTest.suite());
suite.addTest(SQLSessionContextTest.suite());
suite.addTest(RoutineSecurityTest.suite());
suite.addTest(RoutineTest.suite());
suite.addTest(SQLAuthorizationPropTest.suite());
suite.addTest(StatementPlanCacheTest.suite());
suite.addTest(StreamsTest.suite());
suite.addTest(SubqueryFlatteningTest.suite());
suite.addTest(TimeHandlingTest.suite());
suite.addTest(TriggerTest.suite());
suite.addTest(TruncateTableTest.suite());
suite.addTest(VTITest.suite());
suite.addTest(SysDiagVTIMappingTest.suite());
suite.addTest(UpdatableResultSetTest.suite());
suite.addTest(CurrentOfTest.suite());
suite.addTest(CursorTest.suite());
suite.addTest(CastingTest.suite());
suite.addTest(ScrollCursors2Test.suite());
suite.addTest(NullIfTest.suite());
suite.addTest(InListMultiProbeTest.suite());
suite.addTest(SecurityPolicyReloadingTest.suite());
suite.addTest(CurrentOfTest.suite());
suite.addTest(UnaryArithmeticParameterTest.suite());
suite.addTest(HoldCursorTest.suite());
suite.addTest(ShutdownDatabaseTest.suite());
suite.addTest(StalePlansTest.suite());
suite.addTest(SystemCatalogTest.suite());
suite.addTest(ForBitDataTest.suite());
suite.addTest(DistinctTest.suite());
suite.addTest(GroupByTest.suite());
suite.addTest(UpdateCursorTest.suite());
suite.addTest(CoalesceTest.suite());
suite.addTest(ProcedureInTriggerTest.suite());
suite.addTest(ForUpdateTest.suite());
suite.addTest(CollationTest.suite());
suite.addTest(CollationTest2.suite());
suite.addTest(ScrollCursors1Test.suite());
suite.addTest(SimpleTest.suite());
suite.addTest(GrantRevokeDDLTest.suite());
suite.addTest(ReleaseCompileLocksTest.suite());
suite.addTest(LazyDefaultSchemaCreationTest.suite());
suite.addTest(ErrorCodeTest.suite());
suite.addTest(TimestampArithTest.suite());
suite.addTest(SpillHashTest.suite());
suite.addTest(CaseExpressionTest.suite());
suite.addTest(CharUTF8Test.suite());
suite.addTest(AggregateClassLoadingTest.suite());
suite.addTest(TableFunctionTest.suite());
suite.addTest(DeclareGlobalTempTableJavaTest.suite());
suite.addTest(PrimaryKeyTest.suite());
suite.addTest(RenameTableTest.suite());
suite.addTest(RenameIndexTest.suite());
suite.addTest(Bug5052rtsTest.suite());
suite.addTest(Bug5054Test.suite());
suite.addTest(Bug4356Test.suite());
suite.addTest(SynonymTest.suite());
suite.addTest(CommentTest.suite());
suite.addTest(NestedWhereSubqueryTest.suite());
suite.addTest(ConglomerateSharingTest.suite());
suite.addTest(NullableUniqueConstraintTest.suite());
suite.addTest(UniqueConstraintSetNullTest.suite());
suite.addTest(UniqueConstraintMultiThreadedTest.suite());
suite.addTest(ViewsTest.suite());
suite.addTest(DeadlockModeTest.suite());
suite.addTest(AnsiSignaturesTest.suite());
suite.addTest(PredicatePushdownTest.suite());
suite.addTest(UngroupedAggregatesNegativeTest.suite());
suite.addTest(XplainStatisticsTest.suite());
suite.addTest(SelectivityTest.suite());
// Add the XML tests, which exist as a separate suite
// so that users can "run all XML tests" easily.
suite.addTest(XMLSuite.suite());
// Add the NIST suite in from the nist package since
// it is a SQL language related test.
suite.addTest(NistScripts.suite());
// Add the java tests that run using a master
// file (ie. partially converted).
suite.addTest(LangHarnessJavaTest.suite());
suite.addTest(ResultSetsFromPreparedStatementTest.suite());
if (!( System.getProperty("java.vm.name").equals("CVM")
&& System.getProperty("java.vm.version").startsWith("phoneme") ) )
{ // Disable temporarily until CVM/phoneME is fixed.. See DERBY-4290)
suite.addTest(OrderByAndSortAvoidance.suite());
}
// tests that do not run with JSR169
if (JDBC.vmSupportsJDBC3())
{
// test uses triggers interwoven with other tasks
// triggers may cause a generated class which calls
// java.sql.DriverManager, which will fail with JSR169.
// also, test calls procedures which use DriverManager
// to get the default connection.
suite.addTest(GrantRevokeDDLTest.suite());
// test uses regex classes that are not available in Foundation 1.1
suite.addTest(ErrorMessageTest.suite());
// Test uses DriverManager to connect to database in jar.
suite.addTest(DBInJarTest.suite());
suite.addTest(ConnectTest.suite());
// test uses PooledConnections and Savepoints
suite.addTest(DeclareGlobalTempTableJavaJDBC30Test.suite());
}
suite.addTest(BigDataTest.suite());
suite.addTest(MixedCaseExpressionTest.suite());
suite.addTest(UpdateStatisticsTest.suite());
suite.addTest(MiscErrorsTest.suite());
suite.addTest(NullsTest.suite());
suite.addTest(ArithmeticTest.suite());
suite.addTest(ConstantExpressionTest.suite());
suite.addTest(OptimizerOverridesTest.suite());
suite.addTest(PrecedenceTest.suite());
suite.addTest(GeneratedColumnsTest.suite());
suite.addTest(GeneratedColumnsPermsTest.suite());
suite.addTest(RestrictedVTITest.suite());
suite.addTest(UDTTest.suite());
suite.addTest(UDTPermsTest.suite());
suite.addTest(AlterColumnTest.suite());
suite.addTest(UserLobTest.suite());
suite.addTest(OffsetFetchNextTest.suite());
suite.addTest(SequenceTest.suite());
suite.addTest(OrderByInSubqueries.suite());
suite.addTest(OLAPTest.suite());
return suite;
}
}
|
[
"[email protected]"
] | |
5a35f2366dd8ab6c885e8f4c18099230799aea7a
|
aa499c2a918d1c51b7f08c471e50e7959198ad0a
|
/src/main/java/tk/jiemin/gx/service/WordService.java
|
fce391695e0d82892800e1a68a0822d9206b81fd
|
[] |
no_license
|
jiemin207/gx
|
6fea74e8a5fb3f255bf3c3018ca457dc178b98ff
|
3cfe1d71fde1b2ed61186e851b296edcad8bdb3a
|
refs/heads/master
| 2021-01-19T12:05:24.194965 | 2017-06-05T06:57:37 | 2017-06-05T06:57:37 | 88,018,428 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,995 |
java
|
package tk.jiemin.gx.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.FieldsDocumentPart;
import org.apache.poi.hwpf.usermodel.Field;
import org.apache.poi.hwpf.usermodel.Fields;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.stereotype.Service;
@Service
public class WordService {
public void readwriteWord(String sourcefilePath, String filepath, String fileName, Map<String, String> map) {
// 读取word模板
FileInputStream in = null;
try {
in = new FileInputStream(new File(sourcefilePath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
HWPFDocument hdt = null;
try {
hdt = new HWPFDocument(in);
} catch (IOException e1) {
e1.printStackTrace();
}
Fields fields = hdt.getFields();
Iterator<Field> it = fields.getFields(FieldsDocumentPart.MAIN).iterator();
while (it.hasNext()) {
System.out.println(it.next().getType());
}
// 读取word文本内容
Range range = hdt.getRange();
// 替换文本内容
for (Map.Entry<String, String> entry : map.entrySet()) {
range.replaceText(entry.getKey(), entry.getValue());
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
FileOutputStream out = null;
try {
out = new FileOutputStream(filepath + fileName, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
hdt.write(ostream);
} catch (IOException e) {
e.printStackTrace();
}
// 输出字节流
try {
out.write(ostream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
[
"[email protected]"
] | |
e36d235a2d19ea7c7304f91818c6889ffe1adcd8
|
b98bb0485a891af340140d1e5faf0ac0b211eeea
|
/modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.java
|
d7c3cb8710ae3c9795e510a6004e970c1f6cff61
|
[
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-khronos"
] |
permissive
|
Sorenon/lwjgl3
|
0041393d0a391f59d3f728fb0b30e59df2871829
|
9c1e8140ba0a94b01c12b6ac0efe6eb5957045f3
|
refs/heads/master
| 2023-06-24T14:15:04.898275 | 2021-07-08T16:07:06 | 2021-07-08T16:07:06 | 340,156,574 | 0 | 1 |
BSD-3-Clause
| 2021-07-08T16:07:07 | 2021-02-18T19:31:31 |
Java
|
UTF-8
|
Java
| false | false | 16,943 |
java
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* Structure describing support for the SPIR-V {@code SPV_KHR_terminate_invocation} extension.
*
* <h5>Description</h5>
*
* <p>If the {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} structure is included in the {@code pNext} chain of {@link VkPhysicalDeviceFeatures2}, it is filled with a value indicating whether the feature is supported. {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} <b>can</b> also be included in the {@code pNext} chain of {@link VkDeviceCreateInfo} to enable the features.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code sType} <b>must</b> be {@link KHRShaderTerminateInvocation#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_TERMINATE_INVOCATION_FEATURES_KHR STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_TERMINATE_INVOCATION_FEATURES_KHR}</li>
* </ul>
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR {
* VkStructureType sType;
* void * pNext;
* VkBool32 {@link #shaderTerminateInvocation};
* }</code></pre>
*/
public class VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
STYPE,
PNEXT,
SHADERTERMINATEINVOCATION;
static {
Layout layout = __struct(
__member(4),
__member(POINTER_SIZE),
__member(4)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
STYPE = layout.offsetof(0);
PNEXT = layout.offsetof(1);
SHADERTERMINATEINVOCATION = layout.offsetof(2);
}
/**
* Creates a {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** @return the value of the {@code sType} field. */
@NativeType("VkStructureType")
public int sType() { return nsType(address()); }
/** @return the value of the {@code pNext} field. */
@NativeType("void *")
public long pNext() { return npNext(address()); }
/** specifies whether the implementation supports SPIR-V modules that use the {@code SPV_KHR_terminate_invocation} extension. */
@NativeType("VkBool32")
public boolean shaderTerminateInvocation() { return nshaderTerminateInvocation(address()) != 0; }
/** Sets the specified value to the {@code sType} field. */
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
/** Sets the specified value to the {@code pNext} field. */
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR pNext(@NativeType("void *") long value) { npNext(address(), value); return this; }
/** Sets the specified value to the {@link #shaderTerminateInvocation} field. */
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR shaderTerminateInvocation(@NativeType("VkBool32") boolean value) { nshaderTerminateInvocation(address(), value ? 1 : 0); return this; }
/** Initializes this struct with the specified values. */
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR set(
int sType,
long pNext,
boolean shaderTerminateInvocation
) {
sType(sType);
pNext(pNext);
shaderTerminateInvocation(shaderTerminateInvocation);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR set(VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR malloc() {
return wrap(VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR calloc() {
return wrap(VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance allocated with {@link BufferUtils}. */
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.class, memAddress(container), container);
}
/** Returns a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance for the specified memory address. */
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR create(long address) {
return wrap(VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR createSafe(long address) {
return address == NULL ? null : wrap(VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.class, address);
}
/**
* Returns a new {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Returns a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance allocated on the thread-local {@link MemoryStack}. */
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR mallocStack(MemoryStack stack) {
return wrap(VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR callocStack(MemoryStack stack) {
return wrap(VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer mallocStack(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer callocStack(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #sType}. */
public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.STYPE); }
/** Unsafe version of {@link #pNext}. */
public static long npNext(long struct) { return memGetAddress(struct + VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.PNEXT); }
/** Unsafe version of {@link #shaderTerminateInvocation}. */
public static int nshaderTerminateInvocation(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.SHADERTERMINATEINVOCATION); }
/** Unsafe version of {@link #sType(int) sType}. */
public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.STYPE, value); }
/** Unsafe version of {@link #pNext(long) pNext}. */
public static void npNext(long struct, long value) { memPutAddress(struct + VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.PNEXT, value); }
/** Unsafe version of {@link #shaderTerminateInvocation(boolean) shaderTerminateInvocation}. */
public static void nshaderTerminateInvocation(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.SHADERTERMINATEINVOCATION, value); }
// -----------------------------------
/** An array of {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR} structs. */
public static class Buffer extends StructBuffer<VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR, Buffer> implements NativeResource {
private static final VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR ELEMENT_FACTORY = VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.create(-1L);
/**
* Creates a new {@code VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@code sType} field. */
@NativeType("VkStructureType")
public int sType() { return VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.nsType(address()); }
/** @return the value of the {@code pNext} field. */
@NativeType("void *")
public long pNext() { return VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.npNext(address()); }
/** @return the value of the {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR#shaderTerminateInvocation} field. */
@NativeType("VkBool32")
public boolean shaderTerminateInvocation() { return VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.nshaderTerminateInvocation(address()) != 0; }
/** Sets the specified value to the {@code sType} field. */
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer sType(@NativeType("VkStructureType") int value) { VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.nsType(address(), value); return this; }
/** Sets the specified value to the {@code pNext} field. */
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer pNext(@NativeType("void *") long value) { VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.npNext(address(), value); return this; }
/** Sets the specified value to the {@link VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR#shaderTerminateInvocation} field. */
public VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.Buffer shaderTerminateInvocation(@NativeType("VkBool32") boolean value) { VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR.nshaderTerminateInvocation(address(), value ? 1 : 0); return this; }
}
}
|
[
"[email protected]"
] | |
c8d5ef06446949cfe0fe28334ce7471c369b0bee
|
c885ef92397be9d54b87741f01557f61d3f794f3
|
/tests-without-trycatch/Math-6/org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer/BBC-F0-opt-10/19/org/apache/commons/math3/optim/nonlinear/vector/jacobian/LevenbergMarquardtOptimizer_ESTest.java
|
4312dc715df3d99e3b8f7b3a97968bc97d960391
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
pderakhshanfar/EMSE-BBC-experiment
|
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
|
fea1a92c2e7ba7080b8529e2052259c9b697bbda
|
refs/heads/main
| 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null |
UTF-8
|
Java
| false | false | 2,790 |
java
|
/*
* This file was automatically generated by EvoSuite
* Thu Oct 21 11:54:17 GMT 2021
*/
package org.apache.commons.math3.optim.nonlinear.vector.jacobian;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.apache.commons.math3.optim.ConvergenceChecker;
import org.apache.commons.math3.optim.PointVectorValuePair;
import org.apache.commons.math3.optim.SimpleVectorValueChecker;
import org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class LevenbergMarquardtOptimizer_ESTest extends LevenbergMarquardtOptimizer_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
LevenbergMarquardtOptimizer levenbergMarquardtOptimizer0 = new LevenbergMarquardtOptimizer(0.0, 2.0, 0.0);
assertEquals(0.0, levenbergMarquardtOptimizer0.getChiSquare(), 0.01);
}
@Test(timeout = 4000)
public void test1() throws Throwable {
LevenbergMarquardtOptimizer levenbergMarquardtOptimizer0 = new LevenbergMarquardtOptimizer(100.0, 703.3750025, 0.5, 0.5, 0.5);
assertEquals(0.0, levenbergMarquardtOptimizer0.getChiSquare(), 0.01);
}
@Test(timeout = 4000)
public void test2() throws Throwable {
SimpleVectorValueChecker simpleVectorValueChecker0 = new SimpleVectorValueChecker(1.0, 1.0);
LevenbergMarquardtOptimizer levenbergMarquardtOptimizer0 = new LevenbergMarquardtOptimizer(Double.NaN, simpleVectorValueChecker0, Double.NaN, 1494.8208, 0.0, Double.NaN);
// Undeclared exception!
// try {
levenbergMarquardtOptimizer0.doOptimize();
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.apache.commons.math3.optim.nonlinear.vector.MultivariateVectorOptimizer", e);
// }
}
@Test(timeout = 4000)
public void test3() throws Throwable {
LevenbergMarquardtOptimizer levenbergMarquardtOptimizer0 = new LevenbergMarquardtOptimizer();
assertEquals(0.0, levenbergMarquardtOptimizer0.getChiSquare(), 0.01);
}
@Test(timeout = 4000)
public void test4() throws Throwable {
LevenbergMarquardtOptimizer levenbergMarquardtOptimizer0 = new LevenbergMarquardtOptimizer((ConvergenceChecker<PointVectorValuePair>) null);
assertEquals(0.0, levenbergMarquardtOptimizer0.getChiSquare(), 0.01);
}
}
|
[
"[email protected]"
] | |
4450651cf7b8c744ecd9691bedaf052bddcbff57
|
d7789119ab5084876fa7fea9bb52ea2c761c4bbf
|
/sdk/src/main/java/com/velopayments/blockchain/sdk/entity/EntityKeyConfigBuilder.java
|
4d33cc37e6737fabbf6c7f9921c68b0205acec2b
|
[
"MIT"
] |
permissive
|
hocktide/v-j-sdk
|
5090969a0bbfa906abd7cb6cfadc3c7e5a1e5574
|
f60fe9414b25bb783f9d54ba424af001699ac189
|
refs/heads/master
| 2022-11-06T23:46:52.725570 | 2020-06-17T01:36:28 | 2020-06-17T01:36:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 7,187 |
java
|
package com.velopayments.blockchain.sdk.entity;
import com.velopayments.blockchain.cert.*;
import com.velopayments.blockchain.crypt.*;
import com.velopayments.blockchain.sdk.ArrayUtils;
import com.velopayments.blockchain.sdk.BlockchainUtils;
import com.velopayments.blockchain.sdk.metadata.ArtifactState;
import com.velopayments.blockchain.sdk.metadata.ArtifactTypeMetadataBuilder;
import com.velopayments.blockchain.sdk.metadata.CoreMetadata;
import com.velopayments.blockchain.sdk.metadata.TransactionType;
import lombok.val;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
import static com.velopayments.blockchain.sdk.Base64Util.fromBase64;
import static com.velopayments.blockchain.sdk.Base64Util.toBase64;
import static com.velopayments.blockchain.sdk.BlockchainUtils.INITIAL_TRANSACTION_UUID;
import static com.velopayments.blockchain.sdk.entity.EntityKeyConfigContentType.UnprotectedPlusPassphraseProtected;
import static com.velopayments.blockchain.sdk.metadata.ArtifactTypeMetadataBuilder.extractMetadata;
import static java.util.UUID.randomUUID;
/**
* Helper class for building {@link EntityKeyConfig}s
*/
public final class EntityKeyConfigBuilder {
private EntityKeyConfigBuilder() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
public static EntityKeyConfig toEntityKeyConfig(UUID entityId, String entityName, EncryptionKeyPair encryptionKeyPair, SigningKeyPair signingKeyPair, String passPhrase) {
val keyConfigBuilder = EntityKeyConfig.builder()
.entityId(entityId)
.entityName(entityName)
.signingKeyPair(signingKeyPair)
.encryptionKeyPair(encryptionKeyPair);
if (passPhrase == null) {
keyConfigBuilder.contentType(EntityKeyConfigContentType.UnprotectedOnly);
}
else {
keyConfigBuilder.contentType(UnprotectedPlusPassphraseProtected);
keyConfigBuilder.passphraseProtectedCertificateBase64(toCertificate(entityId, entityName, encryptionKeyPair, signingKeyPair, passPhrase));
}
return keyConfigBuilder.build();
}
public static final class EntityKeyConfigMetadata {
public static final String ENTITY_KEY_CONFIG_TYPE_NAME = "ENTITY_KEY_CONFIG";
public static final UUID ENTITY_KEY_CONFIG_TYPE_ID = UUID.fromString("98129efd-86e9-406d-80aa-e0d3ee7042a0");
public static final TransactionType PRIVATE_ENTITY = new TransactionType(CertificateType.PRIVATE_ENTITY, "PRIVATE_ENTITY");
public static final ArtifactState STATE_NEW = new ArtifactState(100, "NEW");
public static final ArtifactState STATE_CREATED = new ArtifactState(101, "CREATED");
private EntityKeyConfigMetadata() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
public static ArtifactTypeMetadataBuilder create() {
return extractMetadata(ENTITY_KEY_CONFIG_TYPE_ID, ENTITY_KEY_CONFIG_TYPE_NAME, EntityKeyConfigMetadata.class);
}
}
private static String toCertificate(UUID entityId, String entityName, EncryptionKeyPair encryptionKeyPair, SigningKeyPair signingKeyPair, String passPhrase) {
val cert = BlockchainUtils.transactionCertificateBuilder()
.transactionId(randomUUID())
.previousTransactionId(INITIAL_TRANSACTION_UUID)
.transactionType(EntityKeyConfigMetadata.PRIVATE_ENTITY.getId())
.artifactId(entityId)
.artifactType(EntityKeyConfigMetadata.ENTITY_KEY_CONFIG_TYPE_ID)
.previousState(EntityKeyConfigMetadata.STATE_NEW.getValue())
.newState(EntityKeyConfigMetadata.STATE_CREATED.getValue())
.withFields()
.addByteArray(Field.PUBLIC_ENCRYPTION_KEY, encryptionKeyPair.getPublicKey().getRawBytes())
.addByteArray(Field.PRIVATE_ENCRYPTION_KEY, encryptionKeyPair.getPrivateKey().getRawBytes())
.addByteArray(Field.PUBLIC_SIGNING_KEY, signingKeyPair.getPublicKey().getRawBytes())
.addByteArray(Field.PRIVATE_SIGNING_KEY, signingKeyPair.getPrivateKey().getRawBytes())
.addString(CoreMetadata.DISPLAY_NAME.getId(), entityName)
.sign(entityId, signingKeyPair.getPrivateKey());
byte[] saltPlusEncrypted = encrypt(cert.toByteArray(), passPhrase);
return toBase64(saltPlusEncrypted);
}
/**
* Rebuild an EntityKeyConfig from the persisted format
*/
public static EntityKeyConfig fromJson(String json, String passPhrase) throws InvalidPassphraseException {
val protectedKeyConfig = EntityKeysSerializer.fromJson(json);
byte[] encryptedBytes = fromBase64(protectedKeyConfig.getPassphraseProtectedCertificateBase64());
byte[] certSrc = decrypt(encryptedBytes, passPhrase);
val reader = new CertificateReader(new CertificateParser(Certificate.fromByteArray(certSrc)));
val encryptionKeyPair = new EncryptionKeyPair(
new EncryptionPublicKey(reader.getFirst(Field.PUBLIC_ENCRYPTION_KEY).asByteArray()),
new EncryptionPrivateKey(reader.getFirst(Field.PRIVATE_ENCRYPTION_KEY).asByteArray()));
val signingKeyPair = new SigningKeyPair(
new SigningPublicKey(reader.getFirst(Field.PUBLIC_SIGNING_KEY).asByteArray()),
new SigningPrivateKey(reader.getFirst(Field.PRIVATE_SIGNING_KEY).asByteArray())
);
return EntityKeyConfig.builder()
.entityId(reader.getFirst(Field.ARTIFACT_ID).asUUID())
.entityName(reader.getFirst(CoreMetadata.DISPLAY_NAME.getId()).asString())
.contentType(UnprotectedPlusPassphraseProtected)
.encryptionKeyPair(encryptionKeyPair)
.signingKeyPair(signingKeyPair)
.passphraseProtectedCertificateBase64(protectedKeyConfig.getPassphraseProtectedCertificateBase64())
.build();
}
/**
* Encrypt the bytes using the pass phrase
*/
static byte[] encrypt(byte[] plainBytes, String passPhrase) {
Random r = new SecureRandom();
byte[] salt = new byte[32];
r.nextBytes(salt);
Key key = Key.createFromPassword(salt, 10 * 1000, passPhrase);
val cipher = new SimpleStreamCipher(key);
byte[] encryptedBytes = cipher.encrypt(plainBytes);
return ArrayUtils.addAll(salt, encryptedBytes);
}
/**
* Decrypt the bytes using the pass phrase
*/
static byte[] decrypt(byte[] encryptedBytes, String passPhrase) {
try {
byte[] salt = Arrays.copyOfRange(encryptedBytes, 0, 32);
byte[] certEncrypted = Arrays.copyOfRange(encryptedBytes, 32, encryptedBytes.length);
//use the pass phrase to access the certificate / reader
Key key = Key.createFromPassword(salt, 10 * 1000, passPhrase);
val cipher = new SimpleStreamCipher(key);
return cipher.decrypt(certEncrypted);
}
catch (MessageAuthenticationException e) {
throw new InvalidPassphraseException();
}
}
}
|
[
"[email protected]"
] | |
c1e4dc1c29034221b7c69a515e922d7a4772e80d
|
28552d7aeffe70c38960738da05ebea4a0ddff0c
|
/google-ads/src/main/java/com/google/ads/googleads/v6/services/MutateCustomerClientLinkResult.java
|
6756fc2c8b5c39400ca514f75fc0d31c9375fb9a
|
[
"Apache-2.0"
] |
permissive
|
PierrickVoulet/google-ads-java
|
6f84a3c542133b892832be8e3520fb26bfdde364
|
f0a9017f184cad6a979c3048397a944849228277
|
refs/heads/master
| 2021-08-22T08:13:52.146440 | 2020-12-09T17:10:48 | 2020-12-09T17:10:48 | 250,642,529 | 0 | 0 |
Apache-2.0
| 2020-03-27T20:41:26 | 2020-03-27T20:41:25 | null |
UTF-8
|
Java
| false | true | 21,214 |
java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v6/services/customer_client_link_service.proto
package com.google.ads.googleads.v6.services;
/**
* <pre>
* The result for a single customer client link mutate.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v6.services.MutateCustomerClientLinkResult}
*/
public final class MutateCustomerClientLinkResult extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v6.services.MutateCustomerClientLinkResult)
MutateCustomerClientLinkResultOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateCustomerClientLinkResult.newBuilder() to construct.
private MutateCustomerClientLinkResult(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateCustomerClientLinkResult() {
resourceName_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateCustomerClientLinkResult();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private MutateCustomerClientLinkResult(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
resourceName_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v6.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v6_services_MutateCustomerClientLinkResult_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v6.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v6_services_MutateCustomerClientLinkResult_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult.class, com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult.Builder.class);
}
public static final int RESOURCE_NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object resourceName_;
/**
* <pre>
* Returned for successful operations.
* </pre>
*
* <code>string resource_name = 1;</code>
* @return The resourceName.
*/
@java.lang.Override
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
}
}
/**
* <pre>
* Returned for successful operations.
* </pre>
*
* <code>string resource_name = 1;</code>
* @return The bytes for resourceName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getResourceNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getResourceNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult)) {
return super.equals(obj);
}
com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult other = (com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult) obj;
if (!getResourceName()
.equals(other.getResourceName())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getResourceName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* The result for a single customer client link mutate.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v6.services.MutateCustomerClientLinkResult}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v6.services.MutateCustomerClientLinkResult)
com.google.ads.googleads.v6.services.MutateCustomerClientLinkResultOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v6.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v6_services_MutateCustomerClientLinkResult_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v6.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v6_services_MutateCustomerClientLinkResult_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult.class, com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult.Builder.class);
}
// Construct using com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult.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();
resourceName_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v6.services.CustomerClientLinkServiceProto.internal_static_google_ads_googleads_v6_services_MutateCustomerClientLinkResult_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult getDefaultInstanceForType() {
return com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult build() {
com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult buildPartial() {
com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult result = new com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult(this);
result.resourceName_ = resourceName_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult) {
return mergeFrom((com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult other) {
if (other == com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult.getDefaultInstance()) return this;
if (!other.getResourceName().isEmpty()) {
resourceName_ = other.resourceName_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object resourceName_ = "";
/**
* <pre>
* Returned for successful operations.
* </pre>
*
* <code>string resource_name = 1;</code>
* @return The resourceName.
*/
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Returned for successful operations.
* </pre>
*
* <code>string resource_name = 1;</code>
* @return The bytes for resourceName.
*/
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Returned for successful operations.
* </pre>
*
* <code>string resource_name = 1;</code>
* @param value The resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resourceName_ = value;
onChanged();
return this;
}
/**
* <pre>
* Returned for successful operations.
* </pre>
*
* <code>string resource_name = 1;</code>
* @return This builder for chaining.
*/
public Builder clearResourceName() {
resourceName_ = getDefaultInstance().getResourceName();
onChanged();
return this;
}
/**
* <pre>
* Returned for successful operations.
* </pre>
*
* <code>string resource_name = 1;</code>
* @param value The bytes for resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resourceName_ = value;
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:google.ads.googleads.v6.services.MutateCustomerClientLinkResult)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v6.services.MutateCustomerClientLinkResult)
private static final com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult();
}
public static com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateCustomerClientLinkResult>
PARSER = new com.google.protobuf.AbstractParser<MutateCustomerClientLinkResult>() {
@java.lang.Override
public MutateCustomerClientLinkResult parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new MutateCustomerClientLinkResult(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<MutateCustomerClientLinkResult> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateCustomerClientLinkResult> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v6.services.MutateCustomerClientLinkResult getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
[
"[email protected]"
] | |
f342bf35096cc3a52daf208a5a5fe4f11ab551b0
|
27f7409f76c6f6d8e4ac698115f3741e5208bec7
|
/oneMovieWebApp/src/controller/member/JoinFormCommand.java
|
9b547df7569cf37f156723c1659481b61575dc5d
|
[] |
no_license
|
whsanha55/oneMovieWepApp
|
857c78940dc443187626685b0bb704bd6eda0262
|
1df276f096f0c71eb86d68e03a88282ac844e7cf
|
refs/heads/master
| 2021-05-06T00:54:36.240003 | 2017-12-29T08:35:38 | 2017-12-29T08:35:38 | 114,337,917 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 636 |
java
|
package controller.member;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import controller.ActionForward;
import controller.Command;
public class JoinFormCommand implements Command {
@Override
public ActionForward execute(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
ActionForward forward = new ActionForward();
forward.setPath("/layoutUser.jsp?article=/user/member/joinForm.jsp");
forward.setRedirect(false);
return forward;
}
}
|
[
"USER@USER-PC"
] |
USER@USER-PC
|
a11372af50f2ab0cff065d3f4438680e35ca08a1
|
3438e8c139a5833836a91140af412311aebf9e86
|
/chrome/android/java/src/org/chromium/chrome/browser/toolbar/CustomTabToolbar.java
|
e83afab71f8f3fc6ef68e1be666f62764b11ab16
|
[
"BSD-3-Clause"
] |
permissive
|
Exstream-OpenSource/Chromium
|
345b4336b2fbc1d5609ac5a67dbf361812b84f54
|
718ca933938a85c6d5548c5fad97ea7ca1128751
|
refs/heads/master
| 2022-12-21T20:07:40.786370 | 2016-10-18T04:53:43 | 2016-10-18T04:53:43 | 71,210,435 | 0 | 2 |
BSD-3-Clause
| 2022-12-18T12:14:22 | 2016-10-18T04:58:13 | null |
UTF-8
|
Java
| false | false | 31,159 |
java
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.toolbar;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Pair;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.ThreadUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.library_loader.LibraryLoader;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.UrlConstants;
import org.chromium.chrome.browser.WindowDelegate;
import org.chromium.chrome.browser.appmenu.AppMenuButtonHelper;
import org.chromium.chrome.browser.dom_distiller.DomDistillerServiceFactory;
import org.chromium.chrome.browser.dom_distiller.DomDistillerTabUtils;
import org.chromium.chrome.browser.ntp.NativePageFactory;
import org.chromium.chrome.browser.ntp.NewTabPage;
import org.chromium.chrome.browser.omnibox.LocationBar;
import org.chromium.chrome.browser.omnibox.LocationBarLayout;
import org.chromium.chrome.browser.omnibox.UrlBar;
import org.chromium.chrome.browser.omnibox.UrlFocusChangeListener;
import org.chromium.chrome.browser.pageinfo.WebsiteSettingsPopup;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.toolbar.ActionModeController.ActionBarDelegate;
import org.chromium.chrome.browser.util.ColorUtils;
import org.chromium.chrome.browser.widget.TintedDrawable;
import org.chromium.chrome.browser.widget.TintedImageButton;
import org.chromium.components.dom_distiller.core.DomDistillerService;
import org.chromium.components.dom_distiller.core.DomDistillerUrlUtils;
import org.chromium.components.security_state.ConnectionSecurityLevel;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.interpolators.BakedBezierInterpolator;
import org.chromium.ui.widget.Toast;
import java.util.List;
/**
* The Toolbar layout to be used for a custom tab. This is used for both phone and tablet UIs.
*/
public class CustomTabToolbar extends ToolbarLayout implements LocationBar,
View.OnLongClickListener {
/**
* A simple {@link FrameLayout} that prevents its children from getting touch events. This is
* especially useful to prevent {@link UrlBar} from running custom touch logic since it is
* read-only in custom tabs.
*/
public static class InterceptTouchLayout extends FrameLayout {
private GestureDetector mGestureDetector;
public InterceptTouchLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(getContext(),
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (LibraryLoader.isInitialized()) {
RecordUserAction.record("CustomTabs.TapUrlBar");
}
return super.onSingleTapConfirmed(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
}
private static final int TITLE_ANIM_DELAY_MS = 800;
private static final int STATE_DOMAIN_ONLY = 0;
private static final int STATE_TITLE_ONLY = 1;
private static final int STATE_DOMAIN_AND_TITLE = 2;
private View mLocationBarFrameLayout;
private View mTitleUrlContainer;
private UrlBar mUrlBar;
private TextView mTitleBar;
private TintedImageButton mSecurityButton;
private ImageButton mCustomActionButton;
private int mSecurityIconType;
private ImageButton mCloseButton;
// Whether dark tint should be applied to icons and text.
private boolean mUseDarkColors = true;
private ValueAnimator mBrandColorTransitionAnimation;
private boolean mBrandColorTransitionActive;
private CustomTabToolbarAnimationDelegate mAnimDelegate;
private int mState = STATE_DOMAIN_ONLY;
private String mFirstUrl;
private boolean mShowsOfflinePage = false;
private Runnable mTitleAnimationStarter = new Runnable() {
@Override
public void run() {
mAnimDelegate.startTitleAnimation(getContext());
}
};
/**
* Constructor for getting this class inflated from an xml layout file.
*/
public CustomTabToolbar(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
setBackground(new ColorDrawable(
ApiCompatibilityUtils.getColor(getResources(), R.color.default_primary_color)));
mUrlBar = (UrlBar) findViewById(R.id.url_bar);
mUrlBar.setHint("");
mUrlBar.setDelegate(this);
mUrlBar.setEnabled(false);
mUrlBar.setAllowFocus(false);
mTitleBar = (TextView) findViewById(R.id.title_bar);
mLocationBarFrameLayout = findViewById(R.id.location_bar_frame_layout);
mTitleUrlContainer = findViewById(R.id.title_url_container);
mTitleUrlContainer.setOnLongClickListener(this);
mSecurityButton = (TintedImageButton) findViewById(R.id.security_button);
mSecurityIconType = ConnectionSecurityLevel.NONE;
mCustomActionButton = (ImageButton) findViewById(R.id.action_button);
mCustomActionButton.setOnLongClickListener(this);
mCloseButton = (ImageButton) findViewById(R.id.close_button);
mCloseButton.setOnLongClickListener(this);
mAnimDelegate = new CustomTabToolbarAnimationDelegate(mSecurityButton, mTitleUrlContainer);
}
@Override
protected int getToolbarHeightWithoutShadowResId() {
return R.dimen.custom_tabs_control_container_height;
}
@Override
public void initialize(ToolbarDataProvider toolbarDataProvider,
ToolbarTabController tabController, AppMenuButtonHelper appMenuButtonHelper) {
super.initialize(toolbarDataProvider, tabController, appMenuButtonHelper);
updateVisualsForState();
}
@Override
public void onNativeLibraryReady() {
super.onNativeLibraryReady();
mSecurityButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Tab currentTab = getToolbarDataProvider().getTab();
if (currentTab == null || currentTab.getWebContents() == null) return;
Activity activity = currentTab.getWindowAndroid().getActivity().get();
if (activity == null) return;
String publisherName = mState == STATE_TITLE_ONLY
? parsePublisherNameFromUrl(currentTab.getUrl()) : null;
WebsiteSettingsPopup.show(activity, currentTab, publisherName,
WebsiteSettingsPopup.OPENED_FROM_TOOLBAR);
}
});
}
@Override
public void setCloseButtonImageResource(Drawable drawable) {
mCloseButton.setImageDrawable(drawable);
}
@Override
public void setCustomTabCloseClickHandler(OnClickListener listener) {
mCloseButton.setOnClickListener(listener);
}
@Override
public void setCustomActionButton(Drawable drawable, String description,
OnClickListener listener) {
Resources resources = getResources();
// The height will be scaled to match spec while keeping the aspect ratio, so get the scaled
// width through that.
int sourceHeight = drawable.getIntrinsicHeight();
int sourceScaledHeight = resources.getDimensionPixelSize(R.dimen.toolbar_icon_height);
int sourceWidth = drawable.getIntrinsicWidth();
int sourceScaledWidth = sourceWidth * sourceScaledHeight / sourceHeight;
int minPadding = resources.getDimensionPixelSize(R.dimen.min_toolbar_icon_side_padding);
int sidePadding = Math.max((2 * sourceScaledHeight - sourceScaledWidth) / 2, minPadding);
int topPadding = mCustomActionButton.getPaddingTop();
int bottomPadding = mCustomActionButton.getPaddingBottom();
mCustomActionButton.setPadding(sidePadding, topPadding, sidePadding, bottomPadding);
mCustomActionButton.setImageDrawable(drawable);
mCustomActionButton.setContentDescription(description);
mCustomActionButton.setOnClickListener(listener);
mCustomActionButton.setVisibility(VISIBLE);
updateButtonsTint();
}
/**
* @return The custom action button. For test purpose only.
*/
@VisibleForTesting
public ImageButton getCustomActionButtonForTest() {
return mCustomActionButton;
}
@Override
public int getTabStripHeight() {
return 0;
}
@Override
public Tab getCurrentTab() {
return getToolbarDataProvider().getTab();
}
@Override
public boolean shouldEmphasizeHttpsScheme() {
int securityLevel = getSecurityLevel();
return securityLevel == ConnectionSecurityLevel.DANGEROUS
|| securityLevel == ConnectionSecurityLevel.SECURE_WITH_POLICY_INSTALLED_CERT;
}
@Override
public void setShowTitle(boolean showTitle) {
if (showTitle) {
mState = STATE_DOMAIN_AND_TITLE;
mAnimDelegate.prepareTitleAnim(mUrlBar, mTitleBar);
} else {
mState = STATE_DOMAIN_ONLY;
}
}
@Override
public void setUrlBarHidden(boolean hideUrlBar) {
// Urlbar visibility cannot be toggled if it is the only visible element.
if (mState == STATE_DOMAIN_ONLY) return;
if (hideUrlBar && mState == STATE_DOMAIN_AND_TITLE) {
mState = STATE_TITLE_ONLY;
mAnimDelegate.setTitleAnimationEnabled(false);
mUrlBar.setVisibility(View.GONE);
mTitleBar.setVisibility(View.VISIBLE);
LayoutParams lp = (LayoutParams) mTitleBar.getLayoutParams();
lp.bottomMargin = 0;
mTitleBar.setLayoutParams(lp);
mTitleBar.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.location_bar_url_text_size));
} else if (!hideUrlBar && mState == STATE_TITLE_ONLY) {
mState = STATE_DOMAIN_AND_TITLE;
mTitleBar.setVisibility(View.VISIBLE);
mUrlBar.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.custom_tabs_url_text_size));
mUrlBar.setVisibility(View.VISIBLE);
LayoutParams lp = (LayoutParams) mTitleBar.getLayoutParams();
lp.bottomMargin = getResources()
.getDimensionPixelSize(R.dimen.custom_tabs_toolbar_vertical_padding);
mTitleBar.setLayoutParams(lp);
mTitleBar.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.custom_tabs_title_text_size));
updateSecurityIcon(getSecurityLevel());
} else {
assert false : "Unreached state";
}
}
@Override
public String getContentPublisher() {
if (mState == STATE_TITLE_ONLY) {
if (getToolbarDataProvider().getTab() == null) return null;
return parsePublisherNameFromUrl(getToolbarDataProvider().getTab().getUrl());
}
return null;
}
@Override
public void setTitleToPageTitle() {
Tab currentTab = getToolbarDataProvider().getTab();
if (currentTab == null || TextUtils.isEmpty(currentTab.getTitle())) {
mTitleBar.setText("");
return;
}
String title = currentTab.getTitle();
// It takes some time to parse the title of the webcontent, and before that Tab#getTitle
// always return the url. We postpone the title animation until the title is authentic.
if ((mState == STATE_DOMAIN_AND_TITLE || mState == STATE_TITLE_ONLY)
&& !title.equals(currentTab.getUrl())
&& !title.equals(UrlConstants.ABOUT_BLANK)) {
// Delay the title animation until security icon animation finishes.
ThreadUtils.postOnUiThreadDelayed(mTitleAnimationStarter, TITLE_ANIM_DELAY_MS);
}
mTitleBar.setText(title);
}
@Override
protected void onNavigatedToDifferentPage() {
super.onNavigatedToDifferentPage();
setTitleToPageTitle();
if (mState == STATE_TITLE_ONLY) {
if (TextUtils.isEmpty(mFirstUrl)) {
mFirstUrl = getToolbarDataProvider().getTab().getUrl();
} else {
if (mFirstUrl.equals(getToolbarDataProvider().getTab().getUrl())) return;
setUrlBarHidden(false);
}
}
updateSecurityIcon(getSecurityLevel());
}
@Override
public void setUrlToPageUrl() {
if (getCurrentTab() == null) {
mUrlBar.setUrl("", null);
return;
}
String url = getCurrentTab().getUrl().trim();
// Don't show anything for Chrome URLs and "about:blank".
// If we have taken a pre-initialized WebContents, then the starting URL
// is "about:blank". We should not display it.
if (NativePageFactory.isNativePageUrl(url, getCurrentTab().isIncognito())
|| UrlConstants.ABOUT_BLANK.equals(url)) {
mUrlBar.setUrl("", null);
return;
}
String displayText = getToolbarDataProvider().getText();
Pair<String, String> urlText = LocationBarLayout.splitPathFromUrlDisplayText(displayText);
displayText = urlText.first;
if (DomDistillerUrlUtils.isDistilledPage(url)) {
if (isStoredArticle(url)) {
Profile profile = getCurrentTab().getProfile();
DomDistillerService domDistillerService =
DomDistillerServiceFactory.getForProfile(profile);
String originalUrl = domDistillerService.getUrlForEntry(
DomDistillerUrlUtils.getValueForKeyInUrl(url, "entry_id"));
displayText =
DomDistillerTabUtils.getFormattedUrlFromOriginalDistillerUrl(originalUrl);
} else if (DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl(url) != null) {
String originalUrl = DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl(url);
displayText =
DomDistillerTabUtils.getFormattedUrlFromOriginalDistillerUrl(originalUrl);
}
}
if (mUrlBar.setUrl(url, displayText)) {
mUrlBar.deEmphasizeUrl();
mUrlBar.emphasizeUrl();
}
}
private boolean isStoredArticle(String url) {
DomDistillerService domDistillerService =
DomDistillerServiceFactory.getForProfile(Profile.getLastUsedProfile());
String entryIdFromUrl = DomDistillerUrlUtils.getValueForKeyInUrl(url, "entry_id");
if (TextUtils.isEmpty(entryIdFromUrl)) return false;
return domDistillerService.hasEntry(entryIdFromUrl);
}
@Override
public void updateLoadingState(boolean updateUrl) {
if (updateUrl) setUrlToPageUrl();
updateSecurityIcon(getSecurityLevel());
}
@Override
public void updateVisualsForState() {
Resources resources = getResources();
updateSecurityIcon(getSecurityLevel());
updateButtonsTint();
mUrlBar.setUseDarkTextColors(mUseDarkColors);
int titleTextColor = mUseDarkColors
? ApiCompatibilityUtils.getColor(resources, R.color.url_emphasis_default_text)
: ApiCompatibilityUtils.getColor(resources,
R.color.url_emphasis_light_default_text);
mTitleBar.setTextColor(titleTextColor);
if (getProgressBar() != null) {
if (!ColorUtils.isUsingDefaultToolbarColor(getResources(),
getBackground().getColor())) {
getProgressBar().setThemeColor(getBackground().getColor(), false);
} else {
getProgressBar().setBackgroundColor(ApiCompatibilityUtils.getColor(resources,
R.color.progress_bar_background));
getProgressBar().setForegroundColor(ApiCompatibilityUtils.getColor(resources,
R.color.progress_bar_foreground));
}
}
}
private void updateButtonsTint() {
mMenuButton.setTint(mUseDarkColors ? mDarkModeTint : mLightModeTint);
if (mCloseButton.getDrawable() instanceof TintedDrawable) {
((TintedDrawable) mCloseButton.getDrawable()).setTint(
mUseDarkColors ? mDarkModeTint : mLightModeTint);
}
if (mCustomActionButton.getDrawable() instanceof TintedDrawable) {
((TintedDrawable) mCustomActionButton.getDrawable()).setTint(
mUseDarkColors ? mDarkModeTint : mLightModeTint);
}
if (mSecurityButton.getDrawable() instanceof TintedDrawable) {
((TintedDrawable) mSecurityButton.getDrawable()).setTint(
mUseDarkColors ? mDarkModeTint : mLightModeTint);
}
}
@Override
public void setMenuButtonHelper(final AppMenuButtonHelper helper) {
mMenuButton.setOnTouchListener(new OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
return helper.onTouch(v, event);
}
});
mMenuButton.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
return helper.onEnterKeyPress(view);
}
return false;
}
});
}
@Override
public View getMenuAnchor() {
return mMenuButton;
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setTitleToPageTitle();
setUrlToPageUrl();
}
@Override
public ColorDrawable getBackground() {
return (ColorDrawable) super.getBackground();
}
@Override
public void initializeControls(WindowDelegate windowDelegate, ActionBarDelegate delegate,
WindowAndroid windowAndroid) {
}
private int getSecurityLevel() {
if (getCurrentTab() == null) return ConnectionSecurityLevel.NONE;
return getCurrentTab().getSecurityLevel();
}
@Override
public void updateSecurityIcon(int securityLevel) {
if (mState == STATE_TITLE_ONLY) return;
mSecurityIconType = securityLevel;
boolean isOfflinePage = getCurrentTab() != null && getCurrentTab().isOfflinePage();
boolean showSecurityButton = securityLevel != ConnectionSecurityLevel.NONE || isOfflinePage;
if (securityLevel == ConnectionSecurityLevel.NONE) {
if (isOfflinePage && mShowsOfflinePage != isOfflinePage) {
TintedDrawable bolt = TintedDrawable.constructTintedDrawable(
getResources(), R.drawable.offline_pin);
bolt.setTint(mUseDarkColors ? mDarkModeTint : mLightModeTint);
mSecurityButton.setImageDrawable(bolt);
}
} else {
boolean isSmallDevice = !DeviceFormFactor.isTablet(getContext());
int id = LocationBarLayout.getSecurityIconResource(securityLevel, isSmallDevice);
if (id == 0) {
// Hide the button if we don't have an actual icon to display.
showSecurityButton = false;
} else {
// ImageView#setImageResource is no-op if given resource is the current one.
mSecurityButton.setImageResource(id);
mSecurityButton.setTint(
LocationBarLayout.getColorStateList(securityLevel, getToolbarDataProvider(),
getResources(), false /* omnibox is not opaque */));
}
}
mShowsOfflinePage = isOfflinePage;
if (showSecurityButton) {
mAnimDelegate.showSecurityButton();
} else {
mAnimDelegate.hideSecurityButton();
}
mUrlBar.emphasizeUrl();
mUrlBar.invalidate();
}
/**
* For extending classes to override and carry out the changes related with the primary color
* for the current tab changing.
*/
@Override
protected void onPrimaryColorChanged(boolean shouldAnimate) {
if (mBrandColorTransitionActive) mBrandColorTransitionAnimation.cancel();
final ColorDrawable background = getBackground();
final int initialColor = background.getColor();
final int finalColor = getToolbarDataProvider().getPrimaryColor();
if (background.getColor() == finalColor) return;
mBrandColorTransitionAnimation = ValueAnimator.ofFloat(0, 1)
.setDuration(ToolbarPhone.THEME_COLOR_TRANSITION_DURATION);
mBrandColorTransitionAnimation.setInterpolator(BakedBezierInterpolator.TRANSFORM_CURVE);
mBrandColorTransitionAnimation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float fraction = animation.getAnimatedFraction();
int red = (int) (Color.red(initialColor)
+ fraction * (Color.red(finalColor) - Color.red(initialColor)));
int green = (int) (Color.green(initialColor)
+ fraction * (Color.green(finalColor) - Color.green(initialColor)));
int blue = (int) (Color.blue(initialColor)
+ fraction * (Color.blue(finalColor) - Color.blue(initialColor)));
background.setColor(Color.rgb(red, green, blue));
}
});
mBrandColorTransitionAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mBrandColorTransitionActive = false;
// Using the current background color instead of the final color in case this
// animation was cancelled. This ensures the assets are updated to the visible
// color.
mUseDarkColors =
!ColorUtils.shouldUseLightForegroundOnBackground(background.getColor());
updateVisualsForState();
}
});
mBrandColorTransitionAnimation.start();
mBrandColorTransitionActive = true;
if (!shouldAnimate) mBrandColorTransitionAnimation.end();
}
@Override
public View getContainerView() {
return this;
}
@Override
public void setDefaultTextEditActionModeCallback(ToolbarActionModeCallback callback) {
mUrlBar.setCustomSelectionActionModeCallback(callback);
}
private void updateLayoutParams() {
int startMargin = 0;
int locationBarLayoutChildIndex = -1;
for (int i = 0; i < getChildCount(); i++) {
View childView = getChildAt(i);
if (childView.getVisibility() != GONE) {
LayoutParams childLayoutParams = (LayoutParams) childView.getLayoutParams();
if (ApiCompatibilityUtils.getMarginStart(childLayoutParams) != startMargin) {
ApiCompatibilityUtils.setMarginStart(childLayoutParams, startMargin);
childView.setLayoutParams(childLayoutParams);
}
if (childView == mLocationBarFrameLayout) {
locationBarLayoutChildIndex = i;
break;
}
int widthMeasureSpec;
int heightMeasureSpec;
if (childLayoutParams.width == LayoutParams.WRAP_CONTENT) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec(
getMeasuredWidth(), MeasureSpec.AT_MOST);
} else if (childLayoutParams.width == LayoutParams.MATCH_PARENT) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec(
getMeasuredWidth(), MeasureSpec.EXACTLY);
} else {
widthMeasureSpec = MeasureSpec.makeMeasureSpec(
childLayoutParams.width, MeasureSpec.EXACTLY);
}
if (childLayoutParams.height == LayoutParams.WRAP_CONTENT) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(
getMeasuredHeight(), MeasureSpec.AT_MOST);
} else if (childLayoutParams.height == LayoutParams.MATCH_PARENT) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(
getMeasuredHeight(), MeasureSpec.EXACTLY);
} else {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(
childLayoutParams.height, MeasureSpec.EXACTLY);
}
childView.measure(widthMeasureSpec, heightMeasureSpec);
startMargin += childView.getMeasuredWidth();
}
}
assert locationBarLayoutChildIndex != -1;
int locationBarLayoutEndMargin = 0;
for (int i = locationBarLayoutChildIndex + 1; i < getChildCount(); i++) {
View childView = getChildAt(i);
if (childView.getVisibility() != GONE) {
locationBarLayoutEndMargin += childView.getMeasuredWidth();
}
}
LayoutParams urlLayoutParams = (LayoutParams) mLocationBarFrameLayout.getLayoutParams();
if (ApiCompatibilityUtils.getMarginEnd(urlLayoutParams) != locationBarLayoutEndMargin) {
ApiCompatibilityUtils.setMarginEnd(urlLayoutParams, locationBarLayoutEndMargin);
mLocationBarFrameLayout.setLayoutParams(urlLayoutParams);
}
// Update left margin of mTitleUrlContainer here to make sure the security icon is always
// placed left of the urlbar.
LayoutParams lp = (LayoutParams) mTitleUrlContainer.getLayoutParams();
if (mSecurityButton.getVisibility() == View.GONE) {
lp.leftMargin = 0;
} else {
lp.leftMargin = mSecurityButton.getMeasuredWidth();
}
mTitleUrlContainer.setLayoutParams(lp);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
updateLayoutParams();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public LocationBar getLocationBar() {
return this;
}
@Override
public boolean onLongClick(View v) {
if (v == mCloseButton) {
return showAccessibilityToast(v, getResources().getString(R.string.close_tab));
} else if (v == mCustomActionButton) {
return showAccessibilityToast(v, mCustomActionButton.getContentDescription());
} else if (v == mTitleUrlContainer) {
ClipboardManager clipboard = (ClipboardManager) getContext()
.getSystemService(Context.CLIPBOARD_SERVICE);
Tab tab = getCurrentTab();
if (tab == null) return false;
String url = tab.getOriginalUrl();
ClipData clip = ClipData.newPlainText("url", url);
clipboard.setPrimaryClip(clip);
Toast.makeText(getContext(), R.string.url_copied, Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
private static String parsePublisherNameFromUrl(String url) {
// TODO(ianwen): Make it generic to parse url from URI path. http://crbug.com/599298
// The url should look like: https://www.google.com/amp/s/www.nyt.com/ampthml/blogs.html
// or https://www.google.com/amp/www.nyt.com/ampthml/blogs.html.
Uri uri = Uri.parse(url);
List<String> segments = uri.getPathSegments();
if (segments.size() >= 3) {
if (segments.get(1).length() > 1) return segments.get(1);
return segments.get(2);
}
return url;
}
// Toolbar and LocationBar calls that are not relevant here.
@Override
public void setToolbarDataProvider(ToolbarDataProvider model) {}
@Override
public void onTextChangedForAutocomplete(boolean canInlineAutocomplete) {}
@Override
public void setUrlFocusChangeListener(UrlFocusChangeListener listener) {}
@Override
public void setUrlBarFocus(boolean shouldBeFocused) {}
@Override
public void showUrlBarCursorWithoutFocusAnimations() {}
@Override
public boolean isUrlBarFocused() {
return false;
}
@Override
public void selectAll() {}
@Override
public void revertChanges() {}
@Override
public long getFirstUrlBarFocusTime() {
return 0;
}
@Override
public void hideSuggestions() {}
@Override
public void updateMicButtonState() {}
@Override
public void onTabLoadingNTP(NewTabPage ntp) {}
@Override
public void setAutocompleteProfile(Profile profile) {}
@Override
public void showAppMenuUpdateBadge() {}
@Override
public boolean isShowingAppMenuUpdateBadge() {
return false;
}
@Override
public void removeAppMenuUpdateBadge(boolean animate) {}
@Override
protected void setAppMenuUpdateBadgeToVisible(boolean animate) {}
@Override
public View getMenuButtonWrapper() {
// This class has no menu button wrapper, so return the menu button instead.
return mMenuButton;
}
}
|
[
"[email protected]"
] | |
031952791ad8dfa1cc8d352164e587431686d0ac
|
28193960505cf7d7a62af39683cb9606e922dde6
|
/app/ITLanBaoProject/src/com/itlanbao/app/fragment/InformationFragment.java
|
5a5061f0828dfccc2b8c033cfcff9f7791a861f4
|
[] |
no_license
|
wujiali/itlanbao
|
da357eb3124e8b4833d3cdaa6c7a3ef070466fce
|
433620893e78d40aa92306278ee65306fa2ec94a
|
refs/heads/master
| 2021-01-10T01:53:02.484811 | 2015-11-13T05:12:45 | 2015-11-13T05:12:45 | 45,890,997 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,388 |
java
|
package com.itlanbao.app.fragment;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.itlanbao.app.R;
import com.itlanbao.app.adapter.FriendAdapter;
import com.itlanbao.applib.pullfreshview.PullRefreshListView;
import com.itlanbao.applib.util.FileUtils;
import com.itlanbao.applib.util.date.DateUtils;
import com.itlanbao.model.FriendDynamic;
import com.itlanbao.model.FriendListInfo;
import com.itlanbao.util.AnalyticalJsonTool;
/**
* @author wjl
* www.itlanbao.com
* Information 资讯部分
*/
public class InformationFragment extends MyFragment implements PullRefreshListView.IXListViewListener{
private View view;
private PullRefreshListView mListView;
private FriendAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_home, container, false);
}
//缓存的rootView需要判断是否已经被加过parent, 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
return view;
}
@Override
protected void onVisible(boolean isInit) {
// TODO Auto-generated method stub
if(isInit){
mListView = (PullRefreshListView) view.findViewById(R.id.pull_listview);
mListView.setPullRefreshEnable(true);
mListView.setPullLoadEnable(false);
mListView.setXListViewListener(this);
mListView.setRefreshTime(DateUtils.getNowDateFormat(DateUtils.DATE_FORMAT_6));
//加载数据
loadFriendListDate();
}
}
/**
* 加载好友动态数据
*/
private void loadFriendListDate(){
new LoadAsynTask().execute();
}
class LoadAsynTask extends AsyncTask<Void, Void, FriendListInfo>{
@Override
protected FriendListInfo doInBackground(Void... params) {
// TODO Auto-generated method stub
//通过获取assets里面数据,解析assets的方法FileUtils.getFromAssets
String friendInfo = FileUtils.getFromAssets(getActivity(), "friendinfo.txt");
//解析工具类直接返回对象
return AnalyticalJsonTool.analyticalFriendList(friendInfo);
}
@Override
protected void onPostExecute(FriendListInfo result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//返回数据刷新页面方法
if(result!=null){
ArrayList<FriendDynamic> mList = result.getFriendList();
if(mList!=null&&mList.size()>0){
if(mAdapter ==null){
mAdapter = new FriendAdapter(getActivity(), mList);
mListView.setAdapter(mAdapter);
}else{
mAdapter.setData(mList);
mAdapter.notifyDataSetChanged();
}
}
}
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//准备异步时处理一些加载框
}
}
@Override
public void onRefresh() {
// TODO Auto-generated method stub
}
@Override
public void onLoadMore() {
// TODO Auto-generated method stub
}
}
|
[
"[email protected]"
] | |
29cdb8cdcd40ded13647abc5369649b80dd53878
|
6083a93dd493e99da48034262f5ac328e848263e
|
/src/main/java/com/jsonservlet/api/FormDataApi.java
|
493ba7c840021a50676fe454d460371c66822b5b
|
[] |
no_license
|
Shivam4819/JasonServlet
|
792bf6550225193988226d93eb2022790ecddc84
|
2487ac1ece8e360101fa435d957266b2e9d796b0
|
refs/heads/master
| 2023-02-26T13:38:57.590198 | 2021-02-06T16:12:14 | 2021-02-06T16:12:14 | 331,204,802 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,519 |
java
|
package com.jsonservlet.api;
import com.google.gson.Gson;
import com.jsonservlet.component.FormDataComponent;
import com.jsonservlet.request.FormDataRequest;
import com.jsonservlet.response.FormDataResponse;
import com.jsonservlet.utils.ReadPostBody;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "FormDataApi", value = "/FormDataApi")
public class FormDataApi extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("in new");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("connection made");
System.out.println("yoyoyoyoyoyoyyo");
PrintWriter out=response.getWriter();
try {
ReadPostBody readPostBody=new ReadPostBody();
String buffer= readPostBody.readBody(request,response);
System.out.println(buffer);
Gson gson=new Gson();
FormDataRequest req= gson.fromJson(buffer, FormDataRequest.class);
FormDataComponent component=new FormDataComponent();
FormDataResponse res=component.formData(req);
out.println(gson.toJson(res));
} catch (Exception e) {
System.out.println("error="+e);
}
}
}
|
[
"[email protected]"
] | |
f014e41355d7138137684ada9dad54d9a6b7c8f6
|
cb6f9ca2db35bb5925f136531c50549b7f80e407
|
/src/GFit-Analysis-Back/src/main/java/com/gfitanalysis/GFitAnalysisBack/repository/RewardRepositoryI.java
|
fb2cb6057177e4cc4477867168ca0130e99b026a
|
[] |
no_license
|
smunozc/GFit-Analysis
|
e67e4fb1bb567980e0c5df3bb3168fc429a69b81
|
2be134a4f1c9b5369bd1950b7d610f47959a8cce
|
refs/heads/main
| 2023-05-31T14:29:50.883907 | 2021-06-18T17:43:58 | 2021-06-18T17:43:58 | 347,695,228 | 0 | 0 | null | 2021-06-13T20:45:45 | 2021-03-14T16:49:33 |
JavaScript
|
UTF-8
|
Java
| false | false | 1,089 |
java
|
package com.gfitanalysis.GFitAnalysisBack.repository;
import java.util.Set;
import org.springframework.data.jpa.repository.JpaRepository;
import com.gfitanalysis.GFitAnalysisBack.model.DataType;
import com.gfitanalysis.GFitAnalysisBack.model.Reward;
import com.gfitanalysis.GFitAnalysisBack.model.UserReward;
public interface RewardRepositoryI extends JpaRepository<Reward, Long>{
/**
* Finds a reward by its name.
* @param name of the reward.
* @return a reward.
*/
public Reward findByName(String name);
/**
* Finds a set of rewards by the user that achieved them.
* @param userRewards userRewards entity that links reward with user.
* @return a set of rewards.
*/
public Set<Reward> findByUserRewards(UserReward userRewards);
/**
* Finds a set of rewards by the dataType and the conditionNum.
* @param dataType is the type of data being checked.
* @param conditionNum is the measure of data being checked.
* @return a set of rewards.
*/
public Set<Reward> findByDataTypeAndConditionNumLessThanEqual(DataType dataType, Integer conditionNum);
}
|
[
"[email protected]"
] | |
f4549fa6b1ed7b7413df255538374ceb28adc0b4
|
47615faf90f578bdad1fde4ef3edae469d995358
|
/practise/SCJP Java 5 專業認證手冊/第二次練習/unit 3/P14.java
|
0b895aef4a194658532a5265b03c3a22f96799c8
|
[] |
no_license
|
hungmans6779/JavaWork-student-practice
|
dca527895e7dbb37aa157784f96658c90cbcf3bd
|
9473ca55c22f30f63fcd1d84c2559b9c609d5829
|
refs/heads/master
| 2020-04-14T01:26:54.467903 | 2018-12-30T04:52:38 | 2018-12-30T04:52:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 422 |
java
|
class Bird
{
{System.out.print("b1 "); }
public Bird()
{ System.out.print("b2 "); }
}
class Raptor extends Bird
{
static {System.out.print("r1 "); }
public Raptor()
{ System.out.print("r2 "); }
{ System.out.print("r3 "); }
static {System.out.print("r4 "); }
}
public class P14 extends Raptor
{
public static void main(String argv[])
{
System.out.print("pre ");
new P14();
System.out.print("hawk ");
}
}
|
[
"[email protected]"
] | |
8a5f31692bdd582b6f16a823d4b4987f8a69de59
|
42524e5952287ae2907235a97e106a72186aeedc
|
/src/com/javarush/test/level12/lesson02/task05/Solution.java
|
34b48bd3da54504607c2494db5586923a633cf3b
|
[] |
no_license
|
BessonovEvgeniy/SmallTaskTraining
|
5682d2a18ef068fb1c022f4192211578ff5b7860
|
e17356620644a84d6e64dc7d3df86cb95a3b07f9
|
refs/heads/master
| 2021-06-10T00:52:26.016101 | 2017-01-04T00:33:13 | 2017-01-04T00:33:13 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,329 |
java
|
package com.javarush.test.level12.lesson02.task05;
/* Или «Корова», или «Кит», или «Собака», или «Неизвестное животное»
Написать метод, который определяет, объект какого класса ему передали, и возвращает результат – одно значение из: «Корова», «Кит», «Собака», «Неизвестное животное».
*/
public class Solution
{
public static void main(String[] args)
{
System.out.println(getObjectType(new Cow()));
System.out.println(getObjectType(new Dog()));
System.out.println(getObjectType(new Whale()));
System.out.println(getObjectType(new Pig()));
}
public static String getObjectType(Object o)
{
if (o instanceof Cow){
return "Корова";
}
else if (o instanceof Whale){
return "Кит";
}
else if (o instanceof Dog){
return "Собака";
}
else {
return "Неизвестное животное";
}
}
public static class Cow
{
}
public static class Dog
{
}
public static class Whale
{
}
public static class Pig
{
}
}
|
[
"[email protected]"
] | |
bf627853b7337fb8fb6e0deeb59f1f248bcbe546
|
d0c946b4485c639553c6b1a16a143856b7ad825c
|
/app/src/main/java/com/project/fanyuzeng/daggerdemo/DaggerApplication.java
|
7e7a9a2b6dac5ec1486d1a4f075fd5449b07eb02
|
[] |
no_license
|
zengfanyu/DaggerDemo
|
5ff28f7106edd0a8f476abd2dd3588dd4e722994
|
87f34dadba3c3c5a3c70dc1fafb655c7fd2c16b5
|
refs/heads/master
| 2021-05-07T08:59:31.242602 | 2018-02-27T08:55:44 | 2018-02-27T08:55:44 | 109,457,687 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 730 |
java
|
package com.project.fanyuzeng.daggerdemo;
import android.app.Application;
import com.project.fanyuzeng.daggerdemo.di.component.DaggerAnimalComponent;
import com.project.fanyuzeng.daggerdemo.di.component.DaggerZoomComponent;
import com.project.fanyuzeng.daggerdemo.di.component.ZoomComponent;
/**
* @author: fanyuzeng on 2018/2/27 16:11
*/
public class DaggerApplication extends Application {
private ZoomComponent mZoomComponent;
@Override
public void onCreate() {
super.onCreate();
mZoomComponent = DaggerZoomComponent.builder().animalComponent(DaggerAnimalComponent.create())
.build();
}
public ZoomComponent getZoomComponent() {
return mZoomComponent;
}
}
|
[
"[email protected]"
] | |
b31d1bc8d77a01f4c46ba8495b08bc2dda9b2232
|
210500e6df8862f9b4531e84d25f925a3bf0fd58
|
/ll-vistaBroker/ll-vistabroker-ejb3/src/main/java/gov/va/med/lom/vistabroker/admin/dao/SurgeryScheduleDao.java
|
e58c3c606bd650339362a6b861d19ffd365d321d
|
[
"Apache-2.0"
] |
permissive
|
merwinn/AVS
|
e1db56e48dc9432e1f73f5043e96749b4799f6fd
|
51f3316586059210d3d8a0a9d1761fed4b9b1826
|
refs/heads/master
| 2020-05-21T09:14:58.372161 | 2014-08-18T18:57:06 | 2014-08-18T18:57:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,861 |
java
|
package gov.va.med.lom.vistabroker.admin.dao;
import gov.va.med.lom.javaUtils.misc.DateUtils;
import gov.va.med.lom.javaUtils.misc.StringUtils;
import gov.va.med.lom.vistabroker.admin.data.SurgeryScheduleItem;
import gov.va.med.lom.vistabroker.dao.BaseDao;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
public class SurgeryScheduleDao extends BaseDao{
private List<SurgeryScheduleItem> items;
public List<SurgeryScheduleItem> fetch(GregorianCalendar date) throws Exception {
setDefaultContext(null);
setDefaultRpcName("ARIL GET SDATA2");
List<String> arr = null;
try{
String start = String.valueOf(DateUtils.formatDate(date.getTime(), DateUtils.ENGLISH_DATE_FORMAT));
Object[] params = {start};
arr = lCall(params);
}catch(Exception e){
return null;
}
items = new ArrayList<SurgeryScheduleItem>();
SurgeryScheduleItem item;
for (String x : arr){
item = new SurgeryScheduleItem();
item.setOperatingRoom(StringUtils.piece(x, 1));
item.setPatientName(StringUtils.piece(x, 2));
item.setLast4(StringUtils.piece(x, 3));
item.setPatientLocation(StringUtils.piece(x, 4));
item.setPrincipleProcedure(StringUtils.piece(x, 5));
item.setOtherProcedure(StringUtils.piece(x, 6));
item.setScheduledStartTime(StringUtils.piece(x, 7));
item.setEstmatedCompletionTime(StringUtils.piece(x, 8));
item.setCaseLength(StringUtils.piece(x, 9));
item.setOperationEndTime(StringUtils.piece(x, 10));
item.setStatus(StringUtils.piece(x, 11));
//StringUtils.piece(x, 12); piece 12 appears to never get set
item.setTimeInOr(StringUtils.piece(x, 13));
item.setInductionCompletionTime(StringUtils.piece(x, 14));
item.setActualBeginTime(StringUtils.piece(x, 15));
item.setActualEndTime(StringUtils.piece(x, 16));
item.setTimeOutOfOr(StringUtils.piece(x, 17));
item.setOrOccupancyTime(StringUtils.piece(x, 18));
item.setSurgeonName(StringUtils.piece(x, 19));
item.setAttendingName(StringUtils.piece(x, 20));
item.setAnesthesiologistName(StringUtils.piece(x, 21));
item.setAnesthesiologistSupervisor(StringUtils.piece(x, 22));
item.setCirculationNurseName(StringUtils.piece(x, 23));
item.setScrubNurseName(StringUtils.piece(x, 24));
item.setIen(StringUtils.piece(x, 25));
item.setConcurrentProcedure(StringUtils.piece(x, 26));
item.setCaseScheduleType(StringUtils.piece(x, 27));
item.setPrincipleProcedureCpt(StringUtils.piece(x, 28));
item.setCaseLengthLeft(StringUtils.piece(x, 29));
// this RPC does not accurately the patient location or fetch the
// patients disposition post procedure so fetch those now
disposition(item);
items.add(item);
}
return items;
}
private void disposition(SurgeryScheduleItem i) {
if (i == null) return;
if (i.getIen() == null || i.getIen().length() == 0) return;
setDefaultContext(null);
setDefaultRpcName("ALSI SURGERY DISPOSITION");
String x;
try{
Object[] params = {i.getIen()};
x = sCall(params);
}catch(Exception e){
return;
}
i.setPatientLocation(StringUtils.piece(x, 2));
i.setPatientDisposition(StringUtils.piece(x, 3));
}
}
|
[
"[email protected]"
] | |
f5b20ba855b39d44b1aa3118a570f6ea04fd8d2c
|
95f41f7e792801b98e9f7f199dc8421033e37469
|
/app/src/main/java/ninja/engineer/GroupMeProjetoFinal/MembersAdapter.java
|
58d79e11a3a58e8b7f9ceac6b10cab71623a38e9
|
[] |
no_license
|
NinjaTheEngineer/GroupMe
|
39f82a7d2b151ee69bfeddd41e181fe1e8872b88
|
9703c17427079544b55c8c9bd43cebbf46d7010f
|
refs/heads/master
| 2020-08-29T14:25:05.602294 | 2019-10-30T17:05:56 | 2019-10-30T17:05:56 | 218,060,481 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,005 |
java
|
package ninja.engineer.GroupMeProjetoFinal;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import java.util.List;
public class MembersAdapter extends RecyclerView.Adapter<MembersAdapter.MyViewHolderTwo> {
private Context context;
private List<Members> members;
private RequestManager glide;
public MembersAdapter(){
}
public MembersAdapter(Context context, List<Members> members) {
this.members = members;
this.context = context;
glide = Glide.with(context);
}
public class MyViewHolderTwo extends RecyclerView.ViewHolder{
TextView tvMember, tvStatus;
ImageView ivMemberPic;
public MyViewHolderTwo(@NonNull View itemView) {
super(itemView);
tvMember = itemView.findViewById(R.id.tvMemberName);
tvStatus = itemView.findViewById(R.id.tvStatus);
ivMemberPic = itemView.findViewById(R.id.ivMemberPic);
}
}
@NonNull
@Override
public MyViewHolderTwo onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.members_layout, viewGroup, false);
return new MyViewHolderTwo(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolderTwo viewHolder, int i) {
Members mem = members.get(i);
viewHolder.tvMember.setText(mem.getName());
viewHolder.ivMemberPic.setImageResource(R.drawable.ic_android);
viewHolder.ivMemberPic.setAdjustViewBounds(true);
viewHolder.ivMemberPic.setCropToPadding(true);
}
@Override
public int getItemCount() {
return members.size();
}
}
|
[
"[email protected]"
] | |
d8c62139592475bbaefe528cf0ed82e60efc93be
|
b83d1b6330213cd99901e4b5a1b327d0c40e5016
|
/JavaSynthesizer/src/view/BDirka.java
|
33284914716d5337883e5d718ea21cffc9a9a3d8
|
[] |
no_license
|
urosradosavljevic/JavaSynthesizer
|
47748a3e033ead16ab5d61a9680ba93f8ca73920
|
52059e121a3e3e0a010317b914cd769bde28bad3
|
refs/heads/master
| 2021-08-28T17:01:31.309679 | 2017-12-12T21:24:33 | 2017-12-12T21:24:33 | 114,022,154 | 0 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 218 |
java
|
package view;
import javafx.scene.control.Button;
public class BDirka extends Button {
public BDirka(){
super();
this.setPrefSize(10, 50);
this.setStyle("-fx-background-color: #ffffff; ");
}
}
|
[
"pozes@DESKTOP-LKTIO2P"
] |
pozes@DESKTOP-LKTIO2P
|
cc9cb4d9bd8714abbc2fa0f5fcb319ad248dc105
|
4a262caae1b36b874ce7e27f52338cbbb53bdb17
|
/MovingImageView/app/src/main/java/com/office/pc25245/movingimageview/MainActivity.java
|
834178a89085ff5a125011a2e47769f9b40d9cf7
|
[] |
no_license
|
zhangrui12138/MovingImageView
|
9cd3776acb4c4ac255d4c62163bb04939f1a29b2
|
24960584c458cd58766de865381f42223cd033ab
|
refs/heads/master
| 2020-04-26T16:48:03.306559 | 2019-03-04T07:12:18 | 2019-03-04T07:12:18 | 173,692,473 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 553 |
java
|
package com.office.pc25245.movingimageview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.office.pc25245.movingimageview.com.john.view.MovingImageView;
public class MainActivity extends AppCompatActivity {
private MovingImageView movingImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// movingImageView = (MovingImageView) findViewById(R.id.moving);
}
}
|
[
"[email protected]"
] | |
5257b92b9a6b868429a1c0bf14f0e8a24f204fab
|
2fc166bb93cdacb34024afacb18bb0722358abb4
|
/Mohammadreza_assignment/app/src/main/java/com/example/mohammadreza_assignment/MainActivity.java
|
8b30632efa6ff9febe89afa72fd92fd77f8be568
|
[] |
no_license
|
rezasaleh/android
|
1c6860328e1884ec680910271117b6fad04855c9
|
19f5685c5575a99e4811407c246b8284da4384e8
|
refs/heads/master
| 2020-06-17T07:50:16.601587 | 2019-07-08T16:51:47 | 2019-07-08T16:51:47 | 195,851,656 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 4,010 |
java
|
package com.example.mohammadreza_assignment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mohammadreza_assignment.model.Person;
import com.example.mohammadreza_assignment.model.Personcollection;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int CODE = 1;
TextView textViewLastName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bind();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
checkPermissions();
}
}
private void bind() {
textViewLastName = findViewById(R.id.textViewLastName);
findViewById(R.id.btnList).setOnClickListener(this);
findViewById(R.id.btnPersonActivity).setOnClickListener(this);
initializeDummyData();
}
private void initializeDummyData() {
Personcollection.getPersonList().add(
new Person("Robert", "Paul", R.drawable.roberto,
"5141112222", "[email protected]", "Montreal")
);
Personcollection.getPersonList().add(
new Person("Joe", "Dao", R.drawable.joe,
"5142223333", "[email protected]", "Montreal")
);
Personcollection.getPersonList().add(
new Person("Smith", "Brandson", R.drawable.smith,
"4383334444", "[email protected]", "Montreal")
);
Personcollection.getPersonList().add(
new Person("Simon", "Doh", R.drawable.doh,
"5144445555", "[email protected]", "Montreal")
);
Personcollection.getPersonList().add(
new Person("Lionel", "karo", R.drawable.karo,
"5146667777", "[email protected]", "Montreal")
);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnList:
showPhoneBookList();
break;
case R.id.btnPersonActivity:
openPersonActivity();
break;
}
}
private void showPhoneBookList() {
Intent intent = new Intent(MainActivity.this, PhoneActivity.class);
startActivity(intent);
}
private void openPersonActivity() {
Intent intent = new Intent(MainActivity.this, PersonActivity.class);
startActivity(intent);
}
private void checkPermissions() {
if (!Permission()) {
String[] perms = new String[]{
Manifest.permission.SEND_SMS,
Manifest.permission.RECEIVE_SMS};
ActivityCompat.requestPermissions(this, perms, CODE);
}
}
private boolean Permission() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS)
== PackageManager.PERMISSION_GRANTED;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == CODE){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
|
[
"[email protected]"
] | |
00e39b4d9b17c0c3e1dea34739e66e041cce4874
|
8890ed186fec09d67ef04e2d0639b4cb11dcd1ea
|
/app/src/androidTest/java/com/example/mecanicoorganizer/ExampleInstrumentedTest.java
|
0e2c83452e640f801162a5fa6ae23598a38b2bde
|
[] |
no_license
|
Daniel6657/Mecanico-Organizer
|
4d0acc782f1c7598b06eaeffcbd150dc0d3a5478
|
b5dad38023b9cccec8e7e5386c72eea1abcb9e68
|
refs/heads/master
| 2023-01-30T05:27:48.247189 | 2020-12-09T15:02:50 | 2020-12-09T15:02:50 | 305,921,569 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 772 |
java
|
package com.example.mecanicoorganizer;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.mecanicoorganizer", appContext.getPackageName());
}
}
|
[
"[email protected]"
] | |
79c4c82f579eea25906f8b6dd574cbbb3306e620
|
5a33440b865e3c5cb9cd7eea412ed1fa42313e2d
|
/spring-autowring-resource-inject/src/org/websparrow/ResourceBean.java
|
2e3f8f49e84ed57b1edde7fdf52a7bd34faee02a
|
[
"Apache-2.0"
] |
permissive
|
tanbinh123/spring-1
|
b83267281dd065939865a2365f2826642f586dc3
|
54669d03bb62946f0cc9d0d0c31be13d98517862
|
refs/heads/master
| 2022-04-22T00:08:04.075867 | 2019-09-30T16:02:13 | 2019-09-30T16:02:13 | 479,906,680 | 1 | 0 | null | 2022-04-10T03:53:17 | 2022-04-10T03:53:16 | null |
UTF-8
|
Java
| false | false | 230 |
java
|
package org.websparrow;
import javax.annotation.Resource;
public class ResourceBean {
@Resource
private State state;
public void display() {
System.out.println("State name is: " + state.getStateName());
}
}
|
[
"Atul@Atul-PC"
] |
Atul@Atul-PC
|
45f5f9521ab8d0f81a8c8643e4c1690659666bd2
|
afd89387f3c1dc7ffc7074f684e59dea019f0a94
|
/Datos.java
|
e7d495120e9141711d8b2ef519c3d5e4c4f07a44
|
[] |
no_license
|
sebas-souto/BoH
|
e6b4c57b932d452b8d8c9899bf39e7cc4c627a03
|
846e96c119ed1170e9c3ee016d8510663b8174df
|
refs/heads/master
| 2020-12-02T08:07:38.648402 | 2017-07-26T15:00:08 | 2017-07-26T15:00:08 | 96,771,086 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 554 |
java
|
package BoH;
public abstract class Datos {
private double importe;
private String Fecha;
public Datos(double importe,String Fecha){
this.Fecha=Fecha;
this.importe=importe;
}
public double getImporte() {
return importe;
}
public void setImporte(double importe) {
this.importe = importe;
}
public String getFecha() {
return Fecha;
}
public void setFecha(String fecha) {
Fecha = fecha;
}
public String toString(){
String imprime= String.format("%-20s%-20s",importe,Fecha);
return imprime;
}
}
|
[
"[email protected]"
] | |
1df26452f3b7a0be3d654344d7431ec8ae770a03
|
d07aabcd5a0a55fe26b0b57fd7be1303b198f7a7
|
/src/main/java/com/example/orderactivities/custom/NumberValueValidator.java
|
68fb69f653cb03229ce0411a1c029e17958665cb
|
[] |
no_license
|
satshi25/order-activities
|
3a9cf628bed47ecf7beb468dfc79f1f406107f8d
|
8fa8b38fe95cb930889384f92eb865eda0f9e582
|
refs/heads/master
| 2022-08-21T02:00:01.566045 | 2020-05-26T06:11:37 | 2020-05-26T06:11:37 | 266,278,735 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 634 |
java
|
package com.example.orderactivities.custom;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NumberValueValidator implements ConstraintValidator<NumberValueConstraint, Integer> {
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
Pattern customPattern = Pattern.compile("^([1-9]+(?:[0-9]*)?)$");
Matcher numberMatcher = customPattern.matcher(String.valueOf(value));
return numberMatcher.matches();
}
}
|
[
"[email protected]"
] | |
2713241f6fdc662c52eefdd9c38d55c8ae7f8738
|
33134bb52837420ca0d61a4e4a12d35e0199cd96
|
/data/src/main/java/com/demo/architect/data/model/offline/AttendanceModel.java
|
5147e6d00c3de9511b555c6b048ef599afea0395
|
[] |
no_license
|
lkimlyen/SP20
|
b5492f09326d074e2e1eb28449f4b5bd270f61c5
|
c10332ad670571469ae08519eefcf75f95a43ec8
|
refs/heads/master
| 2020-08-08T02:34:08.336539 | 2020-04-14T02:52:55 | 2020-04-14T02:52:55 | 213,678,136 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,457 |
java
|
package com.demo.architect.data.model.offline;
import com.demo.architect.utils.view.ConvertUtils;
import java.util.Date;
import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class AttendanceModel extends RealmObject {
@PrimaryKey
private int Id;
private String Number;
private double Latitude;
private double Longitude;
private String PathImage;
private String Type;
private Date DateCreateShort;
private String ImageServerId;
private String DateCreate;
private String LastDateUpdate;
private int CreateBy;
public AttendanceModel() {
}
public AttendanceModel(int id, String number, double latitude, double longitude, String type, Date dateCreateShort, String dateCreate, int createBy) {
this.Id = id;
this.Number = number;
this.Latitude = latitude;
this.Longitude = longitude;
Type = type;
DateCreateShort = dateCreateShort;
this.DateCreate = dateCreate;
this.CreateBy = createBy;
}
public static void addAttendance(Realm realm, AttendanceModel model) {
AttendanceModel attendanceModel = realm.where(AttendanceModel.class).equalTo("Id", model.Id).findFirst();
if (attendanceModel == null) {
realm.copyToRealm(model);
} else {
attendanceModel.setLastDateUpdate(ConvertUtils.getDateTimeCurrent());
attendanceModel.setNumber(attendanceModel.Number + "," + model.Number);
}
}
public static void addImageToAtten(Realm realm, int attendanceId, int imageId, String path) {
AttendanceModel attendanceModel = realm.where(AttendanceModel.class).equalTo("Id", attendanceId).findFirst();
attendanceModel.setPathImage(attendanceModel.PathImage != null && attendanceModel.PathImage.length() > 0 ?
attendanceModel.PathImage + "," + path : path);
attendanceModel.setImageServerId(attendanceModel.ImageServerId != null && attendanceModel.ImageServerId.length() > 0 ?
attendanceModel.ImageServerId + "," + String.valueOf(imageId) : String.valueOf(imageId));
}
public void setId(int id) {
Id = id;
}
public void setNumber(String number) {
Number = number;
}
public void setLatitude(double latitude) {
Latitude = latitude;
}
public void setLongitude(double longitude) {
Longitude = longitude;
}
public void setPathImage(String pathImage) {
PathImage = pathImage;
}
public void setImageServerId(String imageServerId) {
ImageServerId = imageServerId;
}
public void setDateCreate(String dateCreate) {
DateCreate = dateCreate;
}
public void setLastDateUpdate(String lastDateUpdate) {
LastDateUpdate = lastDateUpdate;
}
public void setCreateBy(int createBy) {
CreateBy = createBy;
}
public String getPathImage() {
return PathImage;
}
public static boolean checkUserCheckIn(Realm realm, int teamOutletId) {
Date dateCurrent = ConvertUtils.ConvertStringToShortDate(ConvertUtils.getDateTimeCurrentShort());
AttendanceModel results = realm.where(AttendanceModel.class)
.equalTo("CreateBy", teamOutletId)
.equalTo("Type","IN_TIME")
.equalTo("DateCreateShort", dateCurrent).findFirst();
return results != null;
}
}
|
[
"[email protected]"
] | |
23839d06028993ca0745201a907a8078a936eb32
|
194c43c84273c2e7277b466d3d0d747a97ddd066
|
/app/src/main/java/com/bahaoth/zaihuangye/user/User.java
|
cdfbb4e3dd5e452a624c730965f7ac42f7e8b341
|
[] |
no_license
|
bahaodangpu/ZaiHuangYe
|
a96d16820681eea8ebcc12cf6e219b8d967fa510
|
ac691a5ac5bd1160d3c565c7ec1f36b8ba9995d6
|
refs/heads/master
| 2021-01-10T14:04:07.033797 | 2016-03-04T08:10:22 | 2016-03-04T08:10:22 | 53,116,388 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 551 |
java
|
package com.bahaoth.zaihuangye.user;
import cn.bmob.v3.BmobUser;
/**
* Created by 道谊戎 on 2016/2/27.
*/
public class User extends BmobUser {
private Boolean sex;
private Integer age;
private Boolean ishit;
public boolean getSex() {
return this.sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public boolean ishit() {
return this.ishit;
}
}
|
[
"[email protected]"
] | |
dbd21c8b560c336bedc5da7c4ebf21ddc64ff32a
|
b3322ead8bc4e4c0815c934583ab1cfab81257ca
|
/boot-rest-banner-favicon/src/main/java/com/candidjava/spring/service/UserService.java
|
60579f0fac38cfa1fd7000689ed894a621cc7009
|
[] |
no_license
|
mathanlalsait/spring-boot
|
167a9122e771caaf580685cc8e876d53ef03aab0
|
0baf2af27507e033f177d67762987964316d2385
|
refs/heads/master
| 2023-02-04T15:39:51.077799 | 2023-01-28T04:51:44 | 2023-01-28T04:51:44 | 145,101,926 | 9 | 33 | null | 2020-07-30T13:58:27 | 2018-08-17T09:37:21 |
Java
|
UTF-8
|
Java
| false | false | 402 |
java
|
package com.candidjava.spring.service;
import java.util.List;
import java.util.Optional;
import com.candidjava.spring.bean.User;
public interface UserService {
public void createUser(User user);
public List<User> getUser();
public Optional<User> findById(long id);
public User update(User user, long l);
public void deleteUserById(long id);
public User updatePartially(User user, long id);
}
|
[
"[email protected]"
] | |
198cf934b4fbce7aca314cbd7aa31664c0b2b4f3
|
1505c46cf56edadb45052aaf5916303051f91279
|
/Citter-Chronologer-master/starter/critter/src/main/java/com/udacity/jdnd/course3/critter/service/EmployeeService.java
|
14416823c4699cee176c4ca772195de9a4c97568
|
[
"MIT"
] |
permissive
|
phoenix010/Citter-Chronologer-submission
|
6f401323b6fb06fcd6520e0de418bd84f539e6b4
|
85e6d6c5456d7a3b429e3d4ab34f1c40084b57e5
|
refs/heads/master
| 2023-02-25T20:24:25.661040 | 2021-02-01T03:03:34 | 2021-02-01T03:03:34 | 334,498,032 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 592 |
java
|
package com.udacity.jdnd.course3.critter.service;
import com.udacity.jdnd.course3.critter.entity.Employee;
import com.udacity.jdnd.course3.critter.user.EmployeeSkill;
import java.time.DayOfWeek;
import java.util.List;
import java.util.Set;
public interface EmployeeService {
Boolean isEmployeeInDB(Long Id);
Employee saveEmployee(Employee employee);
Employee getEmployeeById(long employeeId);
List<Employee> getAvailableEmployees(Set<EmployeeSkill> skills, DayOfWeek dayOfWeek);
Long getEmployeeIdbyName(String name);
Employee updateEmployee(Employee employee);
}
|
[
"[email protected]"
] | |
b54491ab35a93b7c87eb7b8f47722e1aca8cf570
|
6ec57c26b14bb518dcff1db661145427eb389858
|
/chap01/src/sec06/ch07/SamsungTv.java
|
875eabbc58b1d32dc39e4d54e54e27107583ff31
|
[] |
no_license
|
jincheol2578/Java
|
1eecdd2abc5a376ef9c931da4837c75ea6488019
|
f8a9c1f9edb8653c752f8e92670d28ded1d18d86
|
refs/heads/main
| 2023-04-07T05:57:57.447853 | 2021-04-22T05:30:00 | 2021-04-22T05:30:00 | 353,582,000 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 294 |
java
|
package sec06.ch07;
public class SamsungTv implements RemoteControl {
private int sound;
@Override
public void volumeUp() {
sound += 2;
}
@Override
public void volumeDown() {
sound -= 2;
}
@Override
public void chkVolume() {
System.out.println("sound : " + sound);
}
}
|
[
"[email protected]"
] | |
5b9662d44af40cf2cb26116981c5599199c7a559
|
1708f73319c7de31d5c25f9050538399625f6271
|
/src/main/java/cn/qnxx/modules/admin/controller/VolumeBrandController.java
|
17da4efac39a2425da1231369a1a6f90036f39c2
|
[] |
no_license
|
weilengdeyu/qnb
|
fc05c7af2e770a82842e5739b895bda1557e1485
|
f10c08e3fd371b123a95c2348ff053b5a773bf94
|
refs/heads/master
| 2022-06-22T20:46:11.359720 | 2019-06-22T03:50:35 | 2019-06-22T03:50:38 | 193,187,726 | 0 | 0 | null | 2022-06-21T01:19:40 | 2019-06-22T03:45:19 |
CSS
|
UTF-8
|
Java
| false | false | 2,486 |
java
|
package cn.qnxx.modules.admin.controller;
import cn.qnxx.modules.admin.entity.SalesTop;
import cn.qnxx.modules.admin.entity.VolumeBrand;
import cn.qnxx.modules.admin.service.ISalesTopService;
import cn.qnxx.modules.admin.service.IVolumeBrandService;
import cn.qnxx.modules.admin.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.*;
/**
* @Classname SalesPmController
* @Description 微冷的雨训练营 www.cnblogs.com/weilengdeyu
* @Date 2019/6/18 14:06
* @Created by Happy-微冷的雨
*/
@RestController
@RequestMapping("/sales")
public class VolumeBrandController {
@Autowired
private IVolumeBrandService volumeBrandService;
@RequestMapping("/findAllVolumeBrandpAjax")
public R findAllVolumeBrandpAjax(String date){
Map<String, Object> datamap=new HashMap<String,Object>();
datamap.put("date",date);
List<VolumeBrand> list=volumeBrandService.selectList(datamap);
//品牌集合
List<String> brandList=new ArrayList<String>();
//销售额集合
List<Integer> numList=new ArrayList<Integer>();
for (VolumeBrand item:list) {
brandList.add(item.getPlatform());
numList.add(item.getCount());
}
Map<String,Object> map=new TreeMap<String,Object>();
map.put("brandlist",brandList); //
map.put("numlist",numList); //
return R.success("sales",map);
}
//获取所有的品牌名称
@RequestMapping("/getDataByBrand")
public R getDataByBrand(String brand){
Map<String, Object> datamap=new HashMap<String,Object>();
datamap.put("commodity",brand);
List<VolumeBrand> list=volumeBrandService.selectList(datamap);
//品牌集合
List<String> brandList=new ArrayList<String>();
for (VolumeBrand item:list) {
brandList.add(item.getCommodity());
}
Map<String,Object> map=new TreeMap<String,Object>();
map.put("brandlist2",brandList); //
return R.success("sales",map);
}
@RequestMapping("/getAllBrand")
public R getAllBrand(){
List<VolumeBrand> list=volumeBrandService.selectAll(null);
Map<String,Object> map=new TreeMap<String,Object>();
map.put("list",list); //
return R.success("sales",map);
}
}
|
[
"[email protected]"
] | |
cb4edb05cda5b4f9a535e864a6e8f104151c7c27
|
985b11c6171f2d92fed1ea4c85a012ec2b436aed
|
/ClinicAdmin/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/constraint/R.java
|
d169f60f557c98629b07742d405633430b488be0
|
[] |
no_license
|
mjunaidharis/AppiumProject
|
8d739865d4741c0b2ff63658ac1b4166c887a85b
|
857641eebbae0aebf43cfcdae087229d18f723bb
|
refs/heads/master
| 2020-04-14T05:59:52.890551 | 2018-12-31T14:21:49 | 2018-12-31T14:21:49 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 19,112 |
java
|
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.constraint;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int barrierAllowsGoneWidgets = 0x7f040038;
public static final int barrierDirection = 0x7f040039;
public static final int chainUseRtl = 0x7f040057;
public static final int constraintSet = 0x7f04006e;
public static final int constraint_referenced_ids = 0x7f04006f;
public static final int content = 0x7f040070;
public static final int emptyVisibility = 0x7f040090;
public static final int layout_constrainedHeight = 0x7f0400d4;
public static final int layout_constrainedWidth = 0x7f0400d5;
public static final int layout_constraintBaseline_creator = 0x7f0400d6;
public static final int layout_constraintBaseline_toBaselineOf = 0x7f0400d7;
public static final int layout_constraintBottom_creator = 0x7f0400d8;
public static final int layout_constraintBottom_toBottomOf = 0x7f0400d9;
public static final int layout_constraintBottom_toTopOf = 0x7f0400da;
public static final int layout_constraintCircle = 0x7f0400db;
public static final int layout_constraintCircleAngle = 0x7f0400dc;
public static final int layout_constraintCircleRadius = 0x7f0400dd;
public static final int layout_constraintDimensionRatio = 0x7f0400de;
public static final int layout_constraintEnd_toEndOf = 0x7f0400df;
public static final int layout_constraintEnd_toStartOf = 0x7f0400e0;
public static final int layout_constraintGuide_begin = 0x7f0400e1;
public static final int layout_constraintGuide_end = 0x7f0400e2;
public static final int layout_constraintGuide_percent = 0x7f0400e3;
public static final int layout_constraintHeight_default = 0x7f0400e4;
public static final int layout_constraintHeight_max = 0x7f0400e5;
public static final int layout_constraintHeight_min = 0x7f0400e6;
public static final int layout_constraintHeight_percent = 0x7f0400e7;
public static final int layout_constraintHorizontal_bias = 0x7f0400e8;
public static final int layout_constraintHorizontal_chainStyle = 0x7f0400e9;
public static final int layout_constraintHorizontal_weight = 0x7f0400ea;
public static final int layout_constraintLeft_creator = 0x7f0400eb;
public static final int layout_constraintLeft_toLeftOf = 0x7f0400ec;
public static final int layout_constraintLeft_toRightOf = 0x7f0400ed;
public static final int layout_constraintRight_creator = 0x7f0400ee;
public static final int layout_constraintRight_toLeftOf = 0x7f0400ef;
public static final int layout_constraintRight_toRightOf = 0x7f0400f0;
public static final int layout_constraintStart_toEndOf = 0x7f0400f1;
public static final int layout_constraintStart_toStartOf = 0x7f0400f2;
public static final int layout_constraintTop_creator = 0x7f0400f3;
public static final int layout_constraintTop_toBottomOf = 0x7f0400f4;
public static final int layout_constraintTop_toTopOf = 0x7f0400f5;
public static final int layout_constraintVertical_bias = 0x7f0400f6;
public static final int layout_constraintVertical_chainStyle = 0x7f0400f7;
public static final int layout_constraintVertical_weight = 0x7f0400f8;
public static final int layout_constraintWidth_default = 0x7f0400f9;
public static final int layout_constraintWidth_max = 0x7f0400fa;
public static final int layout_constraintWidth_min = 0x7f0400fb;
public static final int layout_constraintWidth_percent = 0x7f0400fc;
public static final int layout_editor_absoluteX = 0x7f0400fe;
public static final int layout_editor_absoluteY = 0x7f0400ff;
public static final int layout_goneMarginBottom = 0x7f040100;
public static final int layout_goneMarginEnd = 0x7f040101;
public static final int layout_goneMarginLeft = 0x7f040102;
public static final int layout_goneMarginRight = 0x7f040103;
public static final int layout_goneMarginStart = 0x7f040104;
public static final int layout_goneMarginTop = 0x7f040105;
public static final int layout_optimizationLevel = 0x7f040108;
}
public static final class id {
private id() {}
public static final int barrier = 0x7f09002b;
public static final int bottom = 0x7f09002e;
public static final int chains = 0x7f090034;
public static final int dimensions = 0x7f090055;
public static final int direct = 0x7f090056;
public static final int end = 0x7f090066;
public static final int gone = 0x7f09007a;
public static final int invisible = 0x7f090085;
public static final int left = 0x7f09008c;
public static final int none = 0x7f0900ac;
public static final int packed = 0x7f0900b1;
public static final int parent = 0x7f0900b3;
public static final int percent = 0x7f0900b8;
public static final int right = 0x7f0900d1;
public static final int spread = 0x7f090100;
public static final int spread_inside = 0x7f090101;
public static final int standard = 0x7f090105;
public static final int start = 0x7f090106;
public static final int top = 0x7f09011f;
public static final int wrap = 0x7f090134;
}
public static final class styleable {
private styleable() {}
public static final int[] ConstraintLayout_Layout = { 0x10100c4, 0x101011f, 0x1010120, 0x101013f, 0x1010140, 0x7f040038, 0x7f040039, 0x7f040057, 0x7f04006e, 0x7f04006f, 0x7f0400d4, 0x7f0400d5, 0x7f0400d6, 0x7f0400d7, 0x7f0400d8, 0x7f0400d9, 0x7f0400da, 0x7f0400db, 0x7f0400dc, 0x7f0400dd, 0x7f0400de, 0x7f0400df, 0x7f0400e0, 0x7f0400e1, 0x7f0400e2, 0x7f0400e3, 0x7f0400e4, 0x7f0400e5, 0x7f0400e6, 0x7f0400e7, 0x7f0400e8, 0x7f0400e9, 0x7f0400ea, 0x7f0400eb, 0x7f0400ec, 0x7f0400ed, 0x7f0400ee, 0x7f0400ef, 0x7f0400f0, 0x7f0400f1, 0x7f0400f2, 0x7f0400f3, 0x7f0400f4, 0x7f0400f5, 0x7f0400f6, 0x7f0400f7, 0x7f0400f8, 0x7f0400f9, 0x7f0400fa, 0x7f0400fb, 0x7f0400fc, 0x7f0400fe, 0x7f0400ff, 0x7f040100, 0x7f040101, 0x7f040102, 0x7f040103, 0x7f040104, 0x7f040105, 0x7f040108 };
public static final int ConstraintLayout_Layout_android_orientation = 0;
public static final int ConstraintLayout_Layout_android_maxWidth = 1;
public static final int ConstraintLayout_Layout_android_maxHeight = 2;
public static final int ConstraintLayout_Layout_android_minWidth = 3;
public static final int ConstraintLayout_Layout_android_minHeight = 4;
public static final int ConstraintLayout_Layout_barrierAllowsGoneWidgets = 5;
public static final int ConstraintLayout_Layout_barrierDirection = 6;
public static final int ConstraintLayout_Layout_chainUseRtl = 7;
public static final int ConstraintLayout_Layout_constraintSet = 8;
public static final int ConstraintLayout_Layout_constraint_referenced_ids = 9;
public static final int ConstraintLayout_Layout_layout_constrainedHeight = 10;
public static final int ConstraintLayout_Layout_layout_constrainedWidth = 11;
public static final int ConstraintLayout_Layout_layout_constraintBaseline_creator = 12;
public static final int ConstraintLayout_Layout_layout_constraintBaseline_toBaselineOf = 13;
public static final int ConstraintLayout_Layout_layout_constraintBottom_creator = 14;
public static final int ConstraintLayout_Layout_layout_constraintBottom_toBottomOf = 15;
public static final int ConstraintLayout_Layout_layout_constraintBottom_toTopOf = 16;
public static final int ConstraintLayout_Layout_layout_constraintCircle = 17;
public static final int ConstraintLayout_Layout_layout_constraintCircleAngle = 18;
public static final int ConstraintLayout_Layout_layout_constraintCircleRadius = 19;
public static final int ConstraintLayout_Layout_layout_constraintDimensionRatio = 20;
public static final int ConstraintLayout_Layout_layout_constraintEnd_toEndOf = 21;
public static final int ConstraintLayout_Layout_layout_constraintEnd_toStartOf = 22;
public static final int ConstraintLayout_Layout_layout_constraintGuide_begin = 23;
public static final int ConstraintLayout_Layout_layout_constraintGuide_end = 24;
public static final int ConstraintLayout_Layout_layout_constraintGuide_percent = 25;
public static final int ConstraintLayout_Layout_layout_constraintHeight_default = 26;
public static final int ConstraintLayout_Layout_layout_constraintHeight_max = 27;
public static final int ConstraintLayout_Layout_layout_constraintHeight_min = 28;
public static final int ConstraintLayout_Layout_layout_constraintHeight_percent = 29;
public static final int ConstraintLayout_Layout_layout_constraintHorizontal_bias = 30;
public static final int ConstraintLayout_Layout_layout_constraintHorizontal_chainStyle = 31;
public static final int ConstraintLayout_Layout_layout_constraintHorizontal_weight = 32;
public static final int ConstraintLayout_Layout_layout_constraintLeft_creator = 33;
public static final int ConstraintLayout_Layout_layout_constraintLeft_toLeftOf = 34;
public static final int ConstraintLayout_Layout_layout_constraintLeft_toRightOf = 35;
public static final int ConstraintLayout_Layout_layout_constraintRight_creator = 36;
public static final int ConstraintLayout_Layout_layout_constraintRight_toLeftOf = 37;
public static final int ConstraintLayout_Layout_layout_constraintRight_toRightOf = 38;
public static final int ConstraintLayout_Layout_layout_constraintStart_toEndOf = 39;
public static final int ConstraintLayout_Layout_layout_constraintStart_toStartOf = 40;
public static final int ConstraintLayout_Layout_layout_constraintTop_creator = 41;
public static final int ConstraintLayout_Layout_layout_constraintTop_toBottomOf = 42;
public static final int ConstraintLayout_Layout_layout_constraintTop_toTopOf = 43;
public static final int ConstraintLayout_Layout_layout_constraintVertical_bias = 44;
public static final int ConstraintLayout_Layout_layout_constraintVertical_chainStyle = 45;
public static final int ConstraintLayout_Layout_layout_constraintVertical_weight = 46;
public static final int ConstraintLayout_Layout_layout_constraintWidth_default = 47;
public static final int ConstraintLayout_Layout_layout_constraintWidth_max = 48;
public static final int ConstraintLayout_Layout_layout_constraintWidth_min = 49;
public static final int ConstraintLayout_Layout_layout_constraintWidth_percent = 50;
public static final int ConstraintLayout_Layout_layout_editor_absoluteX = 51;
public static final int ConstraintLayout_Layout_layout_editor_absoluteY = 52;
public static final int ConstraintLayout_Layout_layout_goneMarginBottom = 53;
public static final int ConstraintLayout_Layout_layout_goneMarginEnd = 54;
public static final int ConstraintLayout_Layout_layout_goneMarginLeft = 55;
public static final int ConstraintLayout_Layout_layout_goneMarginRight = 56;
public static final int ConstraintLayout_Layout_layout_goneMarginStart = 57;
public static final int ConstraintLayout_Layout_layout_goneMarginTop = 58;
public static final int ConstraintLayout_Layout_layout_optimizationLevel = 59;
public static final int[] ConstraintLayout_placeholder = { 0x7f040070, 0x7f040090 };
public static final int ConstraintLayout_placeholder_content = 0;
public static final int ConstraintLayout_placeholder_emptyVisibility = 1;
public static final int[] ConstraintSet = { 0x10100c4, 0x10100d0, 0x10100dc, 0x10100f4, 0x10100f5, 0x10100f7, 0x10100f8, 0x10100f9, 0x10100fa, 0x101031f, 0x1010320, 0x1010321, 0x1010322, 0x1010323, 0x1010324, 0x1010325, 0x1010326, 0x1010327, 0x1010328, 0x10103b5, 0x10103b6, 0x10103fa, 0x1010440, 0x7f0400d4, 0x7f0400d5, 0x7f0400d6, 0x7f0400d7, 0x7f0400d8, 0x7f0400d9, 0x7f0400da, 0x7f0400db, 0x7f0400dc, 0x7f0400dd, 0x7f0400de, 0x7f0400df, 0x7f0400e0, 0x7f0400e1, 0x7f0400e2, 0x7f0400e3, 0x7f0400e4, 0x7f0400e5, 0x7f0400e6, 0x7f0400e7, 0x7f0400e8, 0x7f0400e9, 0x7f0400ea, 0x7f0400eb, 0x7f0400ec, 0x7f0400ed, 0x7f0400ee, 0x7f0400ef, 0x7f0400f0, 0x7f0400f1, 0x7f0400f2, 0x7f0400f3, 0x7f0400f4, 0x7f0400f5, 0x7f0400f6, 0x7f0400f7, 0x7f0400f8, 0x7f0400f9, 0x7f0400fa, 0x7f0400fb, 0x7f0400fc, 0x7f0400fe, 0x7f0400ff, 0x7f040100, 0x7f040101, 0x7f040102, 0x7f040103, 0x7f040104, 0x7f040105 };
public static final int ConstraintSet_android_orientation = 0;
public static final int ConstraintSet_android_id = 1;
public static final int ConstraintSet_android_visibility = 2;
public static final int ConstraintSet_android_layout_width = 3;
public static final int ConstraintSet_android_layout_height = 4;
public static final int ConstraintSet_android_layout_marginLeft = 5;
public static final int ConstraintSet_android_layout_marginTop = 6;
public static final int ConstraintSet_android_layout_marginRight = 7;
public static final int ConstraintSet_android_layout_marginBottom = 8;
public static final int ConstraintSet_android_alpha = 9;
public static final int ConstraintSet_android_transformPivotX = 10;
public static final int ConstraintSet_android_transformPivotY = 11;
public static final int ConstraintSet_android_translationX = 12;
public static final int ConstraintSet_android_translationY = 13;
public static final int ConstraintSet_android_scaleX = 14;
public static final int ConstraintSet_android_scaleY = 15;
public static final int ConstraintSet_android_rotation = 16;
public static final int ConstraintSet_android_rotationX = 17;
public static final int ConstraintSet_android_rotationY = 18;
public static final int ConstraintSet_android_layout_marginStart = 19;
public static final int ConstraintSet_android_layout_marginEnd = 20;
public static final int ConstraintSet_android_translationZ = 21;
public static final int ConstraintSet_android_elevation = 22;
public static final int ConstraintSet_layout_constrainedHeight = 23;
public static final int ConstraintSet_layout_constrainedWidth = 24;
public static final int ConstraintSet_layout_constraintBaseline_creator = 25;
public static final int ConstraintSet_layout_constraintBaseline_toBaselineOf = 26;
public static final int ConstraintSet_layout_constraintBottom_creator = 27;
public static final int ConstraintSet_layout_constraintBottom_toBottomOf = 28;
public static final int ConstraintSet_layout_constraintBottom_toTopOf = 29;
public static final int ConstraintSet_layout_constraintCircle = 30;
public static final int ConstraintSet_layout_constraintCircleAngle = 31;
public static final int ConstraintSet_layout_constraintCircleRadius = 32;
public static final int ConstraintSet_layout_constraintDimensionRatio = 33;
public static final int ConstraintSet_layout_constraintEnd_toEndOf = 34;
public static final int ConstraintSet_layout_constraintEnd_toStartOf = 35;
public static final int ConstraintSet_layout_constraintGuide_begin = 36;
public static final int ConstraintSet_layout_constraintGuide_end = 37;
public static final int ConstraintSet_layout_constraintGuide_percent = 38;
public static final int ConstraintSet_layout_constraintHeight_default = 39;
public static final int ConstraintSet_layout_constraintHeight_max = 40;
public static final int ConstraintSet_layout_constraintHeight_min = 41;
public static final int ConstraintSet_layout_constraintHeight_percent = 42;
public static final int ConstraintSet_layout_constraintHorizontal_bias = 43;
public static final int ConstraintSet_layout_constraintHorizontal_chainStyle = 44;
public static final int ConstraintSet_layout_constraintHorizontal_weight = 45;
public static final int ConstraintSet_layout_constraintLeft_creator = 46;
public static final int ConstraintSet_layout_constraintLeft_toLeftOf = 47;
public static final int ConstraintSet_layout_constraintLeft_toRightOf = 48;
public static final int ConstraintSet_layout_constraintRight_creator = 49;
public static final int ConstraintSet_layout_constraintRight_toLeftOf = 50;
public static final int ConstraintSet_layout_constraintRight_toRightOf = 51;
public static final int ConstraintSet_layout_constraintStart_toEndOf = 52;
public static final int ConstraintSet_layout_constraintStart_toStartOf = 53;
public static final int ConstraintSet_layout_constraintTop_creator = 54;
public static final int ConstraintSet_layout_constraintTop_toBottomOf = 55;
public static final int ConstraintSet_layout_constraintTop_toTopOf = 56;
public static final int ConstraintSet_layout_constraintVertical_bias = 57;
public static final int ConstraintSet_layout_constraintVertical_chainStyle = 58;
public static final int ConstraintSet_layout_constraintVertical_weight = 59;
public static final int ConstraintSet_layout_constraintWidth_default = 60;
public static final int ConstraintSet_layout_constraintWidth_max = 61;
public static final int ConstraintSet_layout_constraintWidth_min = 62;
public static final int ConstraintSet_layout_constraintWidth_percent = 63;
public static final int ConstraintSet_layout_editor_absoluteX = 64;
public static final int ConstraintSet_layout_editor_absoluteY = 65;
public static final int ConstraintSet_layout_goneMarginBottom = 66;
public static final int ConstraintSet_layout_goneMarginEnd = 67;
public static final int ConstraintSet_layout_goneMarginLeft = 68;
public static final int ConstraintSet_layout_goneMarginRight = 69;
public static final int ConstraintSet_layout_goneMarginStart = 70;
public static final int ConstraintSet_layout_goneMarginTop = 71;
public static final int[] LinearConstraintLayout = { 0x10100c4 };
public static final int LinearConstraintLayout_android_orientation = 0;
}
}
|
[
"[email protected]"
] | |
f31d5805a41e5b3935df944937488873b2c1a12a
|
e89dc01c95b8b45404f971517c2789fd21657749
|
/src/main/java/com/alipay/api/domain/InterTradeContractPartner.java
|
4d1fcd5f40415578c8535bae3e50304912aa2561
|
[
"Apache-2.0"
] |
permissive
|
guoweiecust/alipay-sdk-java-all
|
3370466eec70c5422c8916c62a99b1e8f37a3f46
|
bb2b0dc8208a7a0ab8521a52f8a5e1fcef61aeb9
|
refs/heads/master
| 2023-05-05T07:06:47.823723 | 2021-05-25T15:26:21 | 2021-05-25T15:26:21 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 899 |
java
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 合约参与方
*
* @author auto create
* @since 1.0, 2019-12-20 17:58:55
*/
public class InterTradeContractPartner extends AlipayObject {
private static final long serialVersionUID = 3558487582623738867L;
/**
* 参与方类型(包括:OU、NAME、PID、CID、UID、
MID)
*/
@ApiField("type")
private String type;
/**
* 根据参与类型来设置具体的值(如:type=NAME, value=网商银行;type=PID, value=2088xxxxxxxx)
*/
@ApiField("value")
private String value;
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
|
[
"[email protected]"
] | |
e550ef0505d34ffd6074e76a2893169304f2d8fe
|
25b103c9955a694567eaf119fe95ed997c076b09
|
/ApiRESTSpringBoot/src/main/java/br/com/renatoschlogel/api/Application.java
|
60dd7b87b635e1fdb03a057dfddd9c86f5105594
|
[
"MIT"
] |
permissive
|
renatoschlogel/DesignAPIsRestFulSpringBootTDD
|
14e7b0de8d376e514f9dce44476b7037e6182a3e
|
eccc85489d2e2068e1c7fea7673e19408d28ef1f
|
refs/heads/main
| 2023-06-22T02:10:44.207734 | 2021-07-23T03:50:37 | 2021-07-23T03:50:37 | 320,957,201 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 308 |
java
|
package br.com.renatoschlogel.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
[
"[email protected]"
] | |
62331fe1a713bb9b53bb32e49cf818b65d90d36a
|
f1a3a86fb39ed532cd969efc92c51d2ae06b7736
|
/my/test.java
|
7e31aaf89a8be2707136edcecb84d5dfc661e9e2
|
[
"Apache-2.0"
] |
permissive
|
lokies/HelloWorld
|
f9011f7b0b17f09639a5d58373b07b1480184c47
|
208a25f9c0f5d67efc67b499f5efb7df96e43a66
|
refs/heads/master
| 2021-01-10T07:35:30.589786 | 2016-01-11T10:00:53 | 2016-01-11T10:00:53 | 49,189,033 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 91 |
java
|
public static void main(String[] args){
System.out.println("测试修改java文件");
}
|
[
"[email protected]"
] | |
208c6ac38c0e685669e1f9a1779b92dbe565855c
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/12/12_dbdef6d3858b5ce2fec3bd97d76064f7f960cdda/Main/12_dbdef6d3858b5ce2fec3bd97d76064f7f960cdda_Main_s.java
|
c0917a3b9d05c27b98e6a1e28dbda8650387130a
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null |
UTF-8
|
Java
| false | false | 18,469 |
java
|
// License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import org.openstreetmap.josm.actions.SaveAction;
import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
import org.openstreetmap.josm.actions.mapmode.MapMode;
import org.openstreetmap.josm.actions.search.SearchAction;
import org.openstreetmap.josm.data.Bounds;
import org.openstreetmap.josm.data.Preferences;
import org.openstreetmap.josm.data.UndoRedoHandler;
import org.openstreetmap.josm.data.osm.DataSet;
import org.openstreetmap.josm.data.projection.Mercator;
import org.openstreetmap.josm.data.projection.Projection;
import org.openstreetmap.josm.gui.ExtendedDialog;
import org.openstreetmap.josm.gui.GettingStarted;
import org.openstreetmap.josm.gui.MainMenu;
import org.openstreetmap.josm.gui.MapFrame;
import org.openstreetmap.josm.gui.PleaseWaitDialog;
import org.openstreetmap.josm.gui.SplashScreen;
import org.openstreetmap.josm.gui.download.DownloadDialog.DownloadTask;
import org.openstreetmap.josm.gui.layer.Layer;
import org.openstreetmap.josm.gui.layer.OsmDataLayer;
import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
import org.openstreetmap.josm.gui.preferences.MapPaintPreference;
import org.openstreetmap.josm.gui.preferences.TaggingPresetPreference;
import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
import org.openstreetmap.josm.plugins.PluginHandler;
import org.openstreetmap.josm.tools.ImageProvider;
import org.openstreetmap.josm.tools.OsmUrlToBounds;
import org.openstreetmap.josm.tools.PlatformHook;
import org.openstreetmap.josm.tools.PlatformHookOsx;
import org.openstreetmap.josm.tools.PlatformHookUnixoid;
import org.openstreetmap.josm.tools.PlatformHookWindows;
import org.openstreetmap.josm.tools.Shortcut;
abstract public class Main {
/**
* Global parent component for all dialogs and message boxes
*/
public static Component parent;
/**
* Global application.
*/
public static Main main;
/**
* The worker thread slave. This is for executing all long and intensive
* calculations. The executed runnables are guaranteed to be executed separately
* and sequential.
*/
public final static ExecutorService worker = Executors.newSingleThreadExecutor();
/**
* Global application preferences
*/
public static Preferences pref = new Preferences();
/**
* The global dataset.
*/
public static DataSet ds = new DataSet();
/**
* The global paste buffer.
*/
public static DataSet pasteBuffer = new DataSet();
public static Layer pasteSource;
/**
* The projection method used.
*/
public static Projection proj;
/**
* The MapFrame. Use setMapFrame to set or clear it.
*/
public static MapFrame map;
/**
* The dialog that gets displayed during background task execution.
*/
public static PleaseWaitDialog pleaseWaitDlg;
/**
* True, when in applet mode
*/
public static boolean applet = false;
/**
* The toolbar preference control to register new actions.
*/
public static ToolbarPreferences toolbar;
public UndoRedoHandler undoRedo = new UndoRedoHandler();
/**
* The main menu bar at top of screen.
*/
public final MainMenu menu;
/**
* The MOTD Layer.
*/
private GettingStarted gettingStarted=new GettingStarted();
/**
* Print a debug message if debugging is on.
*/
static public int debug_level = 1;
static public final void debug(String msg) {
if (debug_level <= 0)
return;
System.out.println(msg);
}
/**
* Platform specific code goes in here.
* Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
* So if you need to hook into those early ones, split your class and send the one with the early hooks
* to the JOSM team for inclusion.
*/
public static PlatformHook platform;
/**
* Set or clear (if passed <code>null</code>) the map.
*/
public final void setMapFrame(final MapFrame map) {
MapFrame old = Main.map;
Main.map = map;
panel.setVisible(false);
panel.removeAll();
if (map != null)
map.fillPanel(panel);
else {
old.destroy();
panel.add(gettingStarted, BorderLayout.CENTER);
}
panel.setVisible(true);
redoUndoListener.commandChanged(0,0);
PluginHandler.setMapFrame(old, map);
}
/**
* Remove the specified layer from the map. If it is the last layer,
* remove the map as well.
*/
public final void removeLayer(final Layer layer) {
map.mapView.removeLayer(layer);
if (layer instanceof OsmDataLayer)
ds = new DataSet();
if (map.mapView.getAllLayers().isEmpty())
setMapFrame(null);
}
public Main() {
this(null);
}
public Main(SplashScreen splash) {
main = this;
// platform = determinePlatformHook();
platform.startupHook();
contentPane.add(panel, BorderLayout.CENTER);
panel.add(gettingStarted, BorderLayout.CENTER);
if(splash != null) splash.setStatus(tr("Creating main GUI"));
menu = new MainMenu();
undoRedo.listenerCommands.add(redoUndoListener);
// creating toolbar
contentPane.add(toolbar.control, BorderLayout.NORTH);
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(Shortcut.registerShortcut("system:help", tr("Help"),
KeyEvent.VK_F1, Shortcut.GROUP_DIRECT).getKeyStroke(), "Help");
contentPane.getActionMap().put("Help", menu.help);
TaggingPresetPreference.initialize();
MapPaintPreference.initialize();
toolbar.refreshToolbarControl();
toolbar.control.updateUI();
contentPane.updateUI();
}
/**
* Add a new layer to the map. If no map exists, create one.
*/
public final void addLayer(final Layer layer) {
if (map == null) {
final MapFrame mapFrame = new MapFrame();
setMapFrame(mapFrame);
mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction());
mapFrame.setVisible(true);
mapFrame.setVisibleDialogs();
}
map.mapView.addLayer(layer);
}
/**
* @return The edit osm layer. If none exists, it will be created.
*/
public final OsmDataLayer editLayer() {
if (map == null || map.mapView.editLayer == null)
menu.newAction.actionPerformed(null);
return map.mapView.editLayer;
}
/**
* Use this to register shortcuts to
*/
public static final JPanel contentPane = new JPanel(new BorderLayout());
///////////////////////////////////////////////////////////////////////////
// Implementation part
///////////////////////////////////////////////////////////////////////////
public static JPanel panel = new JPanel(new BorderLayout());
protected static Rectangle bounds;
private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
public void commandChanged(final int queueSize, final int redoSize) {
menu.undo.setEnabled(queueSize > 0);
menu.redo.setEnabled(redoSize > 0);
}
};
/**
* Should be called before the main constructor to setup some parameter stuff
* @param args The parsed argument list.
*/
public static void preConstructorInit(Map<String, Collection<String>> args) {
try {
Main.proj = (Projection)Class.forName(Main.pref.get("projection")).newInstance();
} catch (final Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, tr("The projection could not be read from preferences. Using Mercartor"));
Main.proj = new Mercator();
}
try {
try {
String laf = Main.pref.get("laf");
if(laf != null && laf.length() > 0)
UIManager.setLookAndFeel(laf);
}
catch (final javax.swing.UnsupportedLookAndFeelException e) {
System.out.println("Look and Feel not supported: " + Main.pref.get("laf"));
}
toolbar = new ToolbarPreferences();
contentPane.updateUI();
panel.updateUI();
} catch (final Exception e) {
e.printStackTrace();
}
UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
String geometry = Main.pref.get("gui.geometry");
if (args.containsKey("geometry")) {
geometry = args.get("geometry").iterator().next();
}
if (geometry.length() != 0) {
final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(geometry);
if (m.matches()) {
int w = Integer.valueOf(m.group(1));
int h = Integer.valueOf(m.group(2));
int x = 0, y = 0;
if (m.group(3) != null) {
x = Integer.valueOf(m.group(5));
y = Integer.valueOf(m.group(7));
if (m.group(4).equals("-"))
x = screenDimension.width - x - w;
if (m.group(6).equals("-"))
y = screenDimension.height - y - h;
}
bounds = new Rectangle(x,y,w,h);
if(!Main.pref.get("gui.geometry").equals(geometry)) {
// remember this geometry
Main.pref.put("gui.geometry", geometry);
}
} else {
System.out.println("Ignoring malformed geometry: "+geometry);
}
}
if (bounds == null)
bounds = !args.containsKey("no-maximize") ? new Rectangle(0,0,screenDimension.width,screenDimension.height) : new Rectangle(1000,740);
// preinitialize a wait dialog for all early downloads (e.g. via command line)
pleaseWaitDlg = new PleaseWaitDialog(null);
}
public void postConstructorProcessCmdLine(Map<String, Collection<String>> args) {
// initialize the pleaseWaitDialog with the application as parent to handle focus stuff
pleaseWaitDlg = new PleaseWaitDialog(parent);
if (args.containsKey("download"))
for (String s : args.get("download"))
downloadFromParamString(false, s);
if (args.containsKey("downloadgps"))
for (String s : args.get("downloadgps"))
downloadFromParamString(true, s);
if (args.containsKey("selection"))
for (String s : args.get("selection"))
SearchAction.search(s, SearchAction.SearchMode.add, false, false);
}
public static boolean breakBecauseUnsavedChanges() {
Shortcut.savePrefs();
if (map != null) {
boolean modified = false;
boolean uploadedModified = false;
for (final Layer l : map.mapView.getAllLayers()) {
if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
modified = true;
uploadedModified = ((OsmDataLayer)l).uploadedModified;
break;
}
}
if (modified) {
final String msg = uploadedModified ? "\n"
+tr("Hint: Some changes came from uploading new data to the server.") : "";
int result = new ExtendedDialog(parent, tr("Unsaved Changes"),
new javax.swing.JLabel(tr("There are unsaved changes. Discard the changes and continue?")+msg),
new String[] {tr("Save and Exit"), tr("Discard and Exit"), tr("Cancel")},
new String[] {"save.png", "exit.png", "cancel.png"}).getValue();
// Save before exiting
if(result == 1) {
Boolean savefailed = false;
for (final Layer l : map.mapView.getAllLayers()) {
if (l instanceof OsmDataLayer && ((OsmDataLayer)l).isModified()) {
SaveAction save = new SaveAction(l);
if(!save.doSave())
savefailed = true;
}
}
return savefailed;
}
else if(result != 2) // Cancel exiting unless the 2nd button was clicked
return true;
}
}
return false;
}
private static void downloadFromParamString(final boolean rawGps, String s) {
if (s.startsWith("http:")) {
final Bounds b = OsmUrlToBounds.parse(s);
if (b == null)
JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed URL: \"{0}\"", s));
else {
//DownloadTask osmTask = main.menu.download.downloadTasks.get(0);
DownloadTask osmTask = new DownloadOsmTask();
osmTask.download(main.menu.download, b.min.lat(), b.min.lon(), b.max.lat(), b.max.lon());
}
return;
}
if (s.startsWith("file:")) {
try {
main.menu.openFile.openFile(new File(new URI(s)));
} catch (URISyntaxException e) {
JOptionPane.showMessageDialog(Main.parent, tr("Ignoring malformed file URL: \"{0}\"", s));
}
return;
}
final StringTokenizer st = new StringTokenizer(s, ",");
if (st.countTokens() == 4) {
try {
DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
task.download(main.menu.download, Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
return;
} catch (final NumberFormatException e) {
}
}
main.menu.openFile.openFile(new File(s));
}
protected static void determinePlatformHook() {
String os = System.getProperty("os.name");
if (os == null) {
System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
platform = new PlatformHookUnixoid();
} else if (os.toLowerCase().startsWith("windows")) {
platform = new PlatformHookWindows();
} else if (os.equals("Linux") || os.equals("Solaris") ||
os.equals("SunOS") || os.equals("AIX") ||
os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
platform = new PlatformHookUnixoid();
} else if (os.toLowerCase().startsWith("mac os x")) {
platform = new PlatformHookOsx();
} else {
System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
platform = new PlatformHookUnixoid();
}
}
static public String getLanguageCodeU()
{
String languageCode = getLanguageCode();
if(languageCode.equals("en"))
return "";
return languageCode.substring(0,1).toUpperCase() + languageCode.substring(1) + ":";
}
static public String getLanguageCode()
{
String full = Locale.getDefault().toString();
if (full.equals("iw_IL"))
return "he";
/* list of non-single codes supported by josm */
else if (full.equals("en_GB"))
return full;
return Locale.getDefault().getLanguage();
}
static public void saveGuiGeometry() {
// save the current window geometry
String newGeometry = "";
try {
if (((JFrame)parent).getExtendedState() == JFrame.NORMAL) {
Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle bounds = parent.getBounds();
int width = (int)bounds.getWidth();
int height = (int)bounds.getHeight();
int x = (int)bounds.getX();
int y = (int)bounds.getY();
if (width > screenDimension.width)
width = screenDimension.width;
if (height > screenDimension.height)
width = screenDimension.height;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
newGeometry = width + "x" + height + "+" + x + "+" + y;
}
}
catch (Exception e) {
System.out.println("Failed to save GUI geometry: " + e);
}
pref.put("gui.geometry", newGeometry);
}
}
|
[
"[email protected]"
] | |
2c52c9b4bb67c93db81c2e8d467623bccf966e6e
|
097d7218213fc45c7b72e7a76373aa589fda187e
|
/ProgrammingTrainingSpringCommon/src/main/java/ru/innopolis/course3/pojo/Subject.java
|
44463198bd348a80da97081439071d4f66a2fca4
|
[] |
no_license
|
korotaeva/RMI
|
c3f9e8b02e9509fec675d78072b4da6bcf6df0c2
|
fe4ebdc78fa54037a925ee4e65fb6af897c3ead6
|
refs/heads/master
| 2021-01-13T05:32:21.643048 | 2017-01-26T20:56:18 | 2017-01-26T20:56:18 | 80,148,667 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,083 |
java
|
package ru.innopolis.course3.pojo;
import java.io.Serializable;
/**
* Created by korot on 23.12.2016.
* Объект тема
*/
public class Subject implements Identified<Integer> , Serializable {
public Subject() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
private String name;
public Subject(String name, String description, Integer id) {
this.name = name;
this.description = description;
this.id = id;
}
public Subject(String name, String description) {
this.name = name;
this.description = description;
}
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
private Integer id;
}
|
[
"[email protected]"
] | |
0d18e707953adf79e14767bdc83391686adf5f76
|
527742c4d4d6b8afbd20339326942374d8469073
|
/rbac-consumer/src/main/java/com/consumer/common/base/service/GenericService.java
|
68b7ee3a9091f3ee0737eaf77561b1e64237f7b0
|
[] |
no_license
|
gitzhangshuai/spring-cloud-rbac-master
|
e6a7d570474f8168f628f6065d2ee211fa66856b
|
b2c58fd57a5b0ae1529ff217b58a2bd53ec2e437
|
refs/heads/master
| 2020-06-02T09:37:04.386080 | 2019-06-10T07:33:48 | 2019-06-10T07:33:48 | 191,116,432 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,630 |
java
|
package com.consumer.common.base.service;
import com.base.common.QueryBase;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
/**
* Created by Administrator on 2018/1/30 0030.
*/
public interface GenericService<T, Q extends QueryBase> {
/**
* 功能描述:根据ID来获取数据
* @param id
* @return
*/
@RequestMapping(value = "/getById",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String,Object> getById(@RequestParam("id") int id);
/**
* 功能描述:获取数据
* @param entity
* @return
*/
@RequestMapping(value = "/get",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String,Object> get(@RequestBody T entity);
/**
* 功能描述:保存数据
* @param entity
* @return
*/
@RequestMapping(value = "/save",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
Map<String,Object> save(@RequestBody T entity);
/**
* 功能描述:更新数据数据
* @param entity
* @return
*/
@RequestMapping(value = "/update",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
Map<String,Object> update(@RequestBody T entity);
/**
* 功能描述:实现删除数据
* @param entity
* @return
*/
@RequestMapping(value = "/remove",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
Map<String,Object> remove(@RequestBody T entity);
/**
* 功能描述:实现批量删除的记录
* @param json
* @return
*/
@RequestMapping(value = "/removeBath",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
Map<String,Object> removeBath(@RequestParam("json") String json);
/**
* 功能描述:获取分页的数据
* @param entity
* @return
*/
@RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
Map<String,Object> list(@RequestBody Q entity);
/**
* 功能描述:判断当前的元素是否已经存在
* @param entity
* @return
*/
@RequestMapping(value = "/isExist",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
Map<String,Object> isExist(@RequestBody Q entity);
}
|
[
"[email protected]"
] | |
73d2fddbcedef7a253b05cb27039f556c3b6f4bc
|
09618dd7031d9a52fca7d7121d1e5aaab2a1661d
|
/Code/org.alloytools.alloy.core/src/main/java/edu/mit/csail/sdg/alloy4/WorkerEngine.java
|
5b8213c4fd4538112ed2dd781f13821557e5017f
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
Allisonius/Hawkeye
|
8acc8bab32d8c8d9e0fe3798b8dae59dfe946240
|
cda662c944b12c50afc49b371703761cefe4454b
|
refs/heads/main
| 2023-05-01T20:07:49.005153 | 2021-05-17T16:29:54 | 2021-05-17T16:29:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 21,305 |
java
|
/* Alloy Analyzer 4 -- Copyright (c) 2006-2009, Felix Chang
*
* 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 edu.mit.csail.sdg.alloy4;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.Thread.UncaughtExceptionHandler;
import org.alloytools.alloy.core.AlloyCore;
/**
* This class allows you to execute tasks in a subprocess, and receive its
* outputs via callback.
* <p>
* By executing the task in a subprocess, we can always terminate a runaway task
* explicitly by calling stop(), and we can control how much memory and stack
* space to give to the subprocess.
* <p>
* Only one task may execute concurrently at any given time; if you try to issue
* a new task when the previous task hasn't finished, then you will get an
* IOException.
* <p>
* As long as the subprocess hasn't terminated either due to crashing or due to
* user calling stop(), then the same subprocess is reused to execute each
* subsequent task; however, if the subprocess crashed, the crash will be
* reported to the parent process via callback, and if we try to execute another
* task, then a new subprocess will be spawned automatically.
*/
public final class WorkerEngine {
/**
* This defines an interface for performing tasks in a subprocess.
*/
public interface WorkerTask extends Serializable {
/**
* The task should send zero or more non-null Objects to out.callback(msg) to
* report progress to the parent process.
*/
public void run(WorkerCallback out) throws Exception;
}
/**
* This defines an interface for receiving results from a subprocess.
*/
public interface WorkerCallback {
/**
* The task would send zero or more non-null Objects to this handler (the
* objects will be serialized by the sub JVM and deserialized in the parent
* JVM).
*/
public void callback(Object msg);
/**
* If the task completed successfully, this method will be called.
*/
public void done();
/**
* If the task terminated with an error, this method will be called.
*/
public void fail();
}
/**
* This wraps the given InputStream such that the resulting object's "close()"
* method does nothing; if stream==null, we get an InputStream that always
* returns EOF.
*/
private static InputStream wrap(final InputStream stream) {
return new InputStream() {
@Override
public int read(byte b[], int off, int len) throws IOException {
if (len == 0)
return 0;
else if (stream == null)
return -1;
else
return stream.read(b, off, len);
}
@Override
public int read() throws IOException {
if (stream == null)
return -1;
else
return stream.read();
}
@Override
public long skip(long n) throws IOException {
if (stream == null)
return 0;
else
return stream.skip(n);
}
};
}
/**
* This wraps the given OutputStream such that the resulting object's "close()"
* method simply calls "flush()"; if stream==null, we get an OutputStream that
* ignores all writes.
*/
private static OutputStream wrap(final OutputStream stream) {
return new OutputStream() {
@Override
public void write(int b) throws IOException {
if (stream != null)
stream.write(b);
}
@Override
public void write(byte b[], int off, int len) throws IOException {
if (stream != null)
stream.write(b, off, len);
}
@Override
public void flush() throws IOException {
if (stream != null)
stream.flush();
}
@Override
public void close() throws IOException {
if (stream != null)
stream.flush();
}
// The close() method above INTENTIONALLY does not actually close
// the file
};
}
/** If nonnull, it is the latest sub JVM. */
private static Process latest_sub = null;
/**
* If nonnull, it is the latest worker thread talking to the sub JVM. (If
* latest_sub==null, then we guarantee latest_manager is also null)
*/
private static Thread latest_manager = null;
/**
* Constructor is private since this class does not need to be instantiated.
*/
private WorkerEngine() {
}
/**
* This terminates the subprocess, and prevent any further results from reaching
* the parent's callback handler.
*/
public static void stop() {
synchronized (WorkerEngine.class) {
try {
if (latest_sub != null)
latest_sub.destroy();
} finally {
latest_manager = null;
latest_sub = null;
}
}
}
/**
* This returns true iff the subprocess is still busy processing the last task.
*/
public static boolean isBusy() {
synchronized (WorkerEngine.class) {
return latest_manager != null && latest_manager.isAlive();
}
}
/**
* This executes a task using the current thread.
*
* @param task - the task that we want to execute
* @param callback - the handler that will receive outputs from the task
* @throws IOException - if a previous task is still busy executing
*/
public static void runLocally(final WorkerTask task, final WorkerCallback callback) throws Exception {
synchronized (WorkerEngine.class) {
if (latest_manager != null && latest_manager.isAlive())
throw new IOException("Subprocess still performing the last task.");
try {
task.run(callback);
callback.done();
} catch (Throwable ex) {
callback.callback(ex);
callback.fail();
}
}
}
/**
* This issues a new task to the subprocess; if subprocess hasn't been
* constructed yet or has terminated abnormally, this method will launch a new
* subprocess.
*
* @param task - the task that we want the subprocess to execute
* @param newmem - the amount of memory (in megabytes) we want the subprocess to
* have (if the subproces has not terminated, then this parameter is
* ignored)
* @param newstack - the amount of stack (in kilobytes) we want the subprocess
* to have (if the subproces has not terminated, then this parameter
* is ignored)
* @param jniPath - if nonnull and nonempty, then it specifies the subprocess's
* default JNI library location
* @param classPath - if nonnull and nonempty, then it specifies the
* subprocess's default CLASSPATH, else we'll use
* System.getProperty("java.class.path")
* @param callback - the handler that will receive outputs from the task
* @throws IOException - if a previous task is still busy executing
* @throws IOException - if an error occurred in launching a sub JVM or talking
* to it
*/
public static void run(final WorkerTask task, int newmem, int newstack, String jniPath, String classPath, final WorkerCallback callback) throws IOException {
String java = "java";
String javahome = System.getProperty("java.home");
if (javahome == null)
throw new IllegalArgumentException("java.home not set");
File jhome = new File(javahome);
if (classPath == null || classPath.isEmpty())
classPath = System.getProperty("java.class.path");
if (classPath == null || classPath.isEmpty()) {
File dist = findInAncestors(jhome, "org.alloytools.alloy.dist.jar");
if (dist == null) {
throw new IllegalArgumentException("cannot establish classpath. Neither set for this java nor \"org.alloytools.alloy.dist.jar\" in an ancestor directory of $JAVA_HOME (" + jhome + ")");
}
System.out.println("Found jar in ancestors java_home " + dist);
classPath = dist.getAbsolutePath();
}
synchronized (WorkerEngine.class) {
final Process sub;
if (latest_manager != null && latest_manager.isAlive())
throw new IOException("Subprocess still performing the last task.");
try {
if (latest_sub != null)
latest_sub.exitValue();
latest_manager = null;
latest_sub = null;
} catch (IllegalThreadStateException ex) {
}
if (latest_sub == null) {
File f = new File(javahome + File.separatorChar + "bin" + File.separatorChar + "java");
if (!f.isFile())
f = new File(javahome + File.separatorChar + "java");
if (f.isFile())
java = f.getAbsolutePath();
String debug = AlloyCore.isDebug() ? "yes" : "no";
if (jniPath != null && jniPath.length() > 0)
sub = Runtime.getRuntime().exec(new String[] {
java, "-Xmx" + newmem + "m", "-Xss" + newstack + "k", "-Djava.library.path=" + jniPath, "-Ddebug=" + debug, "-cp", classPath, WorkerEngine.class.getName(), Version.buildDate(), "" + Version.buildNumber()
});
else
sub = Runtime.getRuntime().exec(new String[] {
java, "-Xmx" + newmem + "m", "-Xss" + newstack + "k", "-Ddebug=" + debug, "-cp", classPath, WorkerEngine.class.getName(), Version.buildDate(), "" + Version.buildNumber()
});
latest_sub = sub;
} else {
sub = latest_sub;
}
latest_manager = new Thread(new Runnable() {
@Override
public void run() {
ObjectInputStream sub2main = null;
ObjectOutputStream main2sub = null;
try {
main2sub = new ObjectOutputStream(wrap(sub.getOutputStream()));
main2sub.writeObject(task);
main2sub.close();
sub2main = new ObjectInputStream(wrap(sub.getInputStream()));
} catch (Throwable ex) {
sub.destroy();
Util.close(main2sub);
Util.close(sub2main);
synchronized (WorkerEngine.class) {
if (latest_sub != sub)
return;
callback.fail();
return;
}
}
while (true) {
synchronized (WorkerEngine.class) {
if (latest_sub != sub)
return;
}
Object x;
try {
x = sub2main.readObject();
} catch (Throwable ex) {
sub.destroy();
Util.close(sub2main);
synchronized (WorkerEngine.class) {
if (latest_sub != sub)
return;
callback.fail();
return;
}
}
synchronized (WorkerEngine.class) {
if (latest_sub != sub)
return;
if (x == null) {
callback.done();
return;
} else
callback.callback(x);
}
}
}
});
latest_manager.start();
}
}
/**
* This is the entry point for the sub JVM.
* <p>
* Behavior is very simple: it reads a WorkerTask object from System.in, then
* execute it, then read another... If any error occurred, or if it's
* disconnected from the parent process's pipe, it then terminates itself (since
* we assume the parent process will notice it and react accordingly)
*/
public static void main(String[] args) {
// To prevent people from accidentally invoking this class, or invoking
// it from an incompatible version,
// we add a simple sanity check on the command line arguments
if (args.length != 2)
halt("#args should be 2 but instead is " + args.length, 1);
if (!args[0].equals(Version.buildDate()))
halt("BuildDate mismatch: " + args[0] + " != " + Version.buildDate(), 1);
if (!args[1].equals("" + Version.buildNumber()))
halt("BuildNumber mismatch: " + args[1] + " != " + Version.buildNumber(), 1);
// To prevent a zombie process, we set a default handler to terminate
// itself if something does slip through our detection
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
halt("UncaughtException: " + e, 1);
}
});
// Redirect System.in, System.out, System.err to no-op (so that if a
// task tries to read/write to System.in/out/err,
// those reads and writes won't mess up the
// ObjectInputStream/ObjectOutputStream)
System.setIn(wrap((InputStream) null));
System.setOut(new PrintStream(wrap((OutputStream) null)));
System.setErr(new PrintStream(wrap((OutputStream) null)));
final FileInputStream in = new FileInputStream(FileDescriptor.in);
final FileOutputStream out = new FileOutputStream(FileDescriptor.out);
// Preload these 3 libraries; on MS Windows with JDK 1.6 this seems to
// prevent freezes
try {
System.loadLibrary("minisat");
} catch (Throwable ex) {
}
try {
System.loadLibrary("minisatprover");
} catch (Throwable ex) {
}
try {
System.loadLibrary("zchaff");
} catch (Throwable ex) {
}
// Now we repeat the following read-then-execute loop
Thread t = null;
while (true) {
final WorkerTask task;
try {
System.gc(); // while we're waiting for the next task, we might
// as well encourage garbage collection
ObjectInputStream oin = new ObjectInputStream(wrap(in));
task = (WorkerTask) oin.readObject();
oin.close();
} catch (Throwable ex) {
halt("Can't read task: " + ex, 1);
return;
}
// Our main thread has a loop that keeps "attempting" to read bytes
// from System.in,
// and delegate the actual task to a separate "worker thread".
// This way, if the parent process terminates, then this subprocess
// should see it almost immediately
// (since the inter-process pipe will be broken) and will terminate
// (regardless of the status of the worker thread)
if (t != null && t.isAlive()) {
// We only get here if the previous subtask has informed the
// parent that the job is done, and that the parent
// then issued another job. So we wait up to 5 seconds for the
// worker thread to confirm its termination.
// If 5 seconds is up, then we assume something terrible has
// happened.
try {
t.join(5000);
if (t.isAlive())
halt("Timeout", 1);
} catch (Throwable ex) {
halt("Timeout: " + ex, 1);
}
}
t = new Thread(new Runnable() {
@Override
public void run() {
ObjectOutputStream x = null;
Throwable e = null;
try {
x = new ObjectOutputStream(wrap(out));
final ObjectOutputStream xx = x;
WorkerCallback y = new WorkerCallback() {
@Override
public void callback(Object x) {
try {
xx.writeObject(x);
} catch (IOException ex) {
halt("Callback: " + ex, 1);
}
}
@Override
public void done() {
}
@Override
public void fail() {
}
};
task.run(y);
x.writeObject(null);
x.flush();
} catch (Throwable ex) {
e = ex;
}
for (Throwable t = e; t != null; t = t.getCause())
if (t instanceof OutOfMemoryError || t instanceof StackOverflowError) {
try {
System.gc();
x.writeObject(t);
x.flush();
} catch (Throwable ex2) {
} finally {
halt("Error: " + e, 2);
}
}
if (e instanceof Err) {
try {
System.gc();
x.writeObject(e);
x.writeObject(null);
x.flush();
} catch (Throwable t) {
halt("Error: " + e, 1);
}
}
if (e != null) {
try {
System.gc();
x.writeObject(e);
x.flush();
} catch (Throwable t) {
} finally {
halt("Error: " + e, 1);
}
}
Util.close(x); // avoid memory leaks
}
});
t.start();
}
}
/** This method terminates the caller's process. */
private static void halt(String reason, int exitCode) {
Runtime.getRuntime().halt(exitCode);
}
private static File findInAncestors(File rover, String fileName) {
while (true) {
if (rover == null)
return null;
File f = new File(rover, fileName);
if (f.isFile())
return f;
rover = rover.getParentFile();
}
}
}
|
[
"[email protected]"
] | |
084645cd4436a35dc11218e365c1b57dc339963f
|
83dbd433aeed1f15f6501f39fe152abc0dc803d9
|
/design_pattern_study/geek_design_pattern/src/main/java/com/bd/geek/design/pattern/observer/observable/WeatherData.java
|
f5ceb8a4255a45b47511be1ea4b630442ec1eaa8
|
[] |
no_license
|
pylrichard/web_service_study
|
d0d42ea0c511b9b15a235a99cde5b4b025c33c6d
|
c1bd8753c6aee69c87707db7f3fb8e0d7f5ddbc0
|
refs/heads/master
| 2021-09-14T23:31:12.454640 | 2018-05-22T06:26:14 | 2018-05-22T06:26:14 | 104,879,563 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,253 |
java
|
package com.bd.geek.design.pattern.observer.observable;
import lombok.Getter;
import java.util.Observable;
/**
* Observable是类不是接口
*/
@Getter
public class WeatherData extends Observable {
private float temperature;
private float pressure;
private float humidity;
public void dataChange() {
//可设定满足一定条件才通知观察者,提高灵活性
this.setChanged();
/*
notifyObservers()只通知观察者有变化,不发送数据
notifyObservers(arg)通知观察者有变化,并发送数据
*/
this.notifyObservers(new Data(getTemperature(), getPressure(), getHumidity()));
}
public void setData(float temperature, float pressure, float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
dataChange();
}
@Getter
public class Data {
private float temperature;
private float pressure;
private float humidity;
public Data(float temperature, float pressure, float humidity) {
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
}
}
}
|
[
"[email protected]"
] | |
52b656ed89e2602199c287345e334b3150da6465
|
b4e166bb430ce87a1fc3664af832c95300c05aa9
|
/plugins/BasePlugin/src/org/kvj/vimtouch/ext/impl/read/DoubleFieldReader.java
|
b4eaa8e6bf2e0ccf394160513755a2adb643d7ee
|
[
"Apache-2.0"
] |
permissive
|
suhan-paradkar/vimtouch
|
979ba6d2b7cfb4ac7ab10ad3366155d9c85c457f
|
cc61416d58d2625483d3d2552f0092ef4fc625c8
|
refs/heads/master
| 2023-07-11T18:36:45.707437 | 2021-08-05T01:53:20 | 2021-08-05T01:53:20 | 392,695,683 | 0 | 0 |
Apache-2.0
| 2021-08-04T13:23:37 | 2021-08-04T13:18:36 |
Java
|
UTF-8
|
Java
| false | false | 633 |
java
|
package org.kvj.vimtouch.ext.impl.read;
import org.kvj.vimtouch.ext.FieldReader;
import org.kvj.vimtouch.ext.FieldReaderException;
import org.kvj.vimtouch.ext.IncomingTransfer;
import org.kvj.vimtouch.ext.Transferable.FieldType;
public abstract class DoubleFieldReader implements FieldReader<Double> {
@Override
public FieldType getType() {
return FieldType.Double;
}
@Override
public Double read(IncomingTransfer t) throws FieldReaderException {
String value = t.nextPiece();
try {
return Double.parseDouble(value);
} catch (Exception e) {
}
throw new FieldReaderException("Invalid double: " + value);
}
}
|
[
"[email protected]"
] | |
4e651c61fe424754f519d8bd53c85ff8363a5d96
|
d0935a661f860801dbd1aa1e97cc77632dc03f91
|
/src/main/java/FinTechOne/FOGS/hibernate/DomainInterceptor.java
|
fab6227c98368172c4e4257d35841a0b0bc61e7e
|
[] |
no_license
|
mr-ying/FOGS-backend-ying
|
0da45a7107b555ce8851d09ede90468a3d589251
|
a000c794cf8a03bc2cefc501fc058e858ad7eee5
|
refs/heads/master
| 2021-01-11T20:18:00.077099 | 2017-01-19T15:25:31 | 2017-01-19T15:25:31 | 79,083,787 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 3,129 |
java
|
package FinTechOne.FOGS.hibernate;
import FinTechOne.FOGS.exception.TemperedKeyException;
import FinTechOne.FOGS.exception.TemperedKeyException.KeyProperty;
import org.apache.commons.lang.WordUtils;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.core.annotation.AnnotationUtils;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by User on 14/1/2017.
*/
public class DomainInterceptor extends EmptyInterceptor {
public boolean onFlushDirty(Object entity,Serializable id,
Object[] currentState,Object[] previousState,
String[] propertyNames,Type[] types)
throws CallbackException {
Annotation annotation = AnnotationUtils.findAnnotation(entity.getClass(), Table.class);
if (annotation != null) {
Table table = (Table)annotation;
if (table.uniqueConstraints() !=null) {
for (UniqueConstraint uniqueConstraint : table.uniqueConstraints()) {
if (uniqueConstraint.columnNames() != null) {
List<KeyProperty> keyProperties = new ArrayList<KeyProperty>();
boolean hasError = false;
for (String columnName: uniqueConstraint.columnNames()) {
// try {
// Object newValue = entity.getClass().getMethod("get" + WordUtils.capitalize(columnName)).invoke(entity,null);
// }catch (NoSuchMethodException e){
//
// }catch (InvocationTargetException e){
//
// }catch (IllegalAccessException e){
//
// }
int i = Arrays.asList(propertyNames).indexOf(columnName);
Object oldValue = previousState[i];
Object newValue = currentState[i];
keyProperties.add(KeyProperty.of(columnName, oldValue, newValue));
hasError = hasError || !(
oldValue == null && newValue == null ||
oldValue.equals(newValue));
}
if (hasError){
TemperedKeyException e = new TemperedKeyException(entity.getClass().getSimpleName(), keyProperties, "TemperedKey", "Key Tempered");
throw new CallbackException(e);
}
}
}
}
}
return false;
}
public void onDelete(Object entity, Serializable id,
Object[] state, String[] propertyNames,
Type[] types) {
System.out.println("onDelete");
}
}
|
[
"[email protected]"
] | |
db1ac604f28caa6d7d819c186dd0d1a522888d83
|
220a74a53c7072a18f577d3603467b8796956a68
|
/src/StreamCollectorsGroupingBy/GroupingByPrice.java
|
c2694649a2e98b174713ac5a9622cfb04da1123a
|
[] |
no_license
|
jihazard/JAVA-8-Exercise
|
95bcd7704c9319331971a44548ac4d7e8c116608
|
4a75501c5538f5506ecdfb2b1ac1548b5b121bbe
|
refs/heads/master
| 2021-09-06T06:42:53.977471 | 2018-02-03T10:58:28 | 2018-02-03T10:58:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,388 |
java
|
package StreamCollectorsGroupingBy;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class GroupingByPrice {
public static void main(String[] args) {
//3 apple, 2 banana, others 1
List<Item> items = Arrays.asList(
new Item("apple", 10, new BigDecimal("9.99")),
new Item("banana", 20, new BigDecimal("19.99")),
new Item("orang", 10, new BigDecimal("29.99")),
new Item("watermelon", 10, new BigDecimal("29.99")),
new Item("papaya", 20, new BigDecimal("9.99")),
new Item("apple", 10, new BigDecimal("9.99")),
new Item("banana", 10, new BigDecimal("19.99")),
new Item("apple", 20, new BigDecimal("9.99"))
);
Map<BigDecimal,List<Item>> groupBypriceMap =
items.stream().collect(Collectors.groupingBy(Item::getPrice));
System.out.println(groupBypriceMap);
Map<BigDecimal ,Set<String>> result =
items.stream().collect(
Collectors.groupingBy(Item::getPrice,
Collectors.mapping(Item::getName,Collectors.toSet()))
);
System.out.println(result);
}
}
|
[
"[email protected]"
] | |
3e59baeb0726f5bc0e705763329d0e7634305e21
|
aa4f8a91f2e45ddcfd828ad8aa302d45bc69c0f2
|
/integration-tests/telegram/src/test/java/org/apache/camel/quarkus/component/telegram/it/TelegramTest.java
|
38e40ffd8a7ea0f3e918a9cd5ddff51b6182311b
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
caobingsheng/camel-quarkus
|
a981e70d1d83edea9ed1e63bf29938620642385b
|
9b52e1f568217cd780a21c868a4f20950f3ced4d
|
refs/heads/master
| 2023-01-01T17:46:05.676216 | 2020-10-27T03:04:47 | 2020-10-27T03:04:47 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 7,249 |
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.camel.quarkus.component.telegram.it;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.apache.camel.component.telegram.model.EditMessageLiveLocationMessage;
import org.apache.camel.component.telegram.model.MessageResult;
import org.apache.camel.component.telegram.model.SendLocationMessage;
import org.apache.camel.component.telegram.model.SendVenueMessage;
import org.apache.camel.component.telegram.model.StopMessageLiveLocationMessage;
import org.apache.camel.quarkus.test.TrustStoreResource;
import org.awaitility.Awaitility;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Test;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
@QuarkusTest
@QuarkusTestResource(TrustStoreResource.class)
public class TelegramTest {
private static final Logger LOG = Logger.getLogger(TelegramTest.class);
@Test
public void postText() {
final String uuid = UUID.randomUUID().toString().replace("-", "");
final String msg = String.format("A message from camel-quarkus-telegram %s", uuid);
/* Send a message */
RestAssured.given()
.contentType(ContentType.TEXT)
.body(msg)
.post("/telegram/messages")
.then()
.statusCode(201);
}
@Test
public void getText() {
/* Telegram bots by design see neither their own messages nor other bots' messages.
* So receiving messages is currently possible only if you ping the bot manually.
* If you do so, you should see your messages in the test log. */
for (int i = 0; i < 5; i++) { // For some reason several iterations are needed to pick the messages
final String body = RestAssured.get("/telegram/messages")
.then()
.statusCode(is(both(greaterThanOrEqualTo(200)).and(lessThan(300))))
.extract().body().asString();
LOG.info("Telegram Bot received messages: " + body);
}
}
@Test
public void png() throws IOException {
try (InputStream in = getClass().getClassLoader().getResourceAsStream("camel-quarkus-rocks.png")) {
/* Send a message */
RestAssured.given()
.contentType("image/png")
.body(in)
.post("/telegram/media")
.then()
.statusCode(201);
}
}
@Test
public void mp3() throws IOException {
try (InputStream in = getClass().getClassLoader().getResourceAsStream("camel-quarkus-rocks.mp3")) {
/* Send a message */
RestAssured.given()
.contentType("audio/mpeg")
.body(in)
.post("/telegram/media")
.then()
.statusCode(201);
}
}
@Test
public void mp4() throws IOException {
try (InputStream in = getClass().getClassLoader().getResourceAsStream("camel-quarkus-rocks.mp4")) {
/* Send a message */
RestAssured.given()
.contentType("video/mp4")
.body(in)
.post("/telegram/media")
.then()
.statusCode(201);
}
}
@Test
public void pdf() throws IOException {
try (InputStream in = getClass().getClassLoader().getResourceAsStream("camel-quarkus-rocks.pdf")) {
/* Send a message */
RestAssured.given()
.contentType("application/pdf")
.body(in)
.post("/telegram/media")
.then()
.statusCode(201);
}
}
@Test
public void location() throws IOException {
final SendLocationMessage sendLoc = new SendLocationMessage(29.974834, 31.138577);
sendLoc.setLivePeriod(120);
final MessageResult result = RestAssured.given()
.contentType(ContentType.JSON)
.body(sendLoc)
.post("/telegram/send-location")
.then()
.statusCode(201)
.extract().body().as(MessageResult.class);
/* Update the location */
final EditMessageLiveLocationMessage edit = new EditMessageLiveLocationMessage(29.974928, 31.131115);
edit.setChatId(result.getMessage().getChat().getId());
edit.setMessageId(result.getMessage().getMessageId());
/* The edit fails with various 400 errors unless we wait a bit */
Awaitility.await()
.pollDelay(500, TimeUnit.MILLISECONDS)
.pollInterval(100, TimeUnit.MILLISECONDS)
.atMost(10, TimeUnit.SECONDS).until(() -> {
final int code = RestAssured.given()
.contentType(ContentType.JSON)
.body(edit)
.post("/telegram/edit-location")
.then()
.extract().statusCode();
return code != 201;
});
/* Stop updating */
final StopMessageLiveLocationMessage stop = new StopMessageLiveLocationMessage();
stop.setChatId(result.getMessage().getChat().getId());
stop.setMessageId(result.getMessage().getMessageId());
RestAssured.given()
.contentType(ContentType.JSON)
.body(stop)
.post("/telegram/stop-location")
.then()
.statusCode(201);
}
@Test
public void venue() throws IOException {
final SendVenueMessage venue = new SendVenueMessage(29.977818, 31.136329, "Pyramid of Queen Henutsen",
"El-Hussein Ibn Ali Ln, Nazlet El-Semman, Al Haram, Giza Governorate, Egypt");
RestAssured.given()
.contentType(ContentType.JSON)
.body(venue)
.post("/telegram/venue")
.then()
.statusCode(201);
}
}
|
[
"[email protected]"
] | |
3347a541da7a54078b987148c4bf9b5bd2f28a98
|
3ef55e152decb43bdd90e3de821ffea1a2ec8f75
|
/large/module2097_public/tests/unittests/src/java/module2097_public_tests_unittests/a/IFoo3.java
|
9aa942d1aacc78b204a90e020fb6e4b39782e886
|
[
"BSD-3-Clause"
] |
permissive
|
salesforce/bazel-ls-demo-project
|
5cc6ef749d65d6626080f3a94239b6a509ef145a
|
948ed278f87338edd7e40af68b8690ae4f73ebf0
|
refs/heads/master
| 2023-06-24T08:06:06.084651 | 2023-03-14T11:54:29 | 2023-03-14T11:54:29 | 241,489,944 | 0 | 5 |
BSD-3-Clause
| 2023-03-27T11:28:14 | 2020-02-18T23:30:47 |
Java
|
UTF-8
|
Java
| false | false | 842 |
java
|
package module2097_public_tests_unittests.a;
import java.util.zip.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
/**
* Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
* labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
* Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
*
* @see java.awt.datatransfer.DataFlavor
* @see java.beans.beancontext.BeanContext
* @see java.io.File
*/
@SuppressWarnings("all")
public interface IFoo3<V> extends module2097_public_tests_unittests.a.IFoo2<V> {
java.rmi.Remote f0 = null;
java.nio.file.FileStore f1 = null;
java.sql.Array f2 = null;
String getName();
void setName(String s);
V get();
void set(V e);
}
|
[
"[email protected]"
] | |
a7d66282b4ae5a70afefc2a4f9da2497b648182a
|
b0fdc1b1a6b3d2a48be553c4c3c6aeeafa5d5b36
|
/src/test/java/shoppingcart/TestCart.java
|
f33ab013c65191d0e5f1d17e4c69d3ec9522e8d3
|
[] |
no_license
|
ashwinvarma/ADP_Assignment
|
267ab105b819c4785c5c2af9832fc5552b5cab56
|
28b4c58f872fed664259e660f454e13558fe0198
|
refs/heads/master
| 2020-04-08T20:53:08.441347 | 2018-11-29T19:57:57 | 2018-11-29T19:57:57 | 159,718,991 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,128 |
java
|
package shoppingcart;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.json.simple.parser.ParseException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import junit.framework.Assert;
import shoppingcart.BillProcessing;
public class TestCart {
private BillProcessing billprocess;
@Rule
public final ExpectedException exc = ExpectedException.none();
@Before
public void init(){
billprocess = new BillProcessing();
}
@Test
public void testReadCategories() throws IOException, ParseException{
billprocess.jsonReader("JSONData\\Categories.json");
Assert.assertEquals("BabyProducts",billprocess.getCategoriesMap().get(4).getName());
Assert.assertEquals(10.0,billprocess.getCategoriesMap().get(4).getDiscPerc(),1);
}
@Test
public void testReadFlatDiscountSlabs() throws IOException, ParseException{
billprocess.jsonReader("JSONData\\FlatDiscountSlabs.json");
Assert.assertEquals(3001,billprocess.getflatDiscountSlabsList().get(1).getRangeMin());
Assert.assertEquals(7000,billprocess.getflatDiscountSlabsList().get(1).getRangeMax());
Assert.assertEquals(4.0,billprocess.getflatDiscountSlabsList().get(1).getDiscPerc(),1);
}
@Test
public void testReadShoppingCart() throws IOException, ParseException{
billprocess.jsonReader("JSONData\\ShoppingCart.json");
Assert.assertEquals("Organic Tomatoes",billprocess.getShoppingCartItemsList().get(2).getItemName());
Assert.assertEquals(2,billprocess.getShoppingCartItemsList().get(2).getQuantity());
}
@Test(expected = FileNotFoundException.class)
public void testFileNotFoundException() throws IOException, ParseException{
billprocess.jsonReader("demo.json");
}
@Test
public void testCalculateBillAmount() throws IOException, ParseException{
billprocess.jsonReader("JSONData\\Categories.json");
billprocess.jsonReader("JSONData\\FlatDiscountSlabs.json");
billprocess.jsonReader("JSONData\\ShoppingCart.json");
Assert.assertEquals("Bill Amount check",1601.516,billprocess.calculateBillAmount(),1);
}
}
|
[
"[email protected]"
] | |
0728aea4a28b0a1cf0d7b812943bbb99be7b3d9c
|
f5043eb1ffa70bc999bd63d7f2d6f99c9a9ac057
|
/app/src/main/java/ir/guardianapp/routingproject/network/Requester.java
|
47b04479ce58487da621861904f89c81cf8699d1
|
[] |
no_license
|
GuardianAppProject/RoutingProject
|
d42ff5f3521e4d35e8e43d3d6dc86a5444d118d0
|
f99be5e29b01865e2e4e346d8166e487e121b219
|
refs/heads/master
| 2023-03-30T08:55:56.209168 | 2021-03-30T19:38:53 | 2021-03-30T19:38:53 | 348,464,087 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,999 |
java
|
package ir.guardianapp.routingproject.network;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Requester {
private static Requester requester;
private Requester(){}
public static Requester getInstance(){
if(requester==null) requester = new Requester();
return requester;
}
public Response RequestBestRoute(double source_latitude, double source_longitude, double dest_latitude, double dest_longitude){
OkHttpClient okHttpClient = new OkHttpClient();
// http://router.project-osrm.org/route/v1/driving/51.404343,35.715298;50.99155,35.83266?geometries=geojson
HttpUrl.Builder urlBuilder = HttpUrl.parse("http://router.project-osrm.org/route/v1/driving/" + source_longitude + "," + source_latitude + ";" + dest_longitude + "," + dest_latitude + "?geometries=geojson&overview=full")
.newBuilder();
String url = urlBuilder.build().toString();
final Request request = new Request.Builder().url(url)
.build();
try {
return okHttpClient.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Response RequestPlaces(String places){
OkHttpClient okHttpClient = new OkHttpClient();
// https://nominatim.openstreetmap.org/search?q=سالاریه&format=json&addressdetails=1
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://nominatim.openstreetmap.org/search?q=" + places + "&format=json&addressdetails=1")
.newBuilder();
String url = urlBuilder.build().toString();
final Request request = new Request.Builder().url(url)
.build();
try {
return okHttpClient.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
|
[
"[email protected]"
] | |
f729e90d92039cc62f4ca811807ebe8482e33467
|
a58f389304130b2a0430e4029f8e91796ef14e4d
|
/the-fascinator/branches/media/portal/src/main/java/au/edu/usq/fascinator/portal/velocity/JythonIterator.java
|
89195171cbafc5e5fd8c640a7441dce82377721d
|
[] |
no_license
|
VeenaHosur/the-fascinator
|
f7b78f07a282e82faf5fad0ce1076c69caacebc6
|
048a42519568070e4806ca9fb59fc0eabcb7cb0c
|
refs/heads/master
| 2022-12-22T10:33:13.511883 | 2013-01-23T02:15:51 | 2013-01-23T02:15:51 | 50,575,653 | 1 | 0 | null | 2022-12-16T00:16:12 | 2016-01-28T10:34:28 |
Java
|
UTF-8
|
Java
| false | false | 1,643 |
java
|
/*
* The Fascinator - Portal
* Copyright (C) 2008-2009 University of Southern Queensland
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package au.edu.usq.fascinator.portal.velocity;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.python.core.PySequence;
public class JythonIterator implements Iterator<Object> {
private PySequence seq;
private int pos;
private int size;
public JythonIterator(PySequence sequence) {
seq = sequence;
pos = 0;
size = sequence.__len__();
}
@Override
public Object next() {
if (hasNext()) {
return seq.__getitem__(pos++);
}
throw new NoSuchElementException("No more elements: " + pos + " / "
+ size);
}
@Override
public boolean hasNext() {
return pos < size;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
[
"octalina@f51757dd-c7a7-c463-22b4-a0e335d354ad"
] |
octalina@f51757dd-c7a7-c463-22b4-a0e335d354ad
|
26d7804ce2487cb090f403fa412e0598b6be0483
|
e69e8263b61074ac57ecd5740846d3b1264cc854
|
/app/src/main/java/com/example/simadeui/admin/writer/AdminWriterFragmentPagerAdapter.java
|
9e149229ad1e65d061c5937434dcea15b2dd8c8e
|
[] |
no_license
|
AbhiAdityaksa/SiMade-F-M
|
7b8dcbd80e273881c2ba1cd501606b0061acd197
|
3afb17fa138ae1af99c0f9f5d305d248bc7e128a
|
refs/heads/master
| 2020-04-23T00:21:17.675737 | 2019-03-25T02:55:19 | 2019-03-25T02:55:19 | 170,776,512 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,164 |
java
|
package com.example.simadeui.admin.writer;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.simadeui.admin.writer.carity.DataCarityFragment;
import com.example.simadeui.admin.writer.category.CategoryFragment;
import com.example.simadeui.admin.writer.reportcategory.ReportCategoryFragment;
import com.example.simadeui.admin.writer.villageinfo.VillageInfoFragment;
public class AdminWriterFragmentPagerAdapter extends FragmentPagerAdapter {
private Context mycontext;
public AdminWriterFragmentPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mycontext = context;
}
@Override
public Fragment getItem(int i) {
if (i == 0){
return new VillageInfoFragment();
} else if (i == 1){
return new ReportCategoryFragment();
}else if (i == 2){
return new CategoryFragment();
}else {
return new DataCarityFragment();
}
}
@Override
public int getCount() {
return 4;
}
}
|
[
"[email protected]"
] | |
0e2d96f4a03def06175315a2559a5e49de48693d
|
354ed8b713c775382b1e2c4d91706eeb1671398b
|
/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/package-info.java
|
e5ac4fee8edee1eacab50589da0f4030642c615b
|
[] |
no_license
|
JessenPan/spring-framework
|
8c7cc66252c2c0e8517774d81a083664e1ad4369
|
c0c588454a71f8245ec1d6c12f209f95d3d807ea
|
refs/heads/master
| 2021-06-30T00:54:08.230154 | 2019-10-08T10:20:25 | 2019-10-08T10:20:25 | 91,221,166 | 2 | 0 | null | 2017-05-14T05:01:43 | 2017-05-14T05:01:42 | null |
UTF-8
|
Java
| false | false | 695 |
java
|
/**
* Package allowing MVC Controller implementations to handle requests
* at <i>method</i> rather than <i>class</i> level. This is useful when
* we want to avoid having many trivial controller classes, as can
* easily happen when using an MVC framework.
* <p>
* <p>Typically a controller that handles multiple request types will
* extend MultiActionController, and implement multiple request handling
* methods that will be invoked by reflection if they follow this class'
* naming convention. Classes are analyzed at startup and methods cached,
* so the performance overhead of reflection in this approach is negligible.
*/
package org.springframework.web.servlet.mvc.multiaction;
|
[
"[email protected]"
] | |
a52cec75eca4e11e9c667cb15743273c17e7e3c5
|
ff427c7de6028cac874e59275bf191346757846b
|
/src/main/java/co/edu/sena/booking/jpa/entities/Foto.java
|
92f32dbc4eb6cedd4846adc37bd3b4c9ff8c9c6a
|
[] |
no_license
|
luberf/BookingJPAusuarioCRUD
|
cc1442b30bdd7fa09778c6fd6cba23f9963b2d13
|
37d7aa5b7d786e30344df1358e37c322ff67366a
|
refs/heads/main
| 2023-04-15T11:52:27.901465 | 2021-04-26T22:04:51 | 2021-04-26T22:04:51 | 361,903,062 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 4,122 |
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 co.edu.sena.booking.jpa.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author USER
*/
@Entity
@Table(name = "foto", catalog = "db_booking", schema = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Foto.findAll", query = "SELECT f FROM Foto f")
, @NamedQuery(name = "Foto.findByFotId", query = "SELECT f FROM Foto f WHERE f.fotId = :fotId")
, @NamedQuery(name = "Foto.findByFotRuta", query = "SELECT f FROM Foto f WHERE f.fotRuta = :fotRuta")
, @NamedQuery(name = "Foto.findByFotLabel", query = "SELECT f FROM Foto f WHERE f.fotLabel = :fotLabel")})
public class Foto implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "fotId", nullable = false)
private Integer fotId;
@Basic(optional = false)
@Column(name = "fotRuta", nullable = false, length = 45)
private String fotRuta;
@Basic(optional = false)
@Column(name = "fotLabel", nullable = false, length = 45)
private String fotLabel;
@Lob
@Column(name = "fotDescripcion", length = 16777215)
private String fotDescripcion;
@JoinColumn(name = "fkAlojamiento", referencedColumnName = "aloId")
@ManyToOne(fetch = FetchType.EAGER)
private Alojamiento fkAlojamiento;
@JoinColumn(name = "fkLugar", referencedColumnName = "lugId")
@ManyToOne(fetch = FetchType.EAGER)
private Lugar fkLugar;
public Foto() {
}
public Foto(Integer fotId) {
this.fotId = fotId;
}
public Foto(Integer fotId, String fotRuta, String fotLabel) {
this.fotId = fotId;
this.fotRuta = fotRuta;
this.fotLabel = fotLabel;
}
public Integer getFotId() {
return fotId;
}
public void setFotId(Integer fotId) {
this.fotId = fotId;
}
public String getFotRuta() {
return fotRuta;
}
public void setFotRuta(String fotRuta) {
this.fotRuta = fotRuta;
}
public String getFotLabel() {
return fotLabel;
}
public void setFotLabel(String fotLabel) {
this.fotLabel = fotLabel;
}
public String getFotDescripcion() {
return fotDescripcion;
}
public void setFotDescripcion(String fotDescripcion) {
this.fotDescripcion = fotDescripcion;
}
public Alojamiento getFkAlojamiento() {
return fkAlojamiento;
}
public void setFkAlojamiento(Alojamiento fkAlojamiento) {
this.fkAlojamiento = fkAlojamiento;
}
public Lugar getFkLugar() {
return fkLugar;
}
public void setFkLugar(Lugar fkLugar) {
this.fkLugar = fkLugar;
}
@Override
public int hashCode() {
int hash = 0;
hash += (fotId != null ? fotId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Foto)) {
return false;
}
Foto other = (Foto) object;
if ((this.fotId == null && other.fotId != null) || (this.fotId != null && !this.fotId.equals(other.fotId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "co.edu.sena.booking.apis.entities.Foto[ fotId=" + fotId + " ]";
}
}
|
[
"[email protected]"
] | |
55c25a4b8c9e0eb350a17706cb062c66001407ba
|
b512c8613610380b02ead16e8a207bca3b4d9b89
|
/seleniumTraining/src/main/java/day2/VariablesInJava.java
|
010c2c4bcbe17c93f4be869e8ac887b2e308db7b
|
[] |
no_license
|
sikanm5/DemoRepository
|
2ac5d89a49f8cd3a561f73e4cdd9ae0476156752
|
4952bf025bee3cc602ff462f8adea4f5cc2bbaa3
|
refs/heads/master
| 2020-05-04T11:52:10.208800 | 2019-04-23T15:59:15 | 2019-04-23T15:59:15 | 179,117,333 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 705 |
java
|
package day2;
public class VariablesInJava {
//3 kind of variables
//local - local to methods - stack
//instance - local to instance - heap
//static - class level - class loader area
static String collage; //static variable
String student; //instance
int rollNo; //instance
//constructor
public VariablesInJava(String name,int roll) {
student = name;
rollNo = roll;
}
public void printStudentDetails() {
System.out.println("collage " + collage + "----------" +
"name " + student + "----------" +
"rollno " + rollNo);
}
public void testForLocalVar() {
int z = 0; //local
System.out.println(z);
}
}
|
[
"[email protected]"
] | |
7da1249c9c7f9d4e28b65595df3d049fd8366c45
|
1aebbe83e7ba29bcfad12258d375fb3ce5ffbacc
|
/src/io/github/notaphplover/catan/serialization/command/CommandSerializer.java
|
d40f39cc88fd3bf9a6b8a1637306282bd671d97c
|
[] |
no_license
|
notaphplover/catan-serialization
|
98bef8b0ff5070184b02b2c10b10c58f7f1acd33
|
83ba50677e07ece11314c49343270de29882fa93
|
refs/heads/develop
| 2022-11-12T22:00:02.136691 | 2020-06-26T14:53:17 | 2020-06-26T14:53:17 | 256,505,950 | 0 | 0 | null | 2020-06-26T14:53:18 | 2020-04-17T13:09:15 |
Java
|
UTF-8
|
Java
| false | false | 267 |
java
|
package io.github.notaphplover.catan.serialization.command;
import io.github.notaphplover.catan.core.command.ICommand;
public class CommandSerializer extends BaseCommandSerializer<ICommand> {
private static final long serialVersionUID = -2121903246536401475L;
}
|
[
"[email protected]"
] | |
69b75dc2987dcec4d7d78c57d61952852c48098a
|
bfcc64c52efef9beab31968615f0c30626159bdc
|
/seerp/src/it/seerp/application/bean/tabelle/RuoloTm.java
|
4467271a07c57112831353372a378c380aa9c961
|
[] |
no_license
|
damang/seerp
|
01b48099a10ce43b2157ceb6328ab566844bbff9
|
98c0879ed7d48a989786ebfbbff26d1afee7da31
|
refs/heads/master
| 2021-01-13T02:30:17.896536 | 2018-10-15T03:28:27 | 2018-10-15T03:28:27 | 32,532,561 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,885 |
java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package it.seerp.application.bean.tabelle;
import it.seerp.application.Exception.ValidatorException;
import it.seerp.application.applicazione.AppRuoli;
import it.seerp.storage.ejb.Ruolo;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JTable;
/**
*
* @author Luisa
*/
public class RuoloTm extends Generica<Ruolo> {
private JTable table;
/**
*
* @throws java.sql.SQLException
*/
public RuoloTm() throws SQLException{
Object[] list = new Object[]{ "nome" };
super.setColumnIdentifiers(list);
super.setColumnCount(1);
refresh();
}
public void refresh() throws SQLException{
AppRuoli op = new AppRuoli();
Iterator <Ruolo> it = op.visualizzaTabella().iterator();
this.getDataCollection().removeAllElements();
while (it.hasNext()) {
this.addNewData(it.next());}
}
/**
*
* @param table
* @throws SQLException
*/
public RuoloTm(JTable table) throws SQLException,ValidatorException {
this();
this.table=table;
}
public boolean isCellEditable(int row, int column) {
return false;
}
@Override
public Ruolo newData() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected Vector creaArrayObjectData(Ruolo o) {
Vector c = new Vector();
c.add(o.getNome());
return c;
}
@Override
protected void modifyArrayObjectData(Ruolo element, Object aValue, int column) {
Ruolo p = super.getDataCollection().get(column);
p = element;
}
@Override
public void updateData(Ruolo c, int indice) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
[
"damatoangelo@170c7fde-46e4-11de-aa63-c184e82abc01"
] |
damatoangelo@170c7fde-46e4-11de-aa63-c184e82abc01
|
28dc818927006bacaea3f5267656125be512d2f6
|
3883b0bb5df44665126eabbd870e99b908271730
|
/src/test/java/com/sonnetstone/inventory/service/UserServiceIntTest.java
|
122450394ee4d1fe99676c88b34b734d78805fa8
|
[] |
no_license
|
BulkSecurityGeneratorProject1/inventory
|
7a1b1409f0a9f08b662b7f9d860c5581d670728f
|
ab5f445c05e42846ae06054e9252f46f434f40c1
|
refs/heads/master
| 2022-12-11T10:47:05.772420 | 2018-02-26T06:21:31 | 2018-02-26T06:21:31 | 296,559,108 | 0 | 0 | null | 2020-09-18T08:19:45 | 2020-09-18T08:19:45 | null |
UTF-8
|
Java
| false | false | 6,433 |
java
|
package com.sonnetstone.inventory.service;
import com.sonnetstone.inventory.InventoryApp;
import com.sonnetstone.inventory.config.Constants;
import com.sonnetstone.inventory.domain.User;
import com.sonnetstone.inventory.repository.UserRepository;
import com.sonnetstone.inventory.service.dto.UserDTO;
import com.sonnetstone.inventory.service.util.RandomUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
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.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for the UserResource REST controller.
*
* @see UserService
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = InventoryApp.class)
@Transactional
public class UserServiceIntTest {
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
private User user;
@Before
public void init() {
user = new User();
user.setLogin("johndoe");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setEmail("johndoe@localhost");
user.setFirstName("john");
user.setLastName("doe");
user.setImageUrl("http://placehold.it/50x50");
user.setLangKey("en");
}
@Test
@Transactional
public void assertThatUserMustExistToResetPassword() {
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.requestPasswordReset("invalid.login@localhost");
assertThat(maybeUser).isNotPresent();
maybeUser = userService.requestPasswordReset(user.getEmail());
assertThat(maybeUser).isPresent();
assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail());
assertThat(maybeUser.orElse(null).getResetDate()).isNotNull();
assertThat(maybeUser.orElse(null).getResetKey()).isNotNull();
}
@Test
@Transactional
public void assertThatOnlyActivatedUserCanRequestPasswordReset() {
user.setActivated(false);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
public void assertThatResetKeyMustBeValid() {
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey("1234");
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
public void assertThatUserCanResetPassword() {
String oldPassword = user.getPassword();
Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isPresent();
assertThat(maybeUser.orElse(null).getResetDate()).isNull();
assertThat(maybeUser.orElse(null).getResetKey()).isNull();
assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword);
userRepository.delete(user);
}
@Test
@Transactional
public void testFindNotActivatedUsersByCreationDateBefore() {
Instant now = Instant.now();
user.setActivated(false);
User dbUser = userRepository.saveAndFlush(user);
dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
userRepository.saveAndFlush(user);
List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
assertThat(users).isNotEmpty();
userService.removeNotActivatedUsers();
users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
assertThat(users).isEmpty();
}
@Test
@Transactional
public void assertThatAnonymousUserIsNotGet() {
user.setLogin(Constants.ANONYMOUS_USER);
if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) {
userRepository.saveAndFlush(user);
}
final PageRequest pageable = new PageRequest(0, (int) userRepository.count());
final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable);
assertThat(allManagedUsers.getContent().stream()
.noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin())))
.isTrue();
}
@Test
@Transactional
public void testRemoveNotActivatedUsers() {
user.setActivated(false);
userRepository.saveAndFlush(user);
// Let the audit first set the creation date but then update it
user.setCreatedDate(Instant.now().minus(30, ChronoUnit.DAYS));
userRepository.saveAndFlush(user);
assertThat(userRepository.findOneByLogin("johndoe")).isPresent();
userService.removeNotActivatedUsers();
assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent();
}
}
|
[
"[email protected]"
] | |
60b70dbbdffd8c74d7b04951b39d971790c1ae0d
|
4f96aef6e59606082b79054db63e9d0310cdda8c
|
/src/main/java/sc/fiji/kappa/gui/KappaMenuBar.java
|
c3f1d4378dfb27bd904ec1550b7942da0c8ce361
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
abab219/Kappa
|
c012c50f011ba03a600227a392b0be0c5e07b227
|
83f6b541009d127b7dc93e3ea5be977564f303ea
|
refs/heads/master
| 2020-09-23T17:18:59.337048 | 2019-11-22T19:02:54 | 2019-11-22T19:02:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 30,237 |
java
|
/*
* #%L
* A Fiji plugin for Curvature Analysis.
* %%
* Copyright (C) 2016 - 2017 Gary Brouhard
* %%
* 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.
* #L%
*/
package sc.fiji.kappa.gui;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.io.FilenameUtils;
import org.scijava.Context;
import org.scijava.convert.ConvertService;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import ij.IJ;
import ij.ImagePlus;
import ij.gui.PolygonRoi;
import ij.gui.Roi;
import ij.plugin.ChannelSplitter;
import ij.plugin.frame.RoiManager;
import net.imagej.display.ImageDisplay;
import net.imagej.display.ImageDisplayService;
import sc.fiji.kappa.curve.BSpline;
import sc.fiji.kappa.curve.Curve;
public class KappaMenuBar extends JMenuBar {
private static final long serialVersionUID = 1L;
public static final int DEFAULT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
// X axis parameterization for histograms
// 0 = Parameterized by X-Coordinate
// 1 = Parameterized by Arc Length
// 2 = Parameterized by Point Index
public static final int DEFAULT_DISTRIBUTION_DISPLAY = 2;
public static int distributionDisplay;
@Parameter
private LogService log;
// File handlers
private File file;
private JFileChooser kappaOpen;
private JFileChooser kappaLoad;
private JFileChooser kappaSave;
// Menu Items
private JMenuItem[] toolMenuItems = new JMenuItem[ToolPanel.NO_TOOLS];
private JMenuItem zoomIn;
private JMenuItem zoomOut;
private JMenuItem prevFrame, nextFrame, prevKeyframe, nextKeyframe;
private JMenuItem adjustBrightnessContrast;
private JMenuItem delete, enter, fit;
private JCheckBoxMenuItem boundingBoxMenu;
private JCheckBoxMenuItem scaleCurvesMenu;
private JCheckBoxMenuItem antialiasingMenu;
private JCheckBoxMenuItem tangentMenu;
private KappaFrame frame;
/**
* Creates a menu-bar and adds menu items to it
*/
public KappaMenuBar(Context context, KappaFrame frame) {
context.inject(this);
this.frame = frame;
// File chooser for curve data
FileNameExtensionFilter kappaFilter = new FileNameExtensionFilter("Kappa Files", "kapp");
kappaLoad = new JFileChooser();
kappaLoad.setFileFilter(kappaFilter);
kappaLoad.setDialogTitle("Load Existing Curve Data");
kappaSave = new JFileChooser();
kappaSave.setFileFilter(kappaFilter);
kappaSave.setDialogTitle("Save Curve Data");
// Declares the file menu
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
/*
* // Menu Items for file operations // Creates a new file chooser. Same native
* image support as ImageJ since ImageJ // libraries are used. kappaOpen = new
* JFileChooser(); FileNameExtensionFilter filter = new
* FileNameExtensionFilter("Image Files", "tif", "tiff", "jpeg", "jpg", "bmp",
* "fits", "pgm", "ppm", "pbm", "gif", "png", "dic", "dcm", "dicom", "lsm",
* "avi"); kappaOpen.setFileFilter(filter);
*
* JMenuItem openMenu = new JMenuItem("Open Image File");
* openMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, DEFAULT_MASK));
* openMenu.addActionListener(e -> { int returnVal =
* kappaOpen.showOpenDialog(this.frame); if (returnVal ==
* JFileChooser.APPROVE_OPTION) { openImageFile(kappaOpen.getSelectedFile()); }
* }); fileMenu.add(openMenu);
*/
JMenuItem openActiveMenu = new JMenuItem("Open Active Image");
openActiveMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, DEFAULT_MASK));
openActiveMenu.addActionListener(e -> {
openActiveImage(context);
});
fileMenu.add(openActiveMenu);
fileMenu.addSeparator();
JMenuItem importROIsAsCurvesMenu = new JMenuItem("Import ROIs as curves");
importROIsAsCurvesMenu.addActionListener(e -> {
importROIsAsCurves(context);
});
fileMenu.add(importROIsAsCurvesMenu);
fileMenu.addSeparator();
JMenuItem loadMenu = new JMenuItem("Load Curve Data");
loadMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, DEFAULT_MASK));
loadMenu.addActionListener(e -> {
// Handle open button action.
int returnVal = kappaLoad.showOpenDialog(this.frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = kappaLoad.getSelectedFile();
loadCurveFile(file);
}
});
fileMenu.add(loadMenu);
JMenuItem saveMenu = new JMenuItem("Save Curve Data");
saveMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, DEFAULT_MASK));
saveMenu.addActionListener(e -> {
String dirPath = frame.getImageStack().getOriginalFileInfo().directory;
if (dirPath != null) {
String kappaPath = FilenameUtils.removeExtension(frame.getImageStack().getOriginalFileInfo().fileName);
kappaPath += ".kapp";
File fullPath = new File(dirPath, kappaPath);
kappaSave.setSelectedFile(fullPath);
}
// Handles save button action.
int returnVal = kappaSave.showSaveDialog(this.frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = kappaSave.getSelectedFile();
// Appends a .kapp
if (!file.getPath().toLowerCase().endsWith(".kapp")) {
file = new File(file.getPath() + ".kapp");
}
saveCurveFile(file);
}
});
fileMenu.add(saveMenu);
this.add(fileMenu);
// Menu Items for all the tools
JMenu toolMenu = new JMenu("Tools");
for (int i = 0; i < ToolPanel.NO_TOOLS; i++) {
toolMenuItems[i] = new JMenuItem(ToolPanel.TOOL_MENU_NAMES[i]);
toolMenuItems[i].setEnabled(false);
toolMenuItems[i].setAccelerator(KeyStroke.getKeyStroke(ToolPanel.TOOL_MNEMONICS[i], 0));
final int j = i;
toolMenuItems[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
frame.getToolPanel().setSelected(j, true);
frame.getScrollPane().setCursor(ToolPanel.TOOL_CURSORS[j]);
}
});
toolMenu.add(toolMenuItems[i]);
}
// We also add a menu item for deleting Bezier Curves via the Backspace key.
setDelete(new JMenuItem("Delete Curves"));
getDelete().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
frame.deleteCurve();
}
});
getDelete().setEnabled(false);
getDelete().setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
toolMenu.addSeparator();
toolMenu.add(getDelete());
setEnter(new JMenuItem("Enter Curve"));
getEnter().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
frame.enterCurve();
}
});
getEnter().setEnabled(false);
getEnter().setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
toolMenu.add(getEnter());
fit = new JMenuItem("Fit Curve");
fit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
frame.fitCurves();
}
});
fit.setEnabled(false);
fit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, 0));
toolMenu.add(fit);
toolMenu.addSeparator();
// TODO remove this later
// JMenuItem runTestScript = new JMenuItem ("Run Testing Script");
// runTestScript.addActionListener (new ActionListener(){
// public void actionPerformed (ActionEvent event){
// try{frame.testingScript();}
// catch(IOException e){System.out.println("Script Error");}
// }});
// runTestScript.setAccelerator (KeyStroke.getKeyStroke(KeyEvent.VK_S, 0));
// toolMenu.add(runTestScript);
JCheckBoxMenuItem toggleCtrlPtAdjustment = new JCheckBoxMenuItem("Enable Control Point Adjustment");
toggleCtrlPtAdjustment.setState(frame.isEnableCtrlPtAdjustment());
toggleCtrlPtAdjustment.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.setEnableCtrlPtAdjustment(!frame.isEnableCtrlPtAdjustment());
;
}
});
toggleCtrlPtAdjustment.setEnabled(true);
toolMenu.add(toggleCtrlPtAdjustment);
this.add(toolMenu);
// Navigation Menu
// TODO FIX action listeners to these.
JMenu navigateMenu = new JMenu("Navigate");
prevFrame = new JMenuItem("Previous Frame");
nextFrame = new JMenuItem("Next Frame");
prevKeyframe = new JMenuItem("Previous Keyframe");
nextKeyframe = new JMenuItem("Next Keyframe");
prevFrame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, ActionEvent.ALT_MASK));
nextFrame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, ActionEvent.ALT_MASK));
prevKeyframe.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, DEFAULT_MASK));
nextKeyframe.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, DEFAULT_MASK));
prevFrame.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
frame.getControlPanel().getCurrentLayerSlider()
.setValue(Math.max(frame.getControlPanel().getCurrentLayerSlider().getValue() - 1,
frame.getControlPanel().getCurrentLayerSlider().getMinimum()));
}
});
nextFrame.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
frame.getControlPanel().getCurrentLayerSlider()
.setValue(Math.min(frame.getControlPanel().getCurrentLayerSlider().getValue() + 1,
frame.getControlPanel().getCurrentLayerSlider().getMaximum()));
}
});
prevKeyframe.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
}
});
nextKeyframe.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
}
});
prevFrame.setEnabled(false);
nextFrame.setEnabled(false);
prevKeyframe.setEnabled(false);
nextKeyframe.setEnabled(false);
navigateMenu.add(prevFrame);
navigateMenu.add(nextFrame);
navigateMenu.add(prevKeyframe);
navigateMenu.add(nextKeyframe);
this.add(navigateMenu);
// Image options.
JMenu imageMenu = new JMenu("Image");
// Brightness and Contrast tool. Taken from ImageJ.
adjustBrightnessContrast = new JMenuItem("Adjust Brightness/Contrast");
adjustBrightnessContrast.setEnabled(false);
adjustBrightnessContrast.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ContrastAdjuster c = new ContrastAdjuster(frame);
c.run("Brightness/Contrast...[C]");
}
});
imageMenu.add(adjustBrightnessContrast);
this.add(imageMenu);
// Zoom-In and Zoom-Out Commands
JMenu viewMenu = new JMenu("View");
zoomIn = new JMenuItem("Zoom In");
zoomOut = new JMenuItem("Zoom Out");
zoomIn.addActionListener(new ZoomInListener(frame.getControlPanel()));
zoomOut.addActionListener(new ZoomOutListener(frame.getControlPanel()));
zoomIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, DEFAULT_MASK));
zoomOut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, DEFAULT_MASK));
zoomIn.setEnabled(false);
zoomOut.setEnabled(false);
// Menu Item for showing bounding boxes
setBoundingBoxMenu(new JCheckBoxMenuItem("Show Bounding Boxes"));
getBoundingBoxMenu().setState(false);
getBoundingBoxMenu().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent a) {
frame.drawImageOverlay();
}
});
getBoundingBoxMenu().setEnabled(false);
// Menu Item for choosing the x-axis values for the curvature and intensity
// display
// For instance, you can display x vs. curvature, or current arc length vs
// curvature, or the point index vs curvature
// The default is the point index.
distributionDisplay = DEFAULT_DISTRIBUTION_DISPLAY;
JMenu xAxisSubmenu = new JMenu("Curve Distribution X-Axis:");
ButtonGroup xAxisGroup = new ButtonGroup();
JMenuItem xValue = new JCheckBoxMenuItem("X-Coordinate");
JMenuItem curveLength = new JCheckBoxMenuItem("Arc Length");
JMenuItem pointIndex = new JCheckBoxMenuItem("Point Index");
xAxisGroup.add(xValue);
xAxisGroup.add(curveLength);
xAxisGroup.add(pointIndex);
xAxisSubmenu.add(xValue);
xAxisSubmenu.add(curveLength);
xAxisSubmenu.add(pointIndex);
xValue.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent a) {
distributionDisplay = 0;
frame.getInfoPanel().updateHistograms();
}
});
curveLength.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent a) {
distributionDisplay = 1;
frame.getInfoPanel().updateHistograms();
}
});
pointIndex.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent a) {
distributionDisplay = 2;
frame.getInfoPanel().updateHistograms();
}
});
if (DEFAULT_DISTRIBUTION_DISPLAY == 0) {
xValue.setSelected(true);
} else if (DEFAULT_DISTRIBUTION_DISPLAY == 1) {
curveLength.setSelected(true);
} else {
pointIndex.setSelected(true);
}
// Menu Item for scaling curve strokes when zooming in or out
setScaleCurvesMenu(new JCheckBoxMenuItem("Scale Curve Strokes"));
getScaleCurvesMenu().setState(true);
getScaleCurvesMenu().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent a) {
frame.drawImageOverlay();
}
});
getScaleCurvesMenu().setEnabled(false);
// Menu Item for image antialiasing
setAntialiasingMenu(new JCheckBoxMenuItem("Enable Antialiasing"));
getAntialiasingMenu().setState(false);
getAntialiasingMenu().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent a) {
frame.setScaledImage(frame.getControlPanel().getScaleSlider().getValue() / 100.0);
frame.drawImageOverlay();
}
});
getAntialiasingMenu().setEnabled(false);
// Menu Item for displaying tangent and normal curves.
setTangentMenu(new JCheckBoxMenuItem("Show Tangent and Normal Vectors"));
getTangentMenu().setState(false);
getTangentMenu().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent a) {
frame.drawImageOverlay();
}
});
getTangentMenu().setEnabled(false);
viewMenu.add(zoomIn);
viewMenu.add(zoomOut);
viewMenu.addSeparator();
viewMenu.add(xAxisSubmenu);
viewMenu.addSeparator();
viewMenu.add(getScaleCurvesMenu());
viewMenu.add(getTangentMenu());
viewMenu.add(getBoundingBoxMenu());
viewMenu.add(getAntialiasingMenu());
this.add(viewMenu);
// Sets a "Help" menu list
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
// Adds an "About" option to the menu list
JMenuItem aboutMenuItem = new JMenuItem("About...", 'A');
aboutMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(frame, "Developed by the Brouhard lab, 2016-2017.",
KappaFrame.APPLICATION_NAME, JOptionPane.INFORMATION_MESSAGE);
}
});
// Adds a link to the User Manual
JMenuItem userManualLink = new JMenuItem("User Manual");
userManualLink.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(
new URI("https://dl.dropboxusercontent.com/u/157117/KappaFrame%20User%20Manual.pdf"));
}
} catch (Exception e) {
System.out.println("Incorrect URL Syntax");
}
;
}
});
// Adds all newly created menu items to the "Help" list
helpMenu.add(userManualLink);
helpMenu.add(aboutMenuItem);
this.add(helpMenu);
}
private void importROIsAsCurves(Context context) {
RoiManager rm = RoiManager.getInstance();
if (rm == null) {
log.warn("RoiManager is empty. No curves imported.");
return;
}
Roi[] rois = rm.getRoisAsArray();
Roi roi;
PolygonRoi polygonRoi;
List<Point2D> points;
float x;
float y;
for (int i = 0; i < rois.length; i++) {
roi = rois[i];
if (roi.getTypeAsString().equals("Polyline")) {
polygonRoi = (PolygonRoi) roi;
if (polygonRoi.getXCoordinates().length < 4) {
log.warn("Polyline needs at least 4 points.");
return;
}
points = new ArrayList<>();
for (int j = 0; j < polygonRoi.getFloatPolygon().xpoints.length; j++) {
x = polygonRoi.getFloatPolygon().xpoints[j];
y = polygonRoi.getFloatPolygon().ypoints[j];
points.add(new Point2D.Double(x, y));
}
// Enters a new Bezier Curve or B-Spline when the user presses ENTER
if (frame.getInputType() == KappaFrame.B_SPLINE) {
frame.getCurves().addCurve(points, frame.getControlPanel().getCurrentLayerSlider().getValue(),
points.size(), KappaFrame.B_SPLINE, (frame.getBsplineType() == BSpline.OPEN),
(Integer) (frame.getInfoPanel().getThresholdRadiusSpinner().getValue()));
} else {
frame.getCurves().addCurve(points, frame.getControlPanel().getCurrentLayerSlider().getValue(),
points.size(), KappaFrame.BEZIER_CURVE, true,
(Integer) (frame.getInfoPanel().getThresholdRadiusSpinner().getValue()));
}
// Updates our list after adding the curve
frame.getInfoPanel().getListData().addElement(" CURVE " + frame.getCurves().getCount());
frame.getInfoPanel().getList().setListData(frame.getInfoPanel().getListData());
//
}
}
frame.getInfoPanel().getList().setSelectedIndex(frame.getCurves().size() - 1);
frame.getInfoPanel().getCurvesList().revalidate();
frame.getInfoPanel().getPointSlider().setEnabled(true);
frame.getInfoPanel().getPointSlider().setValue(0);
frame.setCurrCtrlPt(0);
frame.getKappaMenubar().getEnter().setEnabled(false);
frame.drawImageOverlay();
}
public void openImageFile(String file) {
openImageFile(new File(file));
}
public void openImageFile(File file) {
ImagePlus imp = new ImagePlus(file.getPath());
openImage(imp);
}
public void openActiveImage(Context context) {
ImageDisplayService imds = context.getService(ImageDisplayService.class);
ConvertService convert = context.getService(ConvertService.class);
ImageDisplay imd = imds.getActiveImageDisplay();
ImagePlus imp = convert.convert(imd, ImagePlus.class);
openImage(imp);
}
public void openImage(ImagePlus imp) {
frame.setImageStack(imp);
// Splits the image into the R, G, and B channels, but only if the image is in
// RGB color
if (frame.getImageStack().getType() == ImagePlus.COLOR_RGB) {
frame.setImageStackLayers(ChannelSplitter.splitRGB(frame.getImageStack().getImageStack(), true));
}
// Sets the displayed Image Stack to all the channels to begin with.
frame.setDisplayedImageStack(frame.getImageStack());
frame.getImageStack().setDisplayMode(IJ.COMPOSITE);
frame.setMaxLayer(frame.getNFrames());
frame.setMaxLayerDigits(Integer.toString(frame.getMaxLayer()).length());
frame.getControlPanel().getCurrentLayerSlider().setValue(frame.getINIT_LAYER());
frame.getControlPanel().getCurrentLayerSlider().setMaximum(frame.getMaxLayer());
frame.getControlPanel().getCurrentLayerSlider().setMajorTickSpacing(frame.getNFrames() / 10);
frame.getControlPanel().getCurrentLayerSlider().setPaintTicks(true);
frame.getControlPanel().getCurrentLayerSlider().setEnabled(true);
frame.getControlPanel().getScaleSlider().setEnabled(true);
// Sets the maximum intensity depending on the bit depth of the image.
if (frame.isImageRGBColor()) {
frame.getInfoPanel().getDataThresholdSlider().setMaximum(256);
} else {
frame.getInfoPanel().getDataThresholdSlider()
.setMaximum((int) (Math.pow(2, frame.getDisplayedImageStack().getBitDepth())));
}
// Reset channel buttons
for (int i = 0; i < 3; i++) {
frame.getControlPanel().getChannelButtons()[i].setEnabled(false);
frame.getControlPanel().getChannelButtons()[i].setSelected(false);
}
// Sets the buttons to active and selected if the image type is a Color one.
// Otherwise sets them to inactive
if (frame.getImageStack().getNChannels() > 1) {
for (int i = 0; i < frame.getImageStack().getNChannels(); i++) {
frame.getControlPanel().getChannelButtons()[i].setEnabled(true);
frame.getControlPanel().getChannelButtons()[i].setSelected(true);
}
}
// Sets the scroll pane in the drawing panel to display the first layer of the
// image now
frame.setFrame(1);
frame.setCurrImage(frame.getDisplayedImageStack().getBufferedImage());
frame.getCurrImageLabel().setIcon(new ImageIcon(frame.getCurrImage()));
frame.setThresholded(new boolean[frame.getCurrImage().getWidth()][frame.getCurrImage().getHeight()]);
// Sets the maximum scale to a value that prevents a heap space error from
// occuring.
// We set the maximum image size to about 2000 x 2000 pixels = 4,000,000 pixels.
int avgPixelDim = (frame.getCurrImage().getWidth() + frame.getCurrImage().getHeight()) / 2;
frame.getControlPanel().getScaleSlider().setValue(ControlPanel.DEFAULT_SCALE);
frame.getControlPanel().getScaleSlider()
.setMaximum(Math.min(ControlPanel.MAX_SCALE, ControlPanel.MAX_AVG_PIXEL_DIM / avgPixelDim * 100));
this.frame.updateThresholded();
frame.getInfoPanel().getThresholdChannelsComboBox().setEnabled(true);
frame.getInfoPanel().getThresholdSlider().setEnabled(true);
frame.getInfoPanel().getRangeAveragingSpinner().setEnabled(true);
frame.getInfoPanel().getBgCheckBox().setEnabled(true);
frame.getInfoPanel().getApply().setEnabled(true);
frame.getInfoPanel().getRevert().setEnabled(true);
fit.setEnabled(true);
// Enables view checkboxes
getBoundingBoxMenu().setEnabled(true);
getScaleCurvesMenu().setEnabled(true);
getAntialiasingMenu().setEnabled(true);
getTangentMenu().setEnabled(true);
// Enables toolbar buttons and selects the direct selection tool
frame.getToolPanel().enableAllButtons();
// Enables Menu Items
zoomIn.setEnabled(true);
zoomOut.setEnabled(true);
for (JMenuItem menuItem : toolMenuItems) {
menuItem.setEnabled(true);
}
prevFrame.setEnabled(true);
nextFrame.setEnabled(true);
prevKeyframe.setEnabled(true);
nextKeyframe.setEnabled(true);
adjustBrightnessContrast.setEnabled(true);
// Adds file name to the frame.
this.frame.setTitle(KappaFrame.APPLICATION_NAME + "- " + imp.getTitle());
// Load Kappa file if available
if (imp.getOriginalFileInfo() != null) {
String dirPath = imp.getOriginalFileInfo().directory;
if (dirPath != null) {
String kappaPath = FilenameUtils.removeExtension(imp.getOriginalFileInfo().fileName);
kappaPath += ".kapp";
File fullPath = new File(dirPath, kappaPath);
if (fullPath.exists()) {
loadCurveFile(fullPath);
}
}
}
}
public void loadCurveFile(String file) {
loadCurveFile(new File(file));
}
public void loadCurveFile(File file) {
// Tries opening the file
try {
this.frame.resetCurves();
BufferedReader in = new BufferedReader(new FileReader(file));
int noCurves = Integer.parseInt(in.readLine());
for (int n = 0; n < noCurves; n++) {
int curveType = Integer.parseInt(in.readLine());
int noKeyframes = Integer.parseInt(in.readLine());
int noCtrlPts = Integer.parseInt(in.readLine());
int bsplineType = 0;
frame.setPoints(new ArrayList<Point2D>(noCtrlPts));
// If the curve is a B-Spline, there is an extra parameter determining whether
// it's open or closed
if (curveType == KappaFrame.B_SPLINE) {
bsplineType = Integer.parseInt(in.readLine());
}
// Initialize the curve
int currentKeyframe = Integer.parseInt(in.readLine());
for (int i = 0; i < noCtrlPts; i++) {
frame.getPoints().add(
new Point2D.Double(Double.parseDouble(in.readLine()), Double.parseDouble(in.readLine())));
}
if (curveType == KappaFrame.B_SPLINE) {
frame.getCurves().addCurve(frame.getPoints(), currentKeyframe, noCtrlPts, KappaFrame.B_SPLINE,
bsplineType == BSpline.OPEN,
(Integer) (frame.getInfoPanel().getThresholdRadiusSpinner().getValue()));
} else {
frame.getCurves().addCurve(frame.getPoints(), currentKeyframe, noCtrlPts, KappaFrame.BEZIER_CURVE, true,
(Integer) (frame.getInfoPanel().getThresholdRadiusSpinner().getValue()));
}
frame.getInfoPanel().getListData().addElement(" CURVE " + frame.getCurves().getCount());
frame.getInfoPanel().getList().setListData(frame.getInfoPanel().getListData());
// Load all the other keyframes for the curve
for (int i = 1; i < noKeyframes; i++) {
currentKeyframe = Integer.parseInt(in.readLine());
frame.setPoints(new ArrayList<Point2D>(noCtrlPts));
// Adds the control points for each keyframe. We add the redundant control
// points for closed B-Spline curves.
if (bsplineType == BSpline.OPEN) {
for (int j = 0; j < noCtrlPts; j++) {
frame.getPoints().add(new Point2D.Double(Double.parseDouble(in.readLine()),
Double.parseDouble(in.readLine())));
}
} else {
for (int j = 0; j < noCtrlPts - BSpline.B_SPLINE_DEGREE; j++) {
frame.getPoints().add(new Point2D.Double(Double.parseDouble(in.readLine()),
Double.parseDouble(in.readLine())));
}
for (int j = 0; j < BSpline.B_SPLINE_DEGREE; j++) {
frame.getPoints().add(new Point2D.Double(frame.getPoints().get(i).getX(),
frame.getPoints().get(i).getY()));
}
}
frame.getCurves().get(frame.getCurves().size() - 1).addKeyframe(frame.getPoints(), currentKeyframe);
}
}
// Translates all the curves to their position at the current frame.
frame.getCurves().changeFrame(frame.getControlPanel().getCurrentLayerSlider().getValue());
frame.drawImageOverlay();
in.close();
} catch (Exception err) {
// frame.overlay.setVisible(true);
// frame.overlay.drawNotification("There was an error loading the curve
// data",
// frame.scrollPane.getVisibleRect());
err.printStackTrace();
}
}
public void saveCurveFile(String file) {
saveCurveFile(new File(file));
}
public void saveCurveFile(File file) {
try {
PrintWriter out = new PrintWriter(new FileWriter(file));
out.println(frame.getCurves().size());
for (Curve c : frame.getCurves()) {
// Outputs the curve properties: it's type, the number of keyframes, the number
// of control points, etc.
if (c instanceof BSpline) {
out.println(KappaFrame.B_SPLINE);
} else {
out.println(KappaFrame.BEZIER_CURVE);
}
out.println(c.getNoKeyframes());
// Print out the correct number of control points depending on the curve type.
if (c instanceof BSpline && !((BSpline) c).isOpen()) {
out.println(c.getNoCtrlPts() - BSpline.B_SPLINE_DEGREE);
} else {
out.println(c.getNoCtrlPts());
}
if (c instanceof BSpline) {
if (((BSpline) c).isOpen()) {
out.println(BSpline.OPEN);
} else {
out.println(BSpline.CLOSED);
}
}
// Writes the control points and what keyframe they are at for each curve.
for (Curve.BControlPoints b : c.getKeyframes()) {
out.println(b.t);
// If it's a closed B-Spline, we don't output the last redundant points that
// make it closed
if (c instanceof BSpline && !((BSpline) c).isOpen()) {
for (int i = 0; i < b.defPoints.length - BSpline.B_SPLINE_DEGREE; i++) {
Point2D p = b.defPoints[i];
out.println(p.getX());
out.println(p.getY());
}
} // Otherwise, we output all the points
else {
for (Point2D p : b.defPoints) {
out.println(p.getX());
out.println(p.getY());
}
}
}
}
out.close();
} catch (Exception err) {
frame.getOverlay().setVisible(true);
frame.getOverlay().drawNotification("There was an error saving the curve data",
frame.getScrollPane().getVisibleRect());
}
}
public JMenuItem getDelete() {
return delete;
}
public JMenuItem getEnter() {
return enter;
}
public void setDelete(JMenuItem delete) {
this.delete = delete;
}
public void setEnter(JMenuItem enter) {
this.enter = enter;
}
public JCheckBoxMenuItem getTangentMenu() {
return tangentMenu;
}
public void setTangentMenu(JCheckBoxMenuItem tangentMenu) {
this.tangentMenu = tangentMenu;
}
public JCheckBoxMenuItem getScaleCurvesMenu() {
return scaleCurvesMenu;
}
public void setScaleCurvesMenu(JCheckBoxMenuItem scaleCurvesMenu) {
this.scaleCurvesMenu = scaleCurvesMenu;
}
public JCheckBoxMenuItem getBoundingBoxMenu() {
return boundingBoxMenu;
}
public void setBoundingBoxMenu(JCheckBoxMenuItem boundingBoxMenu) {
this.boundingBoxMenu = boundingBoxMenu;
}
public JCheckBoxMenuItem getAntialiasingMenu() {
return antialiasingMenu;
}
public void setAntialiasingMenu(JCheckBoxMenuItem antialiasingMenu) {
this.antialiasingMenu = antialiasingMenu;
}
}
|
[
"[email protected]"
] | |
b1d354c9dd7f7491891fed853fa7a63965e749a4
|
049447054ab829767e77857bba3676b585a6bb6a
|
/sdk/src/main/java/cn/egame/terminal/net/core/TubeResponse.java
|
77d8cb5aca9e62da79fca92b40ec593d6a39fa94
|
[] |
no_license
|
LionelWei/egame.terminal.net
|
da3e131714eaf893999c31bd6d79ed6df5c0307c
|
a520e1bdb3e4e48bae17f6ff59610a2d7a03b713
|
refs/heads/master
| 2021-01-21T14:43:19.981053 | 2017-08-03T15:18:41 | 2017-08-03T15:19:37 | 58,254,647 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 468 |
java
|
package cn.egame.terminal.net.core;
/*
* FileName: TubeResponse.java
* Copyright: 炫彩互动网络科技有限公司
* Author: weilai
* Description: 参照OkHttp的Response, 设计独立于协议栈的response接口
* History: 10/23/16 1.00 初始版本
*/
import java.io.InputStream;
public interface TubeResponse {
String header(String name);
int code();
String getString();
InputStream getStream();
void close();
}
|
[
"[email protected]"
] | |
6502960bf36383ab1a852f1ed5816f07024f7027
|
95cf13174ad285ffe0ef7f52f6c4523516779bf0
|
/src/test/java/com/okta/developer/reactive/ReactiveServiceApplicationTests.java
|
1fa43b9c8426e379bc2325d7c028cbe292ce42bd
|
[] |
no_license
|
indiepopart/reactive-service
|
6acc2930e1ddb2ec9ccf4f03cec6d14a46e8ad01
|
e66468195fc38707ccbc8fb98b3314793ea6465d
|
refs/heads/main
| 2023-07-11T10:14:08.211247 | 2021-08-02T23:17:11 | 2021-08-02T23:17:11 | 390,938,283 | 0 | 1 | null | null | null | null |
UTF-8
|
Java
| false | false | 228 |
java
|
package com.okta.developer.reactive;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ReactiveServiceApplicationTests {
@Test
void contextLoads() {
}
}
|
[
"[email protected]"
] | |
5d4caa2b96a44c2b8405380bcfdb06661d80afb0
|
42a450e45a2c6b56d8effec12cbee7e6b443fd77
|
/casos_de_estudio/proyectoSerializaSocketsDos/proyectoServidor/servidorTCP.java
|
aea58ed16f6fd21d0c0ee0258c2a8fbc38d8b57a
|
[] |
no_license
|
jegiraldp/distribuida
|
8110e8e3f76d62094e648537025ab7be4de3a500
|
fd8a3e183e06c4dcb242b9ba8e9067e398d378e6
|
refs/heads/master
| 2020-04-09T00:13:55.959193 | 2018-11-30T17:47:08 | 2018-11-30T17:47:08 | 159,858,357 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,182 |
java
|
import java.net.*;
import java.io.*;
public class servidorTCP {
static ServerSocket ss;
static Socket s;
public static void iniciar() throws IOException{
ss = new ServerSocket(12345,30000);
escuchar();
}//iniciar
public static void escuchar() throws IOException{
while(true){
System.out.println("Esperando cliente...");
s=ss.accept();
System.out.println(" Cliente conectado - "+s.getInetAddress());
recibir();
}//while
}//inicio
public static void recibir() throws IOException{
String cadena;
estudiante e;
try{
DataInputStream entrada = new DataInputStream(s.getInputStream());
while(true){
cadena = entrada.readUTF();
if((e=inicio.buscarE(Integer.parseInt(cadena)))!=null){
enviar(e);
}
}//while
}catch(Exception ioe){
System.out.println("Servidor-> Cliente desconectado");
escuchar();
}
}//recibir
public static void enviar(estudiante e) throws IOException{
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject(e);
System.out.println("Estudiante enviado");
}//enviar
}//clase
|
[
"[email protected]"
] | |
09398a1eb58c93ac9b9c06d7621593aedb336a02
|
e3622c6483135f17f5f2ebeae21865638757a66c
|
/turbo-rpc/src/main/java/rpc/turbo/param/MethodParamClassFactory.java
|
f02c785080fc5a5a8c525291388ca8b6cf50ed8b
|
[
"Apache-2.0"
] |
permissive
|
solerwell/turbo-rpc
|
6533697dee5a30f0773f0db7ee5e0d9f82aac817
|
49f0389a6beb370f73b85aa0d55af119360d8b54
|
refs/heads/master
| 2020-03-19T11:35:06.537496 | 2018-09-04T02:24:32 | 2018-09-04T02:24:32 | 136,463,431 | 0 | 0 |
Apache-2.0
| 2018-09-03T14:46:21 | 2018-06-07T10:49:40 |
Java
|
UTF-8
|
Java
| false | false | 6,418 |
java
|
package rpc.turbo.param;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.hash.Hashing;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtNewMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import rpc.turbo.util.concurrent.ThreadLocalStringBuilder;
public final class MethodParamClassFactory {
private static final String NOT_SUPPORT_PARAMETER_NAME_MSG = "must turn on \"Store information about method parameters (usable via reflection)\", see https://www.concretepage.com/java/jdk-8/java-8-reflection-access-to-parameter-names-of-method-and-constructor-with-maven-gradle-and-eclipse-using-parameters-compiler-argument";
private static final ConcurrentMap<Method, Class<? extends MethodParam>> methodParamClassMap = new ConcurrentHashMap<>();
/**
* 方法参数封装,用于序列化传输参数数据,其实现类会自动根据方法名称生成get/set方法,<br>
* 必须开启"Store information about method parameters (usable via reflection)"<br>
* 参考:https://www.concretepage.com/java/jdk-8/java-8-reflection-access-to-parameter-names-of-method-and-constructor-with-maven-gradle-and-eclipse-using-parameters-compiler-argument<br>
* <br>
* 方法public CompletableFuture<User> getUser(long id)
* 将会生成下面的MethodParamClass:
*
* <pre>
* public class UserService_getUser_1_6f7c1a8cf867a945306fb82a78c0a191265b9786 implements MethodParam {
* private long id;
*
* public long $param0() {
* return this.id;
* }
*
* public long getId() {
* return this.id;
* }
*
* public void setId(long id) {
* this.id = id;
* }
*
* public UserService_getUser_1_6f7c1a8cf867a945306fb82a78c0a191265b9786() {
* }
*
* public UserService_getUser_1_6f7c1a8cf867a945306fb82a78c0a191265b9786(long id) {
* this.id = id;
* }
* }
* </pre>
*
* @param method
* 方法
* @return MethodParamClass
*
* @throws CannotCompileException
* @throws NotFoundException
*
* @author Hank
*/
public static Class<? extends MethodParam> createClass(Method method)
throws CannotCompileException, NotFoundException {
Objects.requireNonNull(method, "method must not be null");
if (method.getParameterCount() == 0) {
return EmptyMethodParam.class;
}
Class<? extends MethodParam> methodParamClass = methodParamClassMap.get(method);
if (methodParamClass != null) {
return methodParamClass;
}
synchronized (MethodParamClassFactory.class) {
methodParamClass = methodParamClassMap.get(method);
if (methodParamClass != null) {
return methodParamClass;
}
methodParamClass = doCreateClass(method);
methodParamClassMap.put(method, methodParamClass);
}
return methodParamClass;
}
@SuppressWarnings("unchecked")
private static Class<? extends MethodParam> doCreateClass(Method method)
throws CannotCompileException, NotFoundException {
Class<?>[] parameterTypes = method.getParameterTypes();
Parameter[] parameters = method.getParameters();
if (!parameters[0].isNamePresent()) {
throw new RuntimeException(NOT_SUPPORT_PARAMETER_NAME_MSG);
}
String paramTypes = Stream.of(parameterTypes)//
.map(clazz -> clazz.getName())//
.collect(Collectors.joining(",", "(", ")"));
String hash = Hashing.murmur3_128().hashString(paramTypes, StandardCharsets.UTF_8).toString();
final String methodParamClassName = method.getDeclaringClass().getName()//
+ "$MethodParam"//
+ "$" + method.getName()//
+ "$" + parameterTypes.length//
+ "$" + hash;// 防止同名方法冲突
try {
Class<?> clazz = MethodParamClassFactory.class.getClassLoader().loadClass(methodParamClassName);
if (clazz != null) {
return (Class<? extends MethodParam>) clazz;
}
} catch (ClassNotFoundException e) {
}
// 创建类
ClassPool pool = ClassPool.getDefault();
CtClass methodParamCtClass = pool.makeClass(methodParamClassName);
CtClass[] interfaces = { pool.getCtClass(MethodParam.class.getName()) };
methodParamCtClass.setInterfaces(interfaces);
for (int i = 0; i < parameterTypes.length; i++) {
Parameter parameter = parameters[i];
String paramName = parameter.getName();
Class<?> paramType = parameterTypes[i];
String capitalize = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1);
String getter = "get" + capitalize;
String setter = "set" + capitalize;
CtField ctField = new CtField(pool.get(paramType.getName()), paramName, methodParamCtClass);
ctField.setModifiers(Modifier.PRIVATE);
methodParamCtClass.addField(ctField);
methodParamCtClass.addMethod(CtNewMethod.getter("$param" + i, ctField));
methodParamCtClass.addMethod(CtNewMethod.getter(getter, ctField));
methodParamCtClass.addMethod(CtNewMethod.setter(setter, ctField));
}
// 添加无参的构造函数
CtConstructor constructor0 = new CtConstructor(null, methodParamCtClass);
constructor0.setModifiers(Modifier.PUBLIC);
constructor0.setBody("{}");
methodParamCtClass.addConstructor(constructor0);
// 添加有参的构造函数
CtClass[] paramCtClassArray = new CtClass[method.getParameterCount()];
for (int i = 0; i < method.getParameterCount(); i++) {
Class<?> paramType = parameterTypes[i];
CtClass paramCtClass = pool.get(paramType.getName());
paramCtClassArray[i] = paramCtClass;
}
StringBuilder bodyBuilder = ThreadLocalStringBuilder.current();
bodyBuilder.append("{\r\n");
for (int i = 0; i < method.getParameterCount(); i++) {
String paramName = parameters[i].getName();
bodyBuilder.append("$0.");
bodyBuilder.append(paramName);
bodyBuilder.append(" = $");
bodyBuilder.append(i + 1);
bodyBuilder.append(";\r\n");
}
bodyBuilder.append("}");
CtConstructor constructor1 = new CtConstructor(paramCtClassArray, methodParamCtClass);
constructor1.setBody(bodyBuilder.toString());
methodParamCtClass.addConstructor(constructor1);
return (Class<? extends MethodParam>) methodParamCtClass.toClass();
}
}
|
[
"[email protected]"
] | |
9dc16b0728f54a83175559195891f4924e9b4890
|
a8fa344743ecce5f80f4dad8eabfd8ba93f58f00
|
/反射的实例化方式 以及和工厂模式的结合/package-info.java
|
a1fa1c824aadbd63fab3c074dba12e4103f82abb
|
[] |
no_license
|
blue-heart/java_test
|
aa84069b0d2afba4af15740174291616af1c4e05
|
d25ab981a4801c5b6adccc5c5fb40ef1b54b2a01
|
refs/heads/master
| 2020-08-09T11:09:50.435466 | 2019-12-06T11:47:53 | 2019-12-06T11:47:53 | 214,074,695 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 751 |
java
|
package com.bittich2;
/*
获取class对象的3种方式
1.通过类的实例化对象getclass获取
2.通过类名.class获取
前两个 会做编译时检查 错了就是错了
第三个 不会 会在运行时加载指定的类 必须异常处理
类没有被使用 静态块不会被加载
第二个区别
第二个首次使用 会加载类的class文件到java虚拟机
并且执行静态代码块
3.通过class的静态方法forname(类的全限定名)获取
2.类的实例化对象方法
1.通过构造
2.1 通过类的class对象的newinstance方法
实例化对象 局限
2.2通过类的class对象获取constructor对象
constructor的newinstance(有参数)
有对象就能传递参数实例化对象
3.序列化 和反序列化
*/
|
[
"[email protected]"
] | |
63391994c3b2f75d9eb1450fd76b3601b00a016e
|
af41f8be17508e97e7e67c485960acf48d12adec
|
/src/test/java/br/com/stockinfo/prev/security/jwt/JWTFilterTest.java
|
19564158adf622a8c3a48ca00fce2b91c8b3bce4
|
[] |
no_license
|
christiansurf10/stockinfo
|
d6dc90b06bdb96d34ec41ad94f66177ef094e1f2
|
921828d6e510b1fef58bb8cd44df077bbee9a044
|
refs/heads/master
| 2020-04-22T20:10:04.238588 | 2019-02-13T01:16:45 | 2019-02-13T01:16:45 | 170,632,444 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,494 |
java
|
package br.com.stockinfo.prev.security.jwt;
import br.com.stockinfo.prev.security.AuthoritiesConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
public class JWTFilterTest {
private TokenProvider tokenProvider;
private JWTFilter jwtFilter;
@Before
public void setup() {
JHipsterProperties jHipsterProperties = new JHipsterProperties();
tokenProvider = new TokenProvider(jHipsterProperties);
ReflectionTestUtils.setField(tokenProvider, "key",
Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
jwtFilter = new JWTFilter(tokenProvider);
SecurityContextHolder.getContext().setAuthentication(null);
}
@Test
public void testJWTFilter() throws Exception {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"test-user",
"test-password",
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
);
String jwt = tokenProvider.createToken(authentication, false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
@Test
public void testJWTFilterInvalidToken() throws Exception {
String jwt = "wrong_jwt";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testJWTFilterMissingAuthorization() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testJWTFilterMissingToken() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer ");
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testJWTFilterWrongScheme() throws Exception {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"test-user",
"test-password",
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
);
String jwt = tokenProvider.createToken(authentication, false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
}
|
[
"[email protected]"
] | |
330588a6cbbdbe801e347a05df3ce7b21fa23e9d
|
4967ba815d36683bfbab66f717b8b9b82b2671ff
|
/DesktopUi/src/components/multipleStoresData/MultipleStoresDataConstants.java
|
7a3ff480b54fef83f38c92b3ce0cb128c201d056
|
[] |
no_license
|
alonadann/Supermarket-Management-Web
|
1b1b06a8c8b1df27dd7b0f203542cda3639c452b
|
0f766c8e63f306fef64b6c73fbfb60ceb566f5d5
|
refs/heads/master
| 2023-09-05T17:27:03.089025 | 2021-10-29T10:49:57 | 2021-10-29T10:49:57 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 304 |
java
|
package components.multipleStoresData;
public class MultipleStoresDataConstants {
private static final String BASE_PACKAGE= "/components/multipleStoresData"; //todo : ok with jar ?
public static final String STORES_DATA_FXML_RESOURCE_IDENTIFIER = BASE_PACKAGE + "/multipleStoresData.fxml";
}
|
[
"[email protected]"
] | |
59f1551329656eeff3dfc279b1d6910c22de2a80
|
f72ef8fc9d2c78bab604e96186cbaf218c631d44
|
/mat/src/main/java/mat/shared/RadioButtonGroupCell.java
|
490fa16171fb2598fee543388dc24edde420213a
|
[
"LicenseRef-scancode-free-unknown",
"CC0-1.0",
"Apache-2.0"
] |
permissive
|
MeasureAuthoringTool/MeasureAuthoringTool_LatestSprint
|
77d2047405d55d8b1466b17f57bca1a6c9b6d74d
|
71bf83060239e1c6e99a041c43b351e7ed6b4815
|
refs/heads/master
| 2021-01-25T15:56:22.149610 | 2019-12-10T17:13:34 | 2019-12-10T17:13:34 | 14,151,459 | 7 | 6 |
Apache-2.0
| 2019-12-10T17:13:36 | 2013-11-05T19:24:31 |
JavaScript
|
UTF-8
|
Java
| false | false | 5,043 |
java
|
package mat.shared;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.google.gwt.cell.client.AbstractInputCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
/**
* The Class RadioButtonGroupCell.
*/
public class RadioButtonGroupCell extends AbstractInputCell<String, String> {
/**
* The Interface Template.
*/
interface Template extends SafeHtmlTemplates {
/**
* Deselected.
*
* @param choice
* the choice
* @return the safe html
*/
@Template("<input type=\"radio\" name=\"choices\" tabindex=\"-1\" value=\"{0}\" /> {0}</>")
SafeHtml deselected(String choice);
/**
* Selected.
*
* @param choice
* the choice
* @return the safe html
*/
@Template("<input type=\"radio\" name=\"choices\" tabindex=\"-1\" checked=\"checked\" value=\"{0}\" /> {0}</>")
SafeHtml selected(String choice);
}
/** The template. */
private static Template template;
/** The index for option. */
private final HashMap<String, Integer> indexForOption = new HashMap<String, Integer>();
/** The options. */
private final List<String> options;
/**
* Construct a new RadioButtonGroupCell with the specified options.
*
* @param options
* the options in the cell
*/
public RadioButtonGroupCell(List<String> options) {
super("change");
if (template == null) {
template = GWT.create(Template.class);
}
this.options = new ArrayList<String>(options);
int index = 0;
for (String option : options) {
indexForOption.put(option, index++);
}
}
/* (non-Javadoc)
* @see com.google.gwt.cell.client.AbstractInputCell#onBrowserEvent(com.google.gwt.cell.client.Cell.Context, com.google.gwt.dom.client.Element, java.lang.Object, com.google.gwt.dom.client.NativeEvent, com.google.gwt.cell.client.ValueUpdater)
*/
@Override
public void onBrowserEvent(Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
String type = event.getType();
if ("change".equals(type)) {
Object key = context.getKey();
InputElement select;
NodeList<Node> nodeList = parent.getChildNodes();
int nodesNum = nodeList.getLength();
String newValue = null;
for (int i = 0; i < nodesNum; i++) {
select = parent.getChild(i).cast();
if (select.isChecked()) {
newValue = select.getPropertyString("value");
break;
}
}
setViewData(key, newValue);
finishEditing(parent, newValue, key, valueUpdater);
if (valueUpdater != null) {
valueUpdater.update(newValue);
}
}
}
/* (non-Javadoc)
* @see com.google.gwt.cell.client.AbstractCell#render(com.google.gwt.cell.client.Cell.Context, java.lang.Object, com.google.gwt.safehtml.shared.SafeHtmlBuilder)
*/
@Override
public void render(Context context, String value, SafeHtmlBuilder sb) {
// Get the view data.
Object key = context.getKey();
String viewData = getViewData(key);
if (viewData != null && viewData.equals(value)) {
clearViewData(key);
viewData = null;
}
int selectedIndex = getSelectedIndex(viewData == null ? value : viewData);
int index = 0;
for (String option : options) {
if (index++ == selectedIndex) {
sb.append(template.selected(option));
} else {
sb.append(template.deselected(option));
}
}
}
/**
* Gets the selected index.
*
* @param value
* the value
* @return the selected index
*/
private int getSelectedIndex(String value) {
Integer index = indexForOption.get(value);
if (index == null) {
return -1;
}
return index.intValue();
}
}
|
[
"[email protected]"
] | |
e05d9c01d020daa0ffd0f2facf54bf1225a05e52
|
79a33795eed2bbf921e426fdaaf285ed4a38a68f
|
/laijie/app/build/generated/source/buildConfig/androidTest/debug/com/example/laijie/test/BuildConfig.java
|
ae986d4492bf705c59c23e28a8c076a6e175c655
|
[] |
no_license
|
bluelzx/miaobaitiao
|
d809c6cf778852998513f0ae73624567d0798ca1
|
b8be0d5256cb029fef8784069dae7704bb16ad85
|
refs/heads/master
| 2021-01-20T01:51:21.518301 | 2017-04-20T02:53:42 | 2017-04-20T02:53:42 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 453 |
java
|
/**
* Automatically generated file. DO NOT MODIFY
*/
package com.example.laijie.test;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.example.laijie.test";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 2;
public static final String VERSION_NAME = "2.0";
}
|
[
"[email protected]"
] | |
7044ff4a59755ae371b38a3fca8d384bd87fb075
|
7e1511cdceeec0c0aad2b9b916431fc39bc71d9b
|
/flakiness-predicter/input_data/original_tests/qos-ch-logback/nonFlakyMethods/ch.qos.logback.core.spi.AppenderAttachableImplLockTest-getAppenderBoom.java
|
5cac0c3e2e93a8a489f925d8bc9917b390c18211
|
[
"BSD-3-Clause"
] |
permissive
|
Taher-Ghaleb/FlakeFlagger
|
6fd7c95d2710632fd093346ce787fd70923a1435
|
45f3d4bc5b790a80daeb4d28ec84f5e46433e060
|
refs/heads/main
| 2023-07-14T16:57:24.507743 | 2021-08-26T14:50:16 | 2021-08-26T14:50:16 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 413 |
java
|
@SuppressWarnings("unchecked") @Test(timeout=5000) public void getAppenderBoom(){
Appender<Integer> mockAppender1=mock(Appender.class);
when(mockAppender1.getName()).thenThrow(new OutOfMemoryError("oops"));
aai.addAppender(mockAppender1);
try {
aai.getAppender("foo");
}
catch ( OutOfMemoryError e) {
}
Appender<Integer> mockAppender2=mock(Appender.class);
aai.addAppender(mockAppender2);
}
|
[
"[email protected]"
] | |
b8d9eacb483e0c1cabb2777616d96d02e191aa98
|
dcd728452dafe52478cee18eeb823dc27e51c9e1
|
/guice/src/example/java/org/kasource/kaevent/example/guice/custom/Thermometer.java
|
a1127eeebd2f7b7dc4e69041d321a34dbd63a519
|
[] |
no_license
|
wigforss/Ka-Event
|
261c3e16df5323f11e3a96fd7105438db7ef6840
|
48eabe1646928516fa3469f9bc6d9eea20b219d4
|
refs/heads/master
| 2023-09-02T19:26:30.624661 | 2012-12-20T17:15:48 | 2012-12-20T17:15:48 | 2,278,719 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,253 |
java
|
package org.kasource.kaevent.example.guice.custom;
import org.kasource.kaevent.event.EventDispatcher;
import org.kasource.kaevent.example.guice.custom.event.TemperatureChangeEvent;
import com.google.inject.Inject;
//CHECKSTYLE:OFF
///CLOVER:OFF
public class Thermometer implements Runnable {
private double optimalTemperatur = 22.0d;
private double currentTemperatur = 0.0d;
@Inject
private Cooler cooler;
@Inject
private Heater heater;
@Inject
private EventDispatcher eventDispatcher;
public double getOptimalTemperatur() {
return optimalTemperatur;
}
public void setOptimalTemperatur(double optimalTemperatur) {
this.optimalTemperatur = optimalTemperatur;
}
public void run() {
for (int i = 0; i < 100; ++i) {
if (cooler.isEnabled()) {
currentTemperatur -= Math.random() * 3.0d;
} else if (heater.isEnabled()) {
currentTemperatur += Math.random() * 3.0d;
} else {
currentTemperatur += 1.0d;
}
System.out.println("Temp is now: " + currentTemperatur);
eventDispatcher.fireBlocked(new TemperatureChangeEvent(this, currentTemperatur));
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
[
"[email protected]"
] | |
a247c28a14564bcd0f09ef1331b4cd4f4f9d0d82
|
3cd35a5f49caf62491988d0ccd5cb90fda51989e
|
/util_thread/src/main/java/com/zyyapp/util/cmd/ICommand.java
|
67edf0fbd154ef16ec062567e885bac0b88c53d8
|
[] |
no_license
|
zyy329/java
|
355c38614fb04f26450dbc3207e1fe773d55af9b
|
be85985b08548d97f0d6d8b6512fece8477a90d4
|
refs/heads/master
| 2022-07-11T08:09:00.084245 | 2020-08-19T07:14:15 | 2020-08-19T07:14:15 | 93,725,137 | 0 | 0 | null | 2022-06-17T03:27:20 | 2017-06-08T08:25:12 |
Java
|
UTF-8
|
Java
| false | false | 303 |
java
|
package com.zyyapp.util.cmd;
public interface ICommand {
/** 执行命令 */
void action();
/** 释放接口; */
void release();
/** 警告打印时间点 (毫秒);
* @return 超长处理 警告打印时间; 指令处理时间超过该值时, 将打印警告信息;
* */
int warnTime();
}
|
[
"[email protected]"
] | |
40fab3abc5b7faa4923d09781d6f532ebb4abe40
|
ef7dc3d3ebb047145a04dec87cb2cd0f037d9205
|
/app/src/main/java/com/example/chandra_catatatan_harian_api/FirstFragment.java
|
d9b0d251a305ea23f1187e51e8d67cdbd87a08b2
|
[] |
no_license
|
zhacary/chandra_catatan_api
|
b03f7a4bc30e19464ab7f3767744c3c2f463c251
|
b98a7585bd41e6db4c1c911092eff2799fae1d5d
|
refs/heads/master
| 2023-01-18T22:26:24.208523 | 2020-12-05T13:57:17 | 2020-12-05T13:57:17 | 317,296,146 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 5,272 |
java
|
package com.example.chandra_catatatan_harian_api;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FirstFragment extends Fragment {
View fragment_view;
ArrayList<Catatan> catatans;
ProgressBar pb;
SwipeRefreshLayout srl;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
fragment_view = rootView;
pb = (ProgressBar) rootView.findViewById(R.id.progress_horizontal);
//lookup
srl = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshLayout);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
load();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
srl.setRefreshing(false);
}
}, 1000);
}
});
srl.setColorSchemeResources(android.R.color.holo_blue_light,android.R.color.holo_green_light,
android.R.color.holo_orange_light, android.R.color.holo_red_light);
load();
return rootView;
}
public void load(){
pb.setVisibility(ProgressBar.VISIBLE);
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.getCache().clear();
String url = "https://chandrarestapi.000webhostapp.com/catatan.php";
JsonObjectRequest jsObjectRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String id, tanggal, catat;
catatans = new ArrayList<>();
try {
JSONArray jsonArray = response.getJSONArray("result");
catatans.clear();
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
id = data.getString("id").toString().trim();
tanggal = data.getString("tanggal").toString().trim();
catat = data.getString("catat").toString().trim();
catatans.add(new Catatan(id, tanggal, catat));
}
showRecyclerGrid();
}
} catch (JSONException e) {
e.printStackTrace();
}
pb.setVisibility(ProgressBar.GONE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Event :", error.toString());
pb.setVisibility(ProgressBar.GONE);
Toast.makeText(getContext(), "Please check connection", Toast.LENGTH_SHORT).show();
}
});
queue.add(jsObjectRequest);
}
private void showRecyclerGrid() {
RecyclerView recyclerView = (RecyclerView) fragment_view.findViewById(R.id.rv);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
CatatanAdapter mAdapter = new CatatanAdapter(getContext(), catatans);
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
// public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// NavHostFragment.findNavController(FirstFragment.this)
// .navigate(R.id.action_FirstFragment_to_SecondFragment);
// }
// });
// }
}
|
[
"[email protected]"
] | |
fe7a8dbbdb737a163d2aa006af7bd493244bcf09
|
dbf5adca095d04d7d069ecaa916e883bc1e5c73d
|
/x_okr_assemble_control/src/main/java/com/x/okr/assemble/control/jaxrs/okrworkbaseinfo/ExcuteDeleteForce.java
|
8dd858c1c9e05e925ab1960253a04674a172e313
|
[
"BSD-3-Clause"
] |
permissive
|
fancylou/o2oa
|
713529a9d383de5d322d1b99073453dac79a9353
|
e7ec39fc586fab3d38b62415ed06448e6a9d6e26
|
refs/heads/master
| 2020-03-25T00:07:41.775230 | 2018-08-02T01:40:40 | 2018-08-02T01:40:40 | 143,169,936 | 0 | 0 |
BSD-3-Clause
| 2018-08-01T14:49:45 | 2018-08-01T14:49:44 | null |
UTF-8
|
Java
| false | false | 3,581 |
java
|
package com.x.okr.assemble.control.jaxrs.okrworkbaseinfo;
import javax.servlet.http.HttpServletRequest;
import com.x.base.core.http.ActionResult;
import com.x.base.core.http.EffectivePerson;
import com.x.base.core.http.WrapOutId;
import com.x.base.core.logger.Logger;
import com.x.base.core.logger.LoggerFactory;
import com.x.okr.assemble.control.OkrUserCache;
import com.x.okr.assemble.control.jaxrs.okrworkbaseinfo.exception.GetOkrUserCacheException;
import com.x.okr.assemble.control.jaxrs.okrworkbaseinfo.exception.WorkBaseInfoProcessException;
import com.x.okr.assemble.control.jaxrs.okrworkbaseinfo.exception.WorkIdEmptyException;
import com.x.okr.assemble.control.service.OkrWorkBaseInfoOperationService;
import com.x.okr.entity.OkrWorkBaseInfo;
public class ExcuteDeleteForce extends ExcuteBase {
private Logger logger = LoggerFactory.getLogger( ExcuteDeleteForce.class );
private OkrWorkBaseInfoOperationService okrWorkBaseInfoOperationService = new OkrWorkBaseInfoOperationService();
protected ActionResult<WrapOutId> execute( HttpServletRequest request,EffectivePerson effectivePerson, String id ) throws Exception {
ActionResult<WrapOutId> result = new ActionResult<>();
OkrWorkBaseInfo okrWorkBaseInfo = null;
Boolean check = true;
OkrUserCache okrUserCache = null;
if( check ){
try {
okrUserCache = okrUserInfoService.getOkrUserCacheWithPersonName( effectivePerson.getName() );
} catch ( Exception e ) {
check = false;
Exception exception = new GetOkrUserCacheException( e, effectivePerson.getName() );
result.error( exception );
logger.error( e, effectivePerson, request, null);
}
}
if( check ){
if( id == null || id.isEmpty() ){
check = false;
Exception exception = new WorkIdEmptyException();
result.error( exception );
}
}
if( check ){
try{
okrWorkBaseInfo = okrWorkBaseInfoService.get( id );
}catch(Exception e){
check = false;
Exception exception = new WorkBaseInfoProcessException( e, "查询指定ID的具体工作信息时发生异常。ID:" + id );
result.error( exception );
logger.error( e, effectivePerson, request, null);
}
}
if( check ){
try{
okrWorkBaseInfoOperationService.deleteForce( id );
}catch(Exception e){
check = false;
Exception exception = new WorkBaseInfoProcessException( e, "工作删除过程中发生异常。"+id );
result.error( exception );
logger.error( e, effectivePerson, request, null);
}
}
if( check ){
if( okrWorkBaseInfo != null ){
try{
okrWorkDynamicsService.workDynamic(
okrWorkBaseInfo.getCenterId(),
okrWorkBaseInfo.getId(),
okrWorkBaseInfo.getTitle(),
"删除具体工作",
effectivePerson.getName(),
okrUserCache.getLoginUserName(),
okrUserCache.getLoginIdentityName() ,
"删除具体工作:" + okrWorkBaseInfo.getTitle(),
"具体工作删除成功!"
);
}catch(Exception e){
logger.warn( "system save work dynamic got an exception." );
logger.error( e );
}
}else{
try{
okrWorkDynamicsService.workDynamic(
"0000-0000-0000-0000",
id,
"未知",
"删除具体工作",
effectivePerson.getName(),
okrUserCache.getLoginUserName(),
okrUserCache.getLoginIdentityName() ,
"删除具体工作:未知",
"具体工作删除成功!"
);
}catch(Exception e){
logger.warn( "system save work dynamic got an exception." );
logger.error( e );
}
}
}
return result;
}
}
|
[
"[email protected]"
] | |
2052f72213cf81cebb9531739418c4a705377691
|
cd2501101cbbb48503cdf2a817e2942af32b1266
|
/jh-mono-app/src/main/java/com/dgstack/eg/jhmonoapp/security/social/CustomSignInAdapter.java
|
caa4d8b870a0a3039ef1760ff555c89df1d0bcfa
|
[] |
no_license
|
digvijaybhakuni/dgspace
|
6a556e163e836430637a190d3bc845cc04ad63bf
|
bc7844533be4649aae2beef8de8ea18abe2af2ce
|
refs/heads/master
| 2021-01-12T03:27:08.359410 | 2019-04-29T05:41:38 | 2019-04-29T05:41:38 | 78,208,670 | 1 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 2,512 |
java
|
package com.dgstack.eg.jhmonoapp.security.social;
import com.dgstack.eg.jhmonoapp.config.JHipsterProperties;
import com.dgstack.eg.jhmonoapp.security.jwt.TokenProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.SignInAdapter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.context.request.ServletWebRequest;
import javax.servlet.http.Cookie;
import javax.inject.Inject;
public class CustomSignInAdapter implements SignInAdapter {
@SuppressWarnings("unused")
private final Logger log = LoggerFactory.getLogger(CustomSignInAdapter.class);
@Inject
private UserDetailsService userDetailsService;
@Inject
private JHipsterProperties jHipsterProperties;
@Inject
private TokenProvider tokenProvider;
@Override
public String signIn(String userId, Connection<?> connection, NativeWebRequest request){
try {
UserDetails user = userDetailsService.loadUserByUsername(userId);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
user,
null,
user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
String jwt = tokenProvider.createToken(authenticationToken, false);
ServletWebRequest servletWebRequest = (ServletWebRequest) request;
servletWebRequest.getResponse().addCookie(getSocialAuthenticationCookie(jwt));
} catch (AuthenticationException exception) {
log.error("Social authentication error");
}
return jHipsterProperties.getSocial().getRedirectAfterSignIn();
}
private Cookie getSocialAuthenticationCookie(String token) {
Cookie socialAuthCookie = new Cookie("social-authentication", token);
socialAuthCookie.setPath("/");
socialAuthCookie.setMaxAge(10);
return socialAuthCookie;
}
}
|
[
"[email protected]"
] | |
daa2ee609ff581cde6aadd9cdb74dc194a2a0255
|
7948969bb631cd3a852f0756978f019194c4fac3
|
/code/activitiOA/src/test/java/com/cypher/activiti/activiti/LeaveProcessTest.java
|
ef0c22995a73ea144f88328bd1be5192dfd987fb
|
[] |
no_license
|
biliou/activitiOA
|
2e5653bc099c4ec72156b917d0aea3a6250d6d94
|
ffe9754fe35d7d774bcdf4037a98aaab604d3e01
|
refs/heads/master
| 2021-09-07T16:23:20.678873 | 2018-02-26T03:25:46 | 2018-02-26T03:25:46 | 105,358,241 | 0 | 3 | null | null | null | null |
UTF-8
|
Java
| false | false | 11,162 |
java
|
package com.cypher.activiti.activiti;
import java.util.List;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Attachment;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
@Ignore
public class LeaveProcessTest {
private ProcessEngine processEngine;
@Before
public void initProcessEngine() {
processEngine = ProcessEngineConfiguration
.createProcessEngineConfigurationFromResource("activiti/activiti.cfg.xml").buildProcessEngine();
}
/**
* 流程部署
*/
@Test
public void testLeaveProcessDeploy() {
// // 1.通过流程定义相关的接口 RepositoryService 创建部署构建器
// RepositoryService repositoryService = processEngine.getRepositoryService();
// // 流程部署和流程定义相关的服务接口
//
// DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
//
// // 2.添加资源,进行部署
// deploymentBuilder.addClasspathResource("leave.bpmn");
// deploymentBuilder.addClasspathResource("leave.png");
// deploymentBuilder.name("请假流程");
//
// // 3.进行部署
// Deployment deploy = deploymentBuilder.deploy();
// 链式
Deployment deploy = processEngine.getRepositoryService() // 流程部署和流程定义相关的服务接口
.createDeployment() // 创建部署构建器
.addClasspathResource("diagrams/leave1.bpmn") // 添加资源
.addClasspathResource("diagrams/leave1.png")// 添加资源
.name("请假流程")// 定义流程名字
.deploy();// 进行部署
System.out.println(deploy.getId());
System.out.println(deploy.getName());
}
/**
* 流程启动 涉及到的表: <br/>
* act_ru_execution 生成一条流程实例数据 <br/>
* act_ru_task 生成一条待执行的任务记录 <br/>
* act_hi_taskinst 生成一条历史任务记录,但是没有结束时间
*/
@Test
public void testStartLeaveProcess() {
String processDefinitionKey = "myProcess";
ProcessInstance processInstance = processEngine.getRuntimeService()
.startProcessInstanceByKey(processDefinitionKey);
System.out.println("流程部署ID=" + processInstance.getDeploymentId());
System.out.println("流程定义ID=" + processInstance.getProcessDefinitionId());
System.out.println("流程实例ID=" + processInstance.getProcessInstanceId());
System.out.println("流程任务ID=" + processInstance.getActivityId());
// 流程部署ID=null
// 流程定义ID=myProcess:1:47504
// 流程实例ID=50001
// 流程任务ID=usertask1
}
/**
* 流程任务执行:查询个人任务 task1 请假申请
*/
@Test
public void testQueryMyTask1() {
String processInstanceId = "50001";
// String assignee = "user2";
List<Task> taskList = processEngine.getTaskService() // 跟任务处理相关的服务类
.createTaskQuery()// 创建一个任务查询
// .taskAssignee(assignee) // 加入查询条件: 委托人
.processInstanceId(processInstanceId) // 加入查询条件: 流程实例ID
.list();
if (taskList != null && taskList.size() > 0) {
for (Task task : taskList) {
System.out.println("流程定义ID:" + task.getProcessDefinitionId());
System.out.println("流程实例ID:" + task.getProcessInstanceId());
System.out.println("执行对象ID:" + task.getExecutionId());
System.out.println("任务ID:" + task.getId());// 任务ID:10004
System.out.println("任务名称:" + task.getName());
System.out.println("任务的创建时间:" + task.getCreateTime());
}
}
}
/**
* 流程任务完成task1 请假申请
*/
@Test
public void testExecutionTask1() {
String taskId = "52502";
processEngine.getTaskService()// 跟任务处理相关的服务类
.complete(taskId); // 完成任务
System.out.println("请假申请任务完成");
}
/**
* 流程执行过程中,查询流程执行到哪一个状态
*/
@Test
public void testQueryProInstanceState() {
String processInstanceId = "5";
// String taskId = "90010";
// Task task =
// processEngine.getTaskService().createTaskQuery().taskId(taskId).singleResult();
// String processDefinitionId = task.getProcessDefinitionId();
// String processInstanceId = task.getProcessInstanceId();
ProcessInstance processInstance = processEngine.getRuntimeService() // 获取跟执行流程相关的服务类
.createProcessInstanceQuery() // 创建流程实例查询
.processInstanceId(processInstanceId) // 查询条件:实例id
.singleResult();
// 查到当前执行的任务id
if (processInstance != null) {
System.out.println("当前流程执行到:" + processInstance.getActivityId());
} else {
System.out.println("当前流程已执行结束");
}
}
/**
* 流程任务执行:查询个人任务 task2 主管审批
*/
@Test
public void testQueryMyTask2() {
String processInstanceId = "22504";
String assignee = "user2";
List<Task> taskList = processEngine.getTaskService() // 跟任务处理相关的服务类
.createTaskQuery()// 创建一个任务查询
.taskAssignee(assignee) // 加入查询条件: 委托人
.processInstanceId(processInstanceId) // 加入查询条件: 流程实例ID
.list();
if (taskList != null && taskList.size() > 0) {
for (Task task : taskList) {
System.out.println("流程定义ID:" + task.getProcessDefinitionId());
System.out.println("流程实例ID:" + task.getProcessInstanceId());
System.out.println("执行对象ID:" + task.getExecutionId());
System.out.println("任务ID:" + task.getId());// 任务ID:10004
System.out.println("任务名称:" + task.getName());
System.out.println("任务的创建时间:" + task.getCreateTime());
}
}
}
/**
* 流程任务完成task1 请假申请
*/
@Test
public void testExecutionTask2() {
String taskId = "30004";
processEngine.getTaskService()// 跟任务处理相关的服务类
.complete(taskId); // 完成任务
System.out.println("审批任务完成");
}
/**
* 流程任务完成,查看历史记录<br/>
* act_ru_task 中记录会被删除<br/>
* act_hi_taskinst 记录的endtime会加上<br/>
* act_hi_procinst 记录的endtime会加上<br/>
*/
@Test
public void testQueryMyTaskComplate() {
String processInstanceId = "5";
List<HistoricTaskInstance> historicTaskInstancesList = processEngine.getHistoryService() // 跟任务历史相关的服务类
.createHistoricTaskInstanceQuery()// 创建一个任务历史查询
.processInstanceId(processInstanceId)// 加入查询条件: 流程实例ID
.list();
if (historicTaskInstancesList != null && historicTaskInstancesList.size() > 0) {
for (HistoricTaskInstance hisTask : historicTaskInstancesList) {
System.out.println("流程任务ID:" + hisTask.getId());
System.out.println("流程任务执行者:" + hisTask.getAssignee());
System.out.println("流程任务id:" + hisTask.getTaskDefinitionKey());
System.out.println("流程任务开始时间:" + hisTask.getCreateTime());
System.out.println("流程任务结束时间:" + hisTask.getEndTime());
System.out.println("-----------------------------------");
}
}
// 查询任务历史中最新的一条
HistoricProcessInstance hisTask = processEngine.getHistoryService() // 跟任务历史相关的服务类
.createHistoricProcessInstanceQuery()// 创建一个任务历史查询
.processInstanceId(processInstanceId)// 加入查询条件: 流程实例ID
.singleResult();
System.out.println("-----查询任务历史中最新的一条-----");
System.out.println("流程实例ID:" + hisTask.getId());
System.out.println("流程定义ID:" + hisTask.getProcessDefinitionId());
System.out.println("流程实例结束时间:" + hisTask.getEndTime());
// System.out.println("流程任务id:" + hisTask.getTaskDefinitionKey());
// System.out.println("流程任务开始时间:" + hisTask.getCreateTime());
// System.out.println("流程任务结束时间:" + hisTask.getEndTime());
}
/**
* 获取当前流程实例的部署id
*/
@Test
public void testGetDeploymentId() {
String processInstanceId = "5";
String processDefinitionId = "";
ProcessInstance processInstance = processEngine.getRuntimeService()//
.createProcessInstanceQuery()//
.processInstanceId(processInstanceId).singleResult();
if (processInstance != null) {
System.out.println("流程定义id =" + processInstance.getProcessDefinitionId());
System.out.println("流程部署id =" + processInstance.getDeploymentId());
System.out.println("流程部署id =" + processInstance.getProcessDefinitionKey());
processDefinitionId = processInstance.getProcessDefinitionId();
} else {
// 查询执行到哪一个节点
HistoricProcessInstance historicProcessInstance = processEngine.getHistoryService()//
.createHistoricProcessInstanceQuery()//
.processInstanceId(processInstanceId)//
.singleResult();
System.out.println("-----查询任务历史中最新的一条-----");
System.out.println("流程实例ID:" + historicProcessInstance.getId());
System.out.println("流程定义ID:" + historicProcessInstance.getProcessDefinitionId());
System.out.println("流程实例结束时间:" + historicProcessInstance.getEndTime());
System.out.println("流程任务id:" + historicProcessInstance.getEndActivityId());
processDefinitionId = historicProcessInstance.getProcessDefinitionId();
}
ProcessDefinition processDefinition = processEngine.getRepositoryService().createProcessDefinitionQuery()
.processDefinitionId(processDefinitionId).singleResult();
System.out.println("流程部署id =" + processDefinition.getDeploymentId());
}
/**
* 通过任务id获取当前任务对象
*/
@Test
public void testGetTaskByTaskId() {
String taskId = "77509";
Task task = processEngine.getTaskService()//
.createTaskQuery()//
.taskId(taskId)//
.singleResult();
System.out.println("流程任务ID:" + task.getId());
System.out.println("流程任务执行者:" + task.getAssignee());
System.out.println("流程任务定义id:" + task.getTaskDefinitionKey());
System.out.println("流程任务开始时间:" + task.getCreateTime());
System.out.println("流程定义ID:" + task.getProcessDefinitionId());
System.out.println("流程实例ID:" + task.getProcessInstanceId());
}
@Test
public void testGetTaskFormKeyByTaskId() {
String formKey = processEngine.getFormService()//
.getTaskFormData("60009")//
.getFormKey();
System.out.println(formKey);
}
@Test
public void testGetLineName() {
List<Comment> commentList = processEngine.getTaskService()//
.getTaskComments("60009");
System.out.println(commentList);
}
}
|
[
"[email protected]"
] | |
77f21436f3892afa0f807569e43496dbf0c636aa
|
eaec4795e768f4631df4fae050fd95276cd3e01b
|
/src/cmps252/HW4_2/UnitTesting/record_4784.java
|
5781a19a530af75248f8b0f5d0fc51e8a7f34472
|
[
"MIT"
] |
permissive
|
baraabilal/cmps252_hw4.2
|
debf5ae34ce6a7ff8d3bce21b0345874223093bc
|
c436f6ae764de35562cf103b049abd7fe8826b2b
|
refs/heads/main
| 2023-01-04T13:02:13.126271 | 2020-11-03T16:32:35 | 2020-11-03T16:32:35 | 307,839,669 | 1 | 0 |
MIT
| 2020-10-27T22:07:57 | 2020-10-27T22:07:56 | null |
UTF-8
|
Java
| false | false | 2,466 |
java
|
package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("49")
class Record_4784 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 4784: FirstName is Monte")
void FirstNameOfRecord4784() {
assertEquals("Monte", customers.get(4783).getFirstName());
}
@Test
@DisplayName("Record 4784: LastName is Topping")
void LastNameOfRecord4784() {
assertEquals("Topping", customers.get(4783).getLastName());
}
@Test
@DisplayName("Record 4784: Company is Wheatland Abstract Co")
void CompanyOfRecord4784() {
assertEquals("Wheatland Abstract Co", customers.get(4783).getCompany());
}
@Test
@DisplayName("Record 4784: Address is 6850 Manhattan Blvd #-202")
void AddressOfRecord4784() {
assertEquals("6850 Manhattan Blvd #-202", customers.get(4783).getAddress());
}
@Test
@DisplayName("Record 4784: City is Fort Worth")
void CityOfRecord4784() {
assertEquals("Fort Worth", customers.get(4783).getCity());
}
@Test
@DisplayName("Record 4784: County is Tarrant")
void CountyOfRecord4784() {
assertEquals("Tarrant", customers.get(4783).getCounty());
}
@Test
@DisplayName("Record 4784: State is TX")
void StateOfRecord4784() {
assertEquals("TX", customers.get(4783).getState());
}
@Test
@DisplayName("Record 4784: ZIP is 76120")
void ZIPOfRecord4784() {
assertEquals("76120", customers.get(4783).getZIP());
}
@Test
@DisplayName("Record 4784: Phone is 817-446-2384")
void PhoneOfRecord4784() {
assertEquals("817-446-2384", customers.get(4783).getPhone());
}
@Test
@DisplayName("Record 4784: Fax is 817-446-5162")
void FaxOfRecord4784() {
assertEquals("817-446-5162", customers.get(4783).getFax());
}
@Test
@DisplayName("Record 4784: Email is [email protected]")
void EmailOfRecord4784() {
assertEquals("[email protected]", customers.get(4783).getEmail());
}
@Test
@DisplayName("Record 4784: Web is http://www.montetopping.com")
void WebOfRecord4784() {
assertEquals("http://www.montetopping.com", customers.get(4783).getWeb());
}
}
|
[
"[email protected]"
] | |
5ac9fb83bb1c476fe2b298c26bc7adfa26d8ea7c
|
d6ab38714f7a5f0dc6d7446ec20626f8f539406a
|
/backend/collecting/dsfj/Java/edited/mustache.MustacheResourceTemplateLoader.java
|
b65a67506f06f8590fa65b8eff37c2d1f618ad89
|
[] |
no_license
|
haditabatabaei/webproject
|
8db7178affaca835b5d66daa7d47c28443b53c3d
|
86b3f253e894f4368a517711bbfbe257be0259fd
|
refs/heads/master
| 2020-04-10T09:26:25.819406 | 2018-12-08T12:21:52 | 2018-12-08T12:21:52 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,321 |
java
|
package org.springframework.boot.autoconfigure.mustache;
import java.io.InputStreamReader;
import java.io.Reader;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.Compiler;
import com.samskivert.mustache.Mustache.TemplateLoader;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
public class MustacheResourceTemplateLoader
implements TemplateLoader, ResourceLoaderAware {
private String prefix = "";
private String suffix = "";
private String charSet = "UTF-8";
private ResourceLoader resourceLoader = new DefaultResourceLoader();
public MustacheResourceTemplateLoader() {
}
public MustacheResourceTemplateLoader(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public void setCharset(String charSet) {
this.charSet = charSet;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public Reader getTemplate(String name) throws Exception {
return new InputStreamReader(this.resourceLoader
.getResource(this.prefix + name + this.suffix).getInputStream(),
this.charSet);
}
}
|
[
"[email protected]"
] | |
f4262f658d3e2fe6b0a6747e176215be414d5f8a
|
62e60fef3110bf9317ddc3bd036264df15fd8aaf
|
/src/main/java/com/controller/ChefController.java
|
06a62fe630c98f4ac46acba9d8fdb3888c4d4626
|
[] |
no_license
|
xiayizhanxingfu/Order-management
|
245c8393a3d05b8a51004edd5af45f94f05f67e8
|
3d8c42311ac2b3f589a5d33aee47ac543b00c4f4
|
refs/heads/master
| 2022-12-23T02:40:14.664150 | 2019-12-09T02:45:40 | 2019-12-09T02:45:40 | 224,190,086 | 0 | 0 | null | 2022-12-15T23:28:20 | 2019-11-26T12:43:00 |
HTML
|
UTF-8
|
Java
| false | false | 4,413 |
java
|
package com.controller;
import com.alibaba.fastjson.JSON;
import com.bean.Task;
import com.bean.Users;
import com.service.OrderformService;
import com.service.TaskService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 下一张幸福
*/
@Controller
@RequestMapping("/chef")
public class ChefController {
@Resource
TaskService taskService;
@Resource
OrderformService orderformService;
/**
* 获取所有未领取任务列表
*
* @param session 会话
* @return 状态和结果
*/
@ResponseBody
@RequestMapping(value = "/taskList", produces = {"application/json;charset=utf-8"})
public String taskList(HttpSession session,
@RequestParam("page") int page) {
Map<String, Object> map = new HashMap<>(3);
Users users = (Users) session.getAttribute("userinfo");
if (users == null) {
map.put("status", "error");
} else {
map.put("status", "ok");
map.put("pageinfo", taskService.getTask(page));
}
return JSON.toJSONString(map);
}
/**
* 获取自己的己领取任务列表
*
* @param session 会话
* @return 状态和结果
*/
@ResponseBody
@RequestMapping(value = "/myTaskList", produces = {"application/json;charset=utf-8"})
public String myTaskList(HttpSession session,
@RequestParam("page") int page) {
Map<String, Object> map = new HashMap<>(3);
Users users = (Users) session.getAttribute("userinfo");
if (users == null) {
map.put("status", "error");
} else {
map.put("status", "ok");
map.put("pageinfo", taskService.getMyTask(users, page));
}
return JSON.toJSONString(map);
}
/**
* 厨师领取操作
*
* @param session 会话
* @return 状态
*/
@ResponseBody
@RequestMapping(value = "/getTask", produces = {"application/json;charset=utf-8"})
public String getTask(HttpSession session,
@RequestParam("id[]") int[] id) {
Map<String, Object> map = new HashMap<>(2);
Users users = (Users) session.getAttribute("userinfo");
if (users == null) {
map.put("status", "error");
} else {
//修改客户订单状态为未上菜
orderformService.updateStatut(id, 2);
taskService.getTask(users, id);
map.put("status", "ok");
}
return JSON.toJSONString(map);
}
/**
* 厨师取消任务操作
*
* @param session 会话
* @param id 任务编号
* @return 状态
*/
@ResponseBody
@RequestMapping(value = "/cancelTask", produces = {"application/json;charset=utf-8"})
public String calcelTask(HttpSession session,
@RequestParam("id[]") int[] id) {
Map<String, Object> map = new HashMap<>(2);
Users users = (Users) session.getAttribute("userinfo");
if (users == null) {
map.put("status", "error");
} else {
taskService.cancelTask(users, id);
//修个客户订单状态为己付款
orderformService.updateStatut(id, 1);
map.put("status", "ok");
}
return JSON.toJSONString(map);
}
/**
* 厨师完成任务操作
*
* @param session 会话
* @param id 任务编号
* @return 状态
*/
@ResponseBody
@RequestMapping(value = "/doneTask", produces = {"application/json;charset=utf-8"})
public String doneTask(HttpSession session,
@RequestParam("id[]") int[] id) {
Map<String, Object> map = new HashMap<>(2);
Users users = (Users) session.getAttribute("userinfo");
if (users == null) {
map.put("status", "error");
} else {
taskService.doneTask(users, id);
map.put("status", "ok");
}
return JSON.toJSONString(map);
}
}
|
[
"[email protected]"
] | |
ab3247f3b85b60c3073ee28b50db95bf7471f7c7
|
63d4c72fbe83fbda4398e1852c510d8eeee1bc4f
|
/GitHubAutomation/src/test/java/com/epam/ta/driver/DriverSingleton.java
|
7eb17e8b36a8773a3910a8da7c6d75c27e5a3828
|
[] |
no_license
|
SashaShust/HT3
|
a80b0931c954b0c52c6d1745bb46d5561ff78198
|
8d04c690930e1576c11d9cc2db4e8dc05345096c
|
refs/heads/master
| 2020-04-11T18:18:39.323156 | 2018-12-17T13:28:39 | 2018-12-17T13:28:39 | 161,993,760 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,127 |
java
|
package com.epam.ta.driver;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
* Created by Vitali_Shulha on 20-Oct-16.
*/
public class DriverSingleton {
private static WebDriver driver;
private static final Logger logger = LogManager.getRootLogger();
private static final String WEBDRIVER_GECKO_DRIVER = "webdriver.gecko.driver";
private static final String GECKODRIVER_GECKODRIVER_EXE_PATH = ".\\geckodriver\\geckodriver.exe";
private DriverSingleton() {
};
public static WebDriver getDriver() {
if (null == driver) {
System.setProperty(WEBDRIVER_GECKO_DRIVER, GECKODRIVER_GECKODRIVER_EXE_PATH);
driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
logger.info("Browser started");
}
return driver;
}
public static void closeDriver() {
driver.quit();
driver = null;
}
}
|
[
"[email protected]"
] | |
a1ff8dd0489c26a26f107f51cc913ee7ea1981b1
|
1993de00038f9f180c767815bd7685a371a933d0
|
/src/main/java/model/osoba/Osoba.java
|
fffeedca9be3d702eb9b917d6ab1ef2d6cf50e3f
|
[] |
no_license
|
szymciogrosik/SBD_ObjectDbProject
|
4e38fb262d89303f7ceda9694d89e25feb72594a
|
0d608b82c98328063956aeeb0cd70913e751d542
|
refs/heads/master
| 2020-03-18T10:07:15.021208 | 2018-05-23T22:13:38 | 2018-05-23T22:13:38 | 134,597,470 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 1,082 |
java
|
package model.osoba;
import model.dataType.Adres;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public abstract class Osoba implements Serializable {
@Id
@GeneratedValue
private long id;
private String imie;
private String nazwisko;
private String nrTelefonu;
private Adres adres;
public void przedstawSie() {
System.out.println("Jestem osoba. Nazywam sie " + imie + " " + nazwisko + ". Mój nr telefonu to: " + nrTelefonu);
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getNrTelefonu() {
return nrTelefonu;
}
public void setNrTelefonu(String nrTelefonu) {
this.nrTelefonu = nrTelefonu;
}
public Adres getAdres() {
return adres;
}
public void setAdres(Adres adres) {
this.adres = adres;
}
}
|
[
"[email protected]"
] | |
9cc5bcd26add58c1d5ad875601e4f6af99b88468
|
3b30f392e996250bd02714d6066aaa4b4f37a5b6
|
/pet-fetch/src/main/java/com/pet/fetch/PetClient.java
|
18745961a5a194492fce8241b143b4e515d907e5
|
[] |
no_license
|
khaliyo/pet
|
1d4ec5ff2d21388c008177f44e810483f012a249
|
4ea1d08b8e75a6fcd4e20e4096c38c318e8af53b
|
refs/heads/master
| 2021-01-14T11:57:54.447524 | 2013-05-21T12:36:30 | 2013-05-21T12:36:30 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 7,238 |
java
|
package com.pet.fetch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pet.core.domain.Comment;
import com.taobao.api.ApiException;
import com.taobao.api.Constants;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.ItemCat;
import com.taobao.api.domain.ItemProp;
import com.taobao.api.domain.PropValue;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.TaobaokeItemDetail;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ItempropsGetRequest;
import com.taobao.api.request.TaobaokeItemsDetailGetRequest;
import com.taobao.api.request.TaobaokeItemsGetRequest;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ItempropsGetResponse;
import com.taobao.api.response.TaobaokeItemsDetailGetResponse;
import com.taobao.api.response.TaobaokeItemsGetResponse;
public class PetClient {
private static final String serverUrl = "http://gw.api.taobao.com/router/rest";
private static final String appKey = "21501927";
private static final String appSecret = "4b7d7dcfc1c216375ac48a97e706c1e1";
private static final String NICK = "tb46969797";
private static final String COMMENT_URL = "a.m.taobao.com";
private static final String COMMENT_PATH = "/ajax/rate_list.do";
private static TaobaoClient client = new DefaultTaobaoClient(
serverUrl.trim(), appKey.trim(), appSecret.trim(), Constants.FORMAT_JSON);
private static PetClient petClient = new PetClient();
private static Object lock = new Object();
private PetClient() {
}
public List<ItemCat> getItemCats(String cid, long parentCid) {
List<ItemCat> itemCats = null;
try {
ItemcatsGetRequest req = new ItemcatsGetRequest();
req.setFields("cid,parent_cid,name,is_parent");
cid = cid.trim();
if (cid != null && !cid.equals("")) {
if (cid.trim().endsWith(",")) {
req.setCids(cid.substring(0, cid.lastIndexOf(",") - 1));
} else {
req.setCids(cid);
}
}
if (parentCid != 0) {
req.setParentCid(parentCid);
}
ItemcatsGetResponse response = client.execute(req);
itemCats = response.getItemCats();
} catch (ApiException e) {
e.printStackTrace();
}
return itemCats;
}
public static PetClient getInstance() {
synchronized (lock) {
if (petClient == null) {
petClient = new PetClient();
}
}
return petClient;
}
public List<TaobaokeItemDetail> getTaobaokeItemDetails(String numIid)
throws ApiException {
List<TaobaokeItemDetail> taobaokeItemDetails = null;
TaobaokeItemsDetailGetRequest req = new TaobaokeItemsDetailGetRequest();
req.setFields("click_url,shop_click_url,seller_credit_score,num_iid,title,nick");
req.setNick(NICK);
req.setNumIids(numIid);
TaobaokeItemsDetailGetResponse response = client.execute(req);
taobaokeItemDetails = response.getTaobaokeItemDetails();
return taobaokeItemDetails;
}
public List<ItemProp> getItemProps(long cid) {
ItempropsGetRequest request = new ItempropsGetRequest();
List<ItemProp> itemProps = null;
try {
request.setCid(cid);
ItempropsGetResponse response = client.execute(request);
itemProps = response.getItemProps();
for (ItemProp prop : itemProps) {
List<PropValue> propValues = prop.getPropValues();
if (propValues != null) {
for (PropValue value : prop.getPropValues()) {
System.out.println(prop.getName() + ":"
+ value.getName());
}
}
}
} catch (ApiException e) {
e.printStackTrace();
}
return itemProps;
}
public List<Comment> getComment(long itemId, int page) {
JSONObject json = null;
List<Comment> comments = new ArrayList<Comment>();
try {
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(COMMENT_URL, 80, "http");
// client.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,
// 10000);
HttpMethod method = new GetMethod(COMMENT_PATH);
NameValuePair itemPair = new NameValuePair("item_id", itemId + "");
NameValuePair ratePair = new NameValuePair("rateRs", page + "");
NameValuePair psPair = new NameValuePair("ps", 100 + "");
method.setQueryString(new NameValuePair[] { itemPair, ratePair,
psPair });
client.executeMethod(method);
// 打印服务器返回的状态
int methodstatus = method.getStatusCode();
StringBuffer sb = new StringBuffer();
if (methodstatus == 200) {
try {
BufferedReader rd = new BufferedReader(
new InputStreamReader(
method.getResponseBodyAsStream(), "UTF-8"));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
json = JSON.parseObject(sb.toString().toString());
rd.close();
} catch (IOException e) {
throw new RuntimeException("error", e);
}
}
method.releaseConnection();
if (json != null) {
JSONArray array = json.getJSONArray("items");
if (array != null) {
for (Object object : array) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd");
JSONObject objectVal = (JSONObject) object;
Comment comment = new Comment();
comment.setCommodityId(itemId);
comment.setAnnoy(objectVal.getIntValue("annoy"));
comment.setBuyerName(objectVal.getString("buyer"));
comment.setCredit(objectVal.getIntValue("credit"));
comment.setDate(sdf.parse(objectVal
.getString("date")));
comment.setDeal(objectVal.getString("deal"));
comment.setRateId(objectVal.getLongValue("rateId"));
comment.setText(objectVal.getString("text"));
comment.setType(objectVal.getIntValue("type"));
comments.add(comment);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return comments;
}
public static void main(String[] args) {
for (TaobaokeItem taobaokeItem : PetClient.getInstance()
.getTaobaokeItems(50006121)) {
System.out.println(taobaokeItem.getClickUrl());
System.out.println(taobaokeItem.getPicUrl());
PetClient.getInstance().getComment(taobaokeItem.getNumIid(), 1);
}
;
}
public List<TaobaokeItem> getTaobaokeItems(long cid) {
List<TaobaokeItem> taobaokeItems = null;
try {
TaobaokeItemsGetRequest req = new TaobaokeItemsGetRequest();
req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
req.setNick(NICK);
req.setCid(cid);
TaobaokeItemsGetResponse response = client.execute(req);
taobaokeItems = response.getTaobaokeItems();
} catch (ApiException e) {
e.printStackTrace();
}
return taobaokeItems;
}
}
|
[
"[email protected]"
] | |
9094461f6abc2fd8835dbc5f79d3753c8c64110c
|
e0009dbb031ce9404a373b57f5fdf59858d1c6cf
|
/src/test/java/com/mycompany/myapp/web/rest/TablesResourceIT.java
|
761396b124db6190442344541f3f1d388a7052e9
|
[] |
no_license
|
kandjiabrar28/springboot-angular-decpc
|
5f164977829b3cbe5ee7569dfc9807dfa3bac59d
|
b4e46e9a7c9a99514a78d8edac45fce435955402
|
refs/heads/master
| 2022-05-03T07:38:42.466287 | 2020-04-05T16:34:48 | 2020-04-05T16:34:48 | 252,981,638 | 0 | 0 | null | null | null | null |
UTF-8
|
Java
| false | false | 9,087 |
java
|
package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.JhipsterApp;
import com.mycompany.myapp.domain.Tables;
import com.mycompany.myapp.repository.TablesRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link TablesResource} REST controller.
*/
@SpringBootTest(classes = JhipsterApp.class)
@AutoConfigureMockMvc
@WithMockUser
public class TablesResourceIT {
private static final Integer DEFAULT_NUMTABLE = 1;
private static final Integer UPDATED_NUMTABLE = 2;
private static final LocalDate DEFAULT_DATE_CREATION = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATE_CREATION = LocalDate.now(ZoneId.systemDefault());
private static final LocalDate DEFAULT_DATE_MODIFICATION = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATE_MODIFICATION = LocalDate.now(ZoneId.systemDefault());
@Autowired
private TablesRepository tablesRepository;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restTablesMockMvc;
private Tables tables;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Tables createEntity(EntityManager em) {
Tables tables = new Tables()
.numtable(DEFAULT_NUMTABLE)
.dateCreation(DEFAULT_DATE_CREATION)
.dateModification(DEFAULT_DATE_MODIFICATION);
return tables;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Tables createUpdatedEntity(EntityManager em) {
Tables tables = new Tables()
.numtable(UPDATED_NUMTABLE)
.dateCreation(UPDATED_DATE_CREATION)
.dateModification(UPDATED_DATE_MODIFICATION);
return tables;
}
@BeforeEach
public void initTest() {
tables = createEntity(em);
}
@Test
@Transactional
public void createTables() throws Exception {
int databaseSizeBeforeCreate = tablesRepository.findAll().size();
// Create the Tables
restTablesMockMvc.perform(post("/api/tables")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(tables)))
.andExpect(status().isCreated());
// Validate the Tables in the database
List<Tables> tablesList = tablesRepository.findAll();
assertThat(tablesList).hasSize(databaseSizeBeforeCreate + 1);
Tables testTables = tablesList.get(tablesList.size() - 1);
assertThat(testTables.getNumtable()).isEqualTo(DEFAULT_NUMTABLE);
assertThat(testTables.getDateCreation()).isEqualTo(DEFAULT_DATE_CREATION);
assertThat(testTables.getDateModification()).isEqualTo(DEFAULT_DATE_MODIFICATION);
}
@Test
@Transactional
public void createTablesWithExistingId() throws Exception {
int databaseSizeBeforeCreate = tablesRepository.findAll().size();
// Create the Tables with an existing ID
tables.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restTablesMockMvc.perform(post("/api/tables")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(tables)))
.andExpect(status().isBadRequest());
// Validate the Tables in the database
List<Tables> tablesList = tablesRepository.findAll();
assertThat(tablesList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllTables() throws Exception {
// Initialize the database
tablesRepository.saveAndFlush(tables);
// Get all the tablesList
restTablesMockMvc.perform(get("/api/tables?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(tables.getId().intValue())))
.andExpect(jsonPath("$.[*].numtable").value(hasItem(DEFAULT_NUMTABLE)))
.andExpect(jsonPath("$.[*].dateCreation").value(hasItem(DEFAULT_DATE_CREATION.toString())))
.andExpect(jsonPath("$.[*].dateModification").value(hasItem(DEFAULT_DATE_MODIFICATION.toString())));
}
@Test
@Transactional
public void getTables() throws Exception {
// Initialize the database
tablesRepository.saveAndFlush(tables);
// Get the tables
restTablesMockMvc.perform(get("/api/tables/{id}", tables.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(tables.getId().intValue()))
.andExpect(jsonPath("$.numtable").value(DEFAULT_NUMTABLE))
.andExpect(jsonPath("$.dateCreation").value(DEFAULT_DATE_CREATION.toString()))
.andExpect(jsonPath("$.dateModification").value(DEFAULT_DATE_MODIFICATION.toString()));
}
@Test
@Transactional
public void getNonExistingTables() throws Exception {
// Get the tables
restTablesMockMvc.perform(get("/api/tables/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTables() throws Exception {
// Initialize the database
tablesRepository.saveAndFlush(tables);
int databaseSizeBeforeUpdate = tablesRepository.findAll().size();
// Update the tables
Tables updatedTables = tablesRepository.findById(tables.getId()).get();
// Disconnect from session so that the updates on updatedTables are not directly saved in db
em.detach(updatedTables);
updatedTables
.numtable(UPDATED_NUMTABLE)
.dateCreation(UPDATED_DATE_CREATION)
.dateModification(UPDATED_DATE_MODIFICATION);
restTablesMockMvc.perform(put("/api/tables")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(updatedTables)))
.andExpect(status().isOk());
// Validate the Tables in the database
List<Tables> tablesList = tablesRepository.findAll();
assertThat(tablesList).hasSize(databaseSizeBeforeUpdate);
Tables testTables = tablesList.get(tablesList.size() - 1);
assertThat(testTables.getNumtable()).isEqualTo(UPDATED_NUMTABLE);
assertThat(testTables.getDateCreation()).isEqualTo(UPDATED_DATE_CREATION);
assertThat(testTables.getDateModification()).isEqualTo(UPDATED_DATE_MODIFICATION);
}
@Test
@Transactional
public void updateNonExistingTables() throws Exception {
int databaseSizeBeforeUpdate = tablesRepository.findAll().size();
// Create the Tables
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restTablesMockMvc.perform(put("/api/tables")
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(tables)))
.andExpect(status().isBadRequest());
// Validate the Tables in the database
List<Tables> tablesList = tablesRepository.findAll();
assertThat(tablesList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteTables() throws Exception {
// Initialize the database
tablesRepository.saveAndFlush(tables);
int databaseSizeBeforeDelete = tablesRepository.findAll().size();
// Delete the tables
restTablesMockMvc.perform(delete("/api/tables/{id}", tables.getId())
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Tables> tablesList = tablesRepository.findAll();
assertThat(tablesList).hasSize(databaseSizeBeforeDelete - 1);
}
}
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.