blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8c2e9e853392abaf3398d4427f00d294872fc715
| 11,587,821,781,284 |
7e2d0affa7b00f3ee8e373567af7f72898118cbc
|
/src/main/java/stellar/data/GroupRecord.java
|
6d0b638ac5534aed9e420b170af5ec38dd83878d
|
[
"MIT"
] |
permissive
|
makhidkarun/cartography
|
https://github.com/makhidkarun/cartography
|
99a9c2566b6b997bf1398c9d9a77c58c8c19c9a9
|
5ba438edae79c4d4a61eb838f2f0701799dae3bb
|
refs/heads/master
| 2021-01-22T04:53:48.346000 | 2016-08-20T12:53:14 | 2016-08-20T12:53:14 | 12,659,590 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package stellar.data;
import java.awt.Dimension;
import java.lang.IndexOutOfBoundsException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLDocument;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
/**
* Record of star system groups. This is kept as a tree:
* subsectror->quadrant->sector->domain. There is a generic group as well for
* non-standard grouping of systems. The tree may contain one or more of the
* groups, but none of guaranteed to be there.
*
* @version $Id$
* @author $Author$
*/
public class GroupRecord extends Record implements MutableTreeNode
{
/*
<xsd:simpleType name="group_type">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="sector" />
<xsd:enumeration value="subsector" />
<xsd:enumeration value="group" />
<xsd:enumeration value="quadrant" />
<xsd:enumeration value="domain" />
</xsd:restriction>
</xsd:simpleType>
*/
/*
public static final String SECTOR = "sector";
public static final String SUBSECTOR = "subsector";
public static final String GROUP = "group";
public static final String QUADRANT = "quadrant";
public static final String DOMAIN = "domain";
public static final int DOMAIN_INDEX = 0;
public static final int SECTOR_INDEX = 1;
public static final int QUADRANT_INDEX = 2;
public static final int SUBSECTOR_INDEX = 3;
public static final int GROUP_INDEX = 10;
*/
private String name;
private HexID location;
private GroupRecord parent;
private String parentName;
private GroupType type;
private int extentX;
private int extentY;
private int extentZ;
private HTMLDocument comment;
private String fileName;
private ArrayList<StarSystem> systems;
private HashSet links;
private Dimension offset = new Dimension (1,1);
private Vector children;
public GroupRecord()
{
}
public GroupRecord (GroupRecord aGroup)
{
super (aGroup);
this.name = aGroup.getName();
setParent ((MutableTreeNode)aGroup.getParent());
setType (aGroup.getType());
setComment (aGroup.getComment());
setLocation (new HexID (aGroup.getLocation()));
}
public String toString() { return name; }
public HTMLDocument getComment() { return comment; }
public void setComment(Document newComment) { comment = (HTMLDocument)newComment; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public HexID getLocation() { return location; }
public void setLocation(HexID location) { this.location = location; }
public GroupType getType() { return type; }
public int getExtentX() { return extentX; }
public void setExtentX(int extentX) { this.extentX = extentX; }
public int getExtentY() { return extentY; }
public void setExtentY(int extentY) { this.extentY = extentY; }
public int getExtentZ() { return extentZ; }
public void setExtentZ(int extentZ) { this.extentZ = extentZ; }
public String getParentName () { return parentName; }
/*
public int getTypeIndex()
{
if (type.matches(DOMAIN)) return DOMAIN_INDEX;
if (type.matches(SECTOR)) return SECTOR_INDEX;
if (type.matches(QUADRANT)) return QUADRANT_INDEX;
if (type.matches(SUBSECTOR)) return SUBSECTOR_INDEX;
if (type.matches(GROUP)) return GROUP_INDEX;
return -1;
}
*/
public StarSystem getSystem (int index) { return systems.get(index); }
public int getSystemCount () { return systems != null? systems.size() : 0; }
public ListIterator<StarSystem> getSystems () { return systems != null ? systems.listIterator() : null; }
public void addSystem (StarSystem system)
{
if (systems == null) { systems = new ArrayList<StarSystem>(); }
systems.add(system);
}
public StarSystem getSystem (HexID xy)
{
if (systems == null) return null;
StarSystem s;
try
{
s = systems.get(systems.indexOf(xy));
return s;
}
catch (IndexOutOfBoundsException e)
{
return null;
}
}
public Iterator getLinks() { return (links == null) ? Collections.EMPTY_LIST.listIterator() : links.iterator(); }
public void addLink (Links newLink)
{
if (links == null) { links = new HashSet<Links> (); }
if (links.contains (newLink)) return;
links.add(newLink);
}
public int getLinkCount () { return (links == null) ? -1 : links.size(); }
public boolean inGroup (HexID h)
{
int x, y;
/* if this hex is not in this group, make sure it's in one of the parent
* groups. It not in any of them, we've got two branches of the root tree
* for which we don't want to place this system within.
*/
if (!(h.getHexGroup().equals(getKey())))
{
GroupRecord parent = (GroupRecord)getParent();
while (parent != null)
{
if (h.getHexGroup().equals(parent.getKey())) break;
parent = (GroupRecord)parent.getParent();
}
if (parent == null) return false;
}
if (parentName == null)
{
x = 0; y = 0;
}
else
{
x = (location.x - 1) * extentX;
y = (location.y - 1) * extentY;
}
return (h.x > x && h.x <= x + extentX && h.y > y && h.y <= y + extentY);
}
public String getFileName() { return fileName; }
public void setFileName(String fileName) { this.fileName = fileName; }
public Dimension getOffset () { return offset; }
public void setType(GroupType type)
{
this.type = type;
if (type == GroupType.SUBSECTOR) { extentX = 8; extentY=10; }
if (type == GroupType.QUADRANT) { extentX = 16; extentY=20; }
if (type == GroupType.SECTOR) { extentX = 32; extentY=40; }
if (type == GroupType.DOMAIN) { extentX = 64; extentY=80; }
}
// TreeNode functions;
public Enumeration children ()
{
if (children == null) return DefaultMutableTreeNode.EMPTY_ENUMERATION;
else return children.elements();
}
public boolean getAllowsChildren() { return true; }
public TreeNode getChildAt (int index) { return children == null ? null : (TreeNode)children.elementAt(index); }
public int getChildCount () { return children == null ? 0 : children.size(); }
public int getIndex(TreeNode aChild) { return children == null ? -1 : children.indexOf(aChild); }
public TreeNode getParent() { return parent; }
public boolean isLeaf() { return (getChildCount() == 0); }
//MutableTreeNode functions;
public void setParent (MutableTreeNode newParent)
{
parent = (GroupRecord)newParent;
parentName = newParent.toString();
offset.height = ((location.x - 1) * extentX) + 1;
offset.width = ((location.y - 1) * extentY) + 1;
}
public void setUserObject (Object object) {}
public void insert (MutableTreeNode newChild, int index)
{
MutableTreeNode oldParent = (MutableTreeNode)newChild.getParent();
if (oldParent != null) {
oldParent.remove(newChild);
}
newChild.setParent(this);
if (children == null) {
children = new Vector();
}
children.insertElementAt(newChild, index);
}
public void remove (int index)
{
MutableTreeNode child = (MutableTreeNode)getChildAt(index);
children.removeElementAt(index);
child.setParent(null);
}
public void remove (MutableTreeNode aChild)
{
int index = getIndex(aChild);
if (index >= 0) remove (index);
}
public void removeFromParent()
{
MutableTreeNode parent = (MutableTreeNode)getParent();
if (parent != null)
{
parent.remove(this);
}
}
}
|
UTF-8
|
Java
| 8,608 |
java
|
GroupRecord.java
|
Java
|
[] | null |
[] |
package stellar.data;
import java.awt.Dimension;
import java.lang.IndexOutOfBoundsException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLDocument;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
/**
* Record of star system groups. This is kept as a tree:
* subsectror->quadrant->sector->domain. There is a generic group as well for
* non-standard grouping of systems. The tree may contain one or more of the
* groups, but none of guaranteed to be there.
*
* @version $Id$
* @author $Author$
*/
public class GroupRecord extends Record implements MutableTreeNode
{
/*
<xsd:simpleType name="group_type">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="sector" />
<xsd:enumeration value="subsector" />
<xsd:enumeration value="group" />
<xsd:enumeration value="quadrant" />
<xsd:enumeration value="domain" />
</xsd:restriction>
</xsd:simpleType>
*/
/*
public static final String SECTOR = "sector";
public static final String SUBSECTOR = "subsector";
public static final String GROUP = "group";
public static final String QUADRANT = "quadrant";
public static final String DOMAIN = "domain";
public static final int DOMAIN_INDEX = 0;
public static final int SECTOR_INDEX = 1;
public static final int QUADRANT_INDEX = 2;
public static final int SUBSECTOR_INDEX = 3;
public static final int GROUP_INDEX = 10;
*/
private String name;
private HexID location;
private GroupRecord parent;
private String parentName;
private GroupType type;
private int extentX;
private int extentY;
private int extentZ;
private HTMLDocument comment;
private String fileName;
private ArrayList<StarSystem> systems;
private HashSet links;
private Dimension offset = new Dimension (1,1);
private Vector children;
public GroupRecord()
{
}
public GroupRecord (GroupRecord aGroup)
{
super (aGroup);
this.name = aGroup.getName();
setParent ((MutableTreeNode)aGroup.getParent());
setType (aGroup.getType());
setComment (aGroup.getComment());
setLocation (new HexID (aGroup.getLocation()));
}
public String toString() { return name; }
public HTMLDocument getComment() { return comment; }
public void setComment(Document newComment) { comment = (HTMLDocument)newComment; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public HexID getLocation() { return location; }
public void setLocation(HexID location) { this.location = location; }
public GroupType getType() { return type; }
public int getExtentX() { return extentX; }
public void setExtentX(int extentX) { this.extentX = extentX; }
public int getExtentY() { return extentY; }
public void setExtentY(int extentY) { this.extentY = extentY; }
public int getExtentZ() { return extentZ; }
public void setExtentZ(int extentZ) { this.extentZ = extentZ; }
public String getParentName () { return parentName; }
/*
public int getTypeIndex()
{
if (type.matches(DOMAIN)) return DOMAIN_INDEX;
if (type.matches(SECTOR)) return SECTOR_INDEX;
if (type.matches(QUADRANT)) return QUADRANT_INDEX;
if (type.matches(SUBSECTOR)) return SUBSECTOR_INDEX;
if (type.matches(GROUP)) return GROUP_INDEX;
return -1;
}
*/
public StarSystem getSystem (int index) { return systems.get(index); }
public int getSystemCount () { return systems != null? systems.size() : 0; }
public ListIterator<StarSystem> getSystems () { return systems != null ? systems.listIterator() : null; }
public void addSystem (StarSystem system)
{
if (systems == null) { systems = new ArrayList<StarSystem>(); }
systems.add(system);
}
public StarSystem getSystem (HexID xy)
{
if (systems == null) return null;
StarSystem s;
try
{
s = systems.get(systems.indexOf(xy));
return s;
}
catch (IndexOutOfBoundsException e)
{
return null;
}
}
public Iterator getLinks() { return (links == null) ? Collections.EMPTY_LIST.listIterator() : links.iterator(); }
public void addLink (Links newLink)
{
if (links == null) { links = new HashSet<Links> (); }
if (links.contains (newLink)) return;
links.add(newLink);
}
public int getLinkCount () { return (links == null) ? -1 : links.size(); }
public boolean inGroup (HexID h)
{
int x, y;
/* if this hex is not in this group, make sure it's in one of the parent
* groups. It not in any of them, we've got two branches of the root tree
* for which we don't want to place this system within.
*/
if (!(h.getHexGroup().equals(getKey())))
{
GroupRecord parent = (GroupRecord)getParent();
while (parent != null)
{
if (h.getHexGroup().equals(parent.getKey())) break;
parent = (GroupRecord)parent.getParent();
}
if (parent == null) return false;
}
if (parentName == null)
{
x = 0; y = 0;
}
else
{
x = (location.x - 1) * extentX;
y = (location.y - 1) * extentY;
}
return (h.x > x && h.x <= x + extentX && h.y > y && h.y <= y + extentY);
}
public String getFileName() { return fileName; }
public void setFileName(String fileName) { this.fileName = fileName; }
public Dimension getOffset () { return offset; }
public void setType(GroupType type)
{
this.type = type;
if (type == GroupType.SUBSECTOR) { extentX = 8; extentY=10; }
if (type == GroupType.QUADRANT) { extentX = 16; extentY=20; }
if (type == GroupType.SECTOR) { extentX = 32; extentY=40; }
if (type == GroupType.DOMAIN) { extentX = 64; extentY=80; }
}
// TreeNode functions;
public Enumeration children ()
{
if (children == null) return DefaultMutableTreeNode.EMPTY_ENUMERATION;
else return children.elements();
}
public boolean getAllowsChildren() { return true; }
public TreeNode getChildAt (int index) { return children == null ? null : (TreeNode)children.elementAt(index); }
public int getChildCount () { return children == null ? 0 : children.size(); }
public int getIndex(TreeNode aChild) { return children == null ? -1 : children.indexOf(aChild); }
public TreeNode getParent() { return parent; }
public boolean isLeaf() { return (getChildCount() == 0); }
//MutableTreeNode functions;
public void setParent (MutableTreeNode newParent)
{
parent = (GroupRecord)newParent;
parentName = newParent.toString();
offset.height = ((location.x - 1) * extentX) + 1;
offset.width = ((location.y - 1) * extentY) + 1;
}
public void setUserObject (Object object) {}
public void insert (MutableTreeNode newChild, int index)
{
MutableTreeNode oldParent = (MutableTreeNode)newChild.getParent();
if (oldParent != null) {
oldParent.remove(newChild);
}
newChild.setParent(this);
if (children == null) {
children = new Vector();
}
children.insertElementAt(newChild, index);
}
public void remove (int index)
{
MutableTreeNode child = (MutableTreeNode)getChildAt(index);
children.removeElementAt(index);
child.setParent(null);
}
public void remove (MutableTreeNode aChild)
{
int index = getIndex(aChild);
if (index >= 0) remove (index);
}
public void removeFromParent()
{
MutableTreeNode parent = (MutableTreeNode)getParent();
if (parent != null)
{
parent.remove(this);
}
}
}
| 8,608 | 0.602928 | 0.598513 | 239 | 34.016735 | 24.984173 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615063 | false | false |
12
|
147eb226c56049a30dc1bed455bccdc4116d4cf5
| 28,174,985,503,282 |
a9f5b0170a5f1a5c618e1174ba1349a6534ee0d2
|
/SunilSample/app/src/main/java/android/example/com/sunilsample/MoviesAdapter.java
|
ba88d3a6c177eaeb02a439e0b88d9641b64dcfc3
|
[] |
no_license
|
suniltn/My-Notes
|
https://github.com/suniltn/My-Notes
|
384f415eaf19564c495e5b7b7035f697744a0919
|
7852b8456c4a99c44b72fe7e4a3d5ee56104fefd
|
refs/heads/master
| 2020-01-09T22:41:45.071000 | 2019-11-19T06:14:27 | 2019-11-19T06:14:27 | 93,362,945 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package android.example.com.sunilsample;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
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;
/**
* Created by Supreeth on 3/1/17.
*/
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MoviesViewHolder> {
private List<Movies> movies;
private Context context;
public MoviesAdapter(Context context) {
this.context = context;
movies = new ArrayList<>();
}
public void setMovies(List<Movies> movies) {
this.movies = movies;
notifyDataSetChanged();
}
@Override
public MoviesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_item, parent, false);
MoviesViewHolder holder = new MoviesViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MoviesViewHolder holder, int position) {
holder.title.setText(movies.get(position).movieTitle);
Glide.with(context)
.load(movies.get(position).posters.detailed)
.fitCenter()
.dontAnimate()
.crossFade()
.into(holder.image);
}
@Override
public int getItemCount() {
return movies.size();
}
public class MoviesViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private ImageView image;
public MoviesViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.movie_title);
image = (ImageView) itemView.findViewById(R.id.movie_image);
}
}
}
|
UTF-8
|
Java
| 1,700 |
java
|
MoviesAdapter.java
|
Java
|
[
{
"context": "mport com.bumptech.glide.Glide;\n\n/**\n * Created by Supreeth on 3/1/17.\n */\n\npublic class MoviesAdapter extend",
"end": 392,
"score": 0.9696273803710938,
"start": 384,
"tag": "USERNAME",
"value": "Supreeth"
}
] | null |
[] |
package android.example.com.sunilsample;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
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;
/**
* Created by Supreeth on 3/1/17.
*/
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MoviesViewHolder> {
private List<Movies> movies;
private Context context;
public MoviesAdapter(Context context) {
this.context = context;
movies = new ArrayList<>();
}
public void setMovies(List<Movies> movies) {
this.movies = movies;
notifyDataSetChanged();
}
@Override
public MoviesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_item, parent, false);
MoviesViewHolder holder = new MoviesViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MoviesViewHolder holder, int position) {
holder.title.setText(movies.get(position).movieTitle);
Glide.with(context)
.load(movies.get(position).posters.detailed)
.fitCenter()
.dontAnimate()
.crossFade()
.into(holder.image);
}
@Override
public int getItemCount() {
return movies.size();
}
public class MoviesViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private ImageView image;
public MoviesViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.movie_title);
image = (ImageView) itemView.findViewById(R.id.movie_image);
}
}
}
| 1,700 | 0.756471 | 0.753529 | 70 | 23.271429 | 23.429482 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.442857 | false | false |
12
|
4c843c3aa4bc21e14d18fb819084f5eebe576762
| 558,345,756,685 |
db0d2130b32685e87fcdd1c6754017f5b0f64cbf
|
/src/main/org/apache/tools/ant/AntTypeDefinition.java
|
387577f922fc4316e06cc330c88d99086955ff0d
|
[
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"W3C",
"GPL-1.0-or-later",
"SAX-PD",
"Apache-2.0"
] |
permissive
|
maithanhduyan/ant
|
https://github.com/maithanhduyan/ant
|
68c8797afcb527c3aae93befef34c98f65f83a3d
|
d7c518584ecf5dc4b586dd4a1a9a20dec50a1a20
|
refs/heads/master
| 2020-03-27T12:57:36.539000 | 2018-08-27T13:20:15 | 2018-08-27T13:20:15 | 146,581,005 | 1 | 0 |
Apache-2.0
| true | 2018-08-29T10:01:16 | 2018-08-29T10:01:15 | 2018-08-29T10:01:14 | 2018-08-28T19:38:28 | 71,317 | 0 | 0 | 0 | null | false | null |
/*
* 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.tools.ant;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* This class contains all the information
* on a particular ant type,
* the classname, adapter and the class
* it should be assignable from.
* This type replaces the task/datatype split
* of pre ant 1.6.
*
*/
public class AntTypeDefinition {
private String name;
private Class<?> clazz;
private Class<?> adapterClass;
private Class<?> adaptToClass;
private String className;
private ClassLoader classLoader;
private boolean restrict = false;
/**
* Set the restrict attribute.
* @param restrict the value to set.
*/
public void setRestrict(boolean restrict) {
this.restrict = restrict;
}
/**
* Get the restrict attribute.
* @return the restrict attribute.
*/
public boolean isRestrict() {
return restrict;
}
/**
* Set the definition's name.
* @param name the name of the definition.
*/
public void setName(String name) {
this.name = name;
}
/**
* Return the definition's name.
* @return the name of the definition.
*/
public String getName() {
return name;
}
/**
* Set the class of the definition.
* As a side-effect may set the classloader and classname.
* @param clazz the class of this definition.
*/
public void setClass(Class<?> clazz) {
this.clazz = clazz;
if (clazz == null) {
return;
}
this.classLoader = (classLoader == null)
? clazz.getClassLoader() : classLoader;
this.className = (className == null) ? clazz.getName() : className;
}
/**
* Set the classname of the definition.
* @param className the classname of this definition.
*/
public void setClassName(String className) {
this.className = className;
}
/**
* Get the classname of the definition.
* @return the name of the class of this definition.
*/
public String getClassName() {
return className;
}
/**
* Set the adapter class for this definition.
* This class is used to adapt the definitions class if
* required.
* @param adapterClass the adapterClass.
*/
public void setAdapterClass(Class<?> adapterClass) {
this.adapterClass = adapterClass;
}
/**
* Set the assignable class for this definition.
* @param adaptToClass the assignable class.
*/
public void setAdaptToClass(Class<?> adaptToClass) {
this.adaptToClass = adaptToClass;
}
/**
* Set the classloader to use to create an instance
* of the definition.
* @param classLoader the ClassLoader.
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Get the classloader for this definition.
* @return the classloader for this definition.
*/
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Get the exposed class for this
* definition. This will be a proxy class
* (adapted class) if there is an adapter
* class and the definition class is not
* assignable from the assignable class.
* @param project the current project.
* @return the exposed class - may return null if unable to load the class
*/
public Class<?> getExposedClass(Project project) {
if (adaptToClass != null) {
Class<?> z = getTypeClass(project);
if (z == null || adaptToClass.isAssignableFrom(z)) {
return z;
}
}
return (adapterClass == null) ? getTypeClass(project) : adapterClass;
}
/**
* Get the definition class.
* @param project the current project.
* @return the type of the definition.
*/
public Class<?> getTypeClass(Project project) {
try {
return innerGetTypeClass();
} catch (NoClassDefFoundError ncdfe) {
project.log("Could not load a dependent class ("
+ ncdfe.getMessage() + ") for type "
+ name, Project.MSG_DEBUG);
} catch (ClassNotFoundException cnfe) {
project.log("Could not load class (" + className
+ ") for type " + name, Project.MSG_DEBUG);
}
return null;
}
/**
* Try and load a class, with no attempt to catch any fault.
* @return the class that implements this component
* @throws ClassNotFoundException if the class cannot be found.
* @throws NoClassDefFoundError if the there is an error
* finding the class.
*/
public Class<?> innerGetTypeClass() throws ClassNotFoundException {
if (clazz != null) {
return clazz;
}
if (classLoader == null) {
clazz = Class.forName(className);
} else {
clazz = classLoader.loadClass(className);
}
return clazz;
}
/**
* Create an instance of the definition.
* The instance may be wrapped in a proxy class.
* @param project the current project.
* @return the created object.
*/
public Object create(Project project) {
return icreate(project);
}
/**
* Create a component object based on
* its definition.
* @return the component as an <code>Object</code>.
*/
private Object icreate(Project project) {
Class<?> c = getTypeClass(project);
if (c == null) {
return null;
}
Object o = createAndSet(project, c);
if (adapterClass == null
|| (adaptToClass != null && adaptToClass.isAssignableFrom(o.getClass()))) {
return o;
}
TypeAdapter adapterObject = (TypeAdapter) createAndSet(
project, adapterClass);
adapterObject.setProxy(o);
return adapterObject;
}
/**
* Checks if the attributes are correct.
* <ul>
* <li>if the class can be created.</li>
* <li>if an adapter class can be created</li>
* <li>if the type is assignable from adapter</li>
* <li>if the type can be used with the adapter class</li>
* </ul>
* @param project the current project.
*/
public void checkClass(Project project) {
if (clazz == null) {
clazz = getTypeClass(project);
if (clazz == null) {
throw new BuildException(
"Unable to create class for " + getName());
}
}
// check adapter
if (adapterClass != null && (adaptToClass == null
|| !adaptToClass.isAssignableFrom(clazz))) {
TypeAdapter adapter = (TypeAdapter) createAndSet(
project, adapterClass);
adapter.checkProxyClass(clazz);
}
}
/**
* Get the constructor of the definition
* and invoke it.
* @return the instantiated <code>Object</code>, will never be null.
*/
private Object createAndSet(Project project, Class<?> c) {
try {
return innerCreateAndSet(c, project);
} catch (InvocationTargetException ex) {
Throwable t = ex.getTargetException();
throw new BuildException(
"Could not create type " + name + " due to " + t, t);
} catch (NoClassDefFoundError ncdfe) {
String msg = "Type " + name + ": A class needed by class "
+ c + " cannot be found: " + ncdfe.getMessage();
throw new BuildException(msg, ncdfe);
} catch (NoSuchMethodException nsme) {
throw new BuildException("Could not create type " + name
+ " as the class " + c + " has no compatible constructor");
} catch (InstantiationException nsme) {
throw new BuildException("Could not create type "
+ name + " as the class " + c + " is abstract");
} catch (IllegalAccessException e) {
throw new BuildException("Could not create type "
+ name + " as the constructor " + c + " is not accessible");
} catch (Throwable t) {
throw new BuildException(
"Could not create type " + name + " due to " + t, t);
}
}
/**
* Inner implementation of the {@link #createAndSet(Project, Class)} logic, with no
* exception catching.
* @param <T> return type of the method
* @param newclass class to create
* @param project the project to use
* @return a newly constructed and bound instance.
* @throws NoSuchMethodException no good constructor.
* @throws InstantiationException cannot initialize the object.
* @throws IllegalAccessException cannot access the object.
* @throws InvocationTargetException error in invocation.
*/
public <T> T innerCreateAndSet(Class<T> newclass, Project project)
throws NoSuchMethodException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
Constructor<T> ctor;
boolean noArg = false;
// DataType can have a "no arg" constructor or take a single
// Project argument.
try {
ctor = newclass.getConstructor();
noArg = true;
} catch (NoSuchMethodException nse) {
//can throw the same exception, if there is no this(Project) ctor.
ctor = newclass.getConstructor(Project.class);
noArg = false;
}
//now we instantiate
T o = ctor.newInstance(
((noArg) ? new Object[0] : new Object[] {project}));
//set up project references.
project.setProjectReference(o);
return o;
}
/**
* Equality method for this definition (assumes the names are the same).
*
* @param other another definition.
* @param project the project the definition.
* @return true if the definitions are the same.
*/
public boolean sameDefinition(AntTypeDefinition other, Project project) {
return (other != null && other.getClass() == getClass()
&& other.getTypeClass(project).equals(getTypeClass(project))
&& other.getExposedClass(project).equals(getExposedClass(project))
&& other.restrict == restrict
&& other.adapterClass == adapterClass
&& other.adaptToClass == adaptToClass);
}
/**
* Similar definition;
* used to compare two definitions defined twice with the same
* name and the same types.
* The classloader may be different but have the same
* path so #sameDefinition cannot
* be used.
* @param other the definition to compare to.
* @param project the current project.
* @return true if the definitions are the same.
*/
public boolean similarDefinition(AntTypeDefinition other, Project project) {
if (other == null
|| getClass() != other.getClass()
|| !getClassName().equals(other.getClassName())
|| !extractClassname(adapterClass).equals(
extractClassname(other.adapterClass))
|| !extractClassname(adaptToClass).equals(
extractClassname(other.adaptToClass))
|| restrict != other.restrict) {
return false;
}
// all the names are the same: check if the class path of the loader
// is the same
ClassLoader oldLoader = other.getClassLoader();
ClassLoader newLoader = getClassLoader();
return oldLoader == newLoader
|| (oldLoader instanceof AntClassLoader
&& newLoader instanceof AntClassLoader
&& ((AntClassLoader) oldLoader).getClasspath()
.equals(((AntClassLoader) newLoader).getClasspath()));
}
private String extractClassname(Class<?> c) {
return (c == null) ? "<null>" : c.getClass().getName();
}
}
|
UTF-8
|
Java
| 12,969 |
java
|
AntTypeDefinition.java
|
Java
|
[] | null |
[] |
/*
* 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.tools.ant;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* This class contains all the information
* on a particular ant type,
* the classname, adapter and the class
* it should be assignable from.
* This type replaces the task/datatype split
* of pre ant 1.6.
*
*/
public class AntTypeDefinition {
private String name;
private Class<?> clazz;
private Class<?> adapterClass;
private Class<?> adaptToClass;
private String className;
private ClassLoader classLoader;
private boolean restrict = false;
/**
* Set the restrict attribute.
* @param restrict the value to set.
*/
public void setRestrict(boolean restrict) {
this.restrict = restrict;
}
/**
* Get the restrict attribute.
* @return the restrict attribute.
*/
public boolean isRestrict() {
return restrict;
}
/**
* Set the definition's name.
* @param name the name of the definition.
*/
public void setName(String name) {
this.name = name;
}
/**
* Return the definition's name.
* @return the name of the definition.
*/
public String getName() {
return name;
}
/**
* Set the class of the definition.
* As a side-effect may set the classloader and classname.
* @param clazz the class of this definition.
*/
public void setClass(Class<?> clazz) {
this.clazz = clazz;
if (clazz == null) {
return;
}
this.classLoader = (classLoader == null)
? clazz.getClassLoader() : classLoader;
this.className = (className == null) ? clazz.getName() : className;
}
/**
* Set the classname of the definition.
* @param className the classname of this definition.
*/
public void setClassName(String className) {
this.className = className;
}
/**
* Get the classname of the definition.
* @return the name of the class of this definition.
*/
public String getClassName() {
return className;
}
/**
* Set the adapter class for this definition.
* This class is used to adapt the definitions class if
* required.
* @param adapterClass the adapterClass.
*/
public void setAdapterClass(Class<?> adapterClass) {
this.adapterClass = adapterClass;
}
/**
* Set the assignable class for this definition.
* @param adaptToClass the assignable class.
*/
public void setAdaptToClass(Class<?> adaptToClass) {
this.adaptToClass = adaptToClass;
}
/**
* Set the classloader to use to create an instance
* of the definition.
* @param classLoader the ClassLoader.
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Get the classloader for this definition.
* @return the classloader for this definition.
*/
public ClassLoader getClassLoader() {
return classLoader;
}
/**
* Get the exposed class for this
* definition. This will be a proxy class
* (adapted class) if there is an adapter
* class and the definition class is not
* assignable from the assignable class.
* @param project the current project.
* @return the exposed class - may return null if unable to load the class
*/
public Class<?> getExposedClass(Project project) {
if (adaptToClass != null) {
Class<?> z = getTypeClass(project);
if (z == null || adaptToClass.isAssignableFrom(z)) {
return z;
}
}
return (adapterClass == null) ? getTypeClass(project) : adapterClass;
}
/**
* Get the definition class.
* @param project the current project.
* @return the type of the definition.
*/
public Class<?> getTypeClass(Project project) {
try {
return innerGetTypeClass();
} catch (NoClassDefFoundError ncdfe) {
project.log("Could not load a dependent class ("
+ ncdfe.getMessage() + ") for type "
+ name, Project.MSG_DEBUG);
} catch (ClassNotFoundException cnfe) {
project.log("Could not load class (" + className
+ ") for type " + name, Project.MSG_DEBUG);
}
return null;
}
/**
* Try and load a class, with no attempt to catch any fault.
* @return the class that implements this component
* @throws ClassNotFoundException if the class cannot be found.
* @throws NoClassDefFoundError if the there is an error
* finding the class.
*/
public Class<?> innerGetTypeClass() throws ClassNotFoundException {
if (clazz != null) {
return clazz;
}
if (classLoader == null) {
clazz = Class.forName(className);
} else {
clazz = classLoader.loadClass(className);
}
return clazz;
}
/**
* Create an instance of the definition.
* The instance may be wrapped in a proxy class.
* @param project the current project.
* @return the created object.
*/
public Object create(Project project) {
return icreate(project);
}
/**
* Create a component object based on
* its definition.
* @return the component as an <code>Object</code>.
*/
private Object icreate(Project project) {
Class<?> c = getTypeClass(project);
if (c == null) {
return null;
}
Object o = createAndSet(project, c);
if (adapterClass == null
|| (adaptToClass != null && adaptToClass.isAssignableFrom(o.getClass()))) {
return o;
}
TypeAdapter adapterObject = (TypeAdapter) createAndSet(
project, adapterClass);
adapterObject.setProxy(o);
return adapterObject;
}
/**
* Checks if the attributes are correct.
* <ul>
* <li>if the class can be created.</li>
* <li>if an adapter class can be created</li>
* <li>if the type is assignable from adapter</li>
* <li>if the type can be used with the adapter class</li>
* </ul>
* @param project the current project.
*/
public void checkClass(Project project) {
if (clazz == null) {
clazz = getTypeClass(project);
if (clazz == null) {
throw new BuildException(
"Unable to create class for " + getName());
}
}
// check adapter
if (adapterClass != null && (adaptToClass == null
|| !adaptToClass.isAssignableFrom(clazz))) {
TypeAdapter adapter = (TypeAdapter) createAndSet(
project, adapterClass);
adapter.checkProxyClass(clazz);
}
}
/**
* Get the constructor of the definition
* and invoke it.
* @return the instantiated <code>Object</code>, will never be null.
*/
private Object createAndSet(Project project, Class<?> c) {
try {
return innerCreateAndSet(c, project);
} catch (InvocationTargetException ex) {
Throwable t = ex.getTargetException();
throw new BuildException(
"Could not create type " + name + " due to " + t, t);
} catch (NoClassDefFoundError ncdfe) {
String msg = "Type " + name + ": A class needed by class "
+ c + " cannot be found: " + ncdfe.getMessage();
throw new BuildException(msg, ncdfe);
} catch (NoSuchMethodException nsme) {
throw new BuildException("Could not create type " + name
+ " as the class " + c + " has no compatible constructor");
} catch (InstantiationException nsme) {
throw new BuildException("Could not create type "
+ name + " as the class " + c + " is abstract");
} catch (IllegalAccessException e) {
throw new BuildException("Could not create type "
+ name + " as the constructor " + c + " is not accessible");
} catch (Throwable t) {
throw new BuildException(
"Could not create type " + name + " due to " + t, t);
}
}
/**
* Inner implementation of the {@link #createAndSet(Project, Class)} logic, with no
* exception catching.
* @param <T> return type of the method
* @param newclass class to create
* @param project the project to use
* @return a newly constructed and bound instance.
* @throws NoSuchMethodException no good constructor.
* @throws InstantiationException cannot initialize the object.
* @throws IllegalAccessException cannot access the object.
* @throws InvocationTargetException error in invocation.
*/
public <T> T innerCreateAndSet(Class<T> newclass, Project project)
throws NoSuchMethodException,
InstantiationException,
IllegalAccessException,
InvocationTargetException {
Constructor<T> ctor;
boolean noArg = false;
// DataType can have a "no arg" constructor or take a single
// Project argument.
try {
ctor = newclass.getConstructor();
noArg = true;
} catch (NoSuchMethodException nse) {
//can throw the same exception, if there is no this(Project) ctor.
ctor = newclass.getConstructor(Project.class);
noArg = false;
}
//now we instantiate
T o = ctor.newInstance(
((noArg) ? new Object[0] : new Object[] {project}));
//set up project references.
project.setProjectReference(o);
return o;
}
/**
* Equality method for this definition (assumes the names are the same).
*
* @param other another definition.
* @param project the project the definition.
* @return true if the definitions are the same.
*/
public boolean sameDefinition(AntTypeDefinition other, Project project) {
return (other != null && other.getClass() == getClass()
&& other.getTypeClass(project).equals(getTypeClass(project))
&& other.getExposedClass(project).equals(getExposedClass(project))
&& other.restrict == restrict
&& other.adapterClass == adapterClass
&& other.adaptToClass == adaptToClass);
}
/**
* Similar definition;
* used to compare two definitions defined twice with the same
* name and the same types.
* The classloader may be different but have the same
* path so #sameDefinition cannot
* be used.
* @param other the definition to compare to.
* @param project the current project.
* @return true if the definitions are the same.
*/
public boolean similarDefinition(AntTypeDefinition other, Project project) {
if (other == null
|| getClass() != other.getClass()
|| !getClassName().equals(other.getClassName())
|| !extractClassname(adapterClass).equals(
extractClassname(other.adapterClass))
|| !extractClassname(adaptToClass).equals(
extractClassname(other.adaptToClass))
|| restrict != other.restrict) {
return false;
}
// all the names are the same: check if the class path of the loader
// is the same
ClassLoader oldLoader = other.getClassLoader();
ClassLoader newLoader = getClassLoader();
return oldLoader == newLoader
|| (oldLoader instanceof AntClassLoader
&& newLoader instanceof AntClassLoader
&& ((AntClassLoader) oldLoader).getClasspath()
.equals(((AntClassLoader) newLoader).getClasspath()));
}
private String extractClassname(Class<?> c) {
return (c == null) ? "<null>" : c.getClass().getName();
}
}
| 12,969 | 0.59835 | 0.59781 | 378 | 33.309525 | 23.341654 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.312169 | false | false |
12
|
96019ff7038405b30beff25d226bb4388cd15bf9
| 18,519,898,999,522 |
44ae99cc690a2ccd25e22b3dc71343ce3882eee7
|
/org/isotc211/x2005/gmd/impl/MDImagingConditionCodeDocumentImpl.java
|
dded2f28355a67a3afd1eda696a2460131565d72
|
[] |
no_license
|
mcenirm/isotc211-src
|
https://github.com/mcenirm/isotc211-src
|
0ee877ddcb0ff71191008311d3ee60d8c4263a70
|
c8d68f488500ed4815f1fa9875c0c24f3bda845b
|
refs/heads/master
| 2021-03-12T23:00:39.838000 | 2012-06-16T22:15:48 | 2012-06-16T22:15:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* An XML document type.
* Localname: MD_ImagingConditionCode
* Namespace: http://www.isotc211.org/2005/gmd
* Java type: org.isotc211.x2005.gmd.MDImagingConditionCodeDocument
*
* Automatically generated - do not modify.
*/
package org.isotc211.x2005.gmd.impl;
/**
* A document containing one MD_ImagingConditionCode(@http://www.isotc211.org/2005/gmd) element.
*
* This is a complex type.
*/
public class MDImagingConditionCodeDocumentImpl extends org.isotc211.x2005.gco.impl.CharacterStringDocumentImpl implements org.isotc211.x2005.gmd.MDImagingConditionCodeDocument
{
private static final long serialVersionUID = 1L;
public MDImagingConditionCodeDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName MDIMAGINGCONDITIONCODE$0 =
new javax.xml.namespace.QName("http://www.isotc211.org/2005/gmd", "MD_ImagingConditionCode");
/**
* Gets the "MD_ImagingConditionCode" element
*/
public org.isotc211.x2005.gco.CodeListValueType getMDImagingConditionCode()
{
synchronized (monitor())
{
check_orphaned();
org.isotc211.x2005.gco.CodeListValueType target = null;
target = (org.isotc211.x2005.gco.CodeListValueType)get_store().find_element_user(MDIMAGINGCONDITIONCODE$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "MD_ImagingConditionCode" element
*/
public void setMDImagingConditionCode(org.isotc211.x2005.gco.CodeListValueType mdImagingConditionCode)
{
generatedSetterHelperImpl(mdImagingConditionCode, MDIMAGINGCONDITIONCODE$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "MD_ImagingConditionCode" element
*/
public org.isotc211.x2005.gco.CodeListValueType addNewMDImagingConditionCode()
{
synchronized (monitor())
{
check_orphaned();
org.isotc211.x2005.gco.CodeListValueType target = null;
target = (org.isotc211.x2005.gco.CodeListValueType)get_store().add_element_user(MDIMAGINGCONDITIONCODE$0);
return target;
}
}
}
|
UTF-8
|
Java
| 2,344 |
java
|
MDImagingConditionCodeDocumentImpl.java
|
Java
|
[] | null |
[] |
/*
* An XML document type.
* Localname: MD_ImagingConditionCode
* Namespace: http://www.isotc211.org/2005/gmd
* Java type: org.isotc211.x2005.gmd.MDImagingConditionCodeDocument
*
* Automatically generated - do not modify.
*/
package org.isotc211.x2005.gmd.impl;
/**
* A document containing one MD_ImagingConditionCode(@http://www.isotc211.org/2005/gmd) element.
*
* This is a complex type.
*/
public class MDImagingConditionCodeDocumentImpl extends org.isotc211.x2005.gco.impl.CharacterStringDocumentImpl implements org.isotc211.x2005.gmd.MDImagingConditionCodeDocument
{
private static final long serialVersionUID = 1L;
public MDImagingConditionCodeDocumentImpl(org.apache.xmlbeans.SchemaType sType)
{
super(sType);
}
private static final javax.xml.namespace.QName MDIMAGINGCONDITIONCODE$0 =
new javax.xml.namespace.QName("http://www.isotc211.org/2005/gmd", "MD_ImagingConditionCode");
/**
* Gets the "MD_ImagingConditionCode" element
*/
public org.isotc211.x2005.gco.CodeListValueType getMDImagingConditionCode()
{
synchronized (monitor())
{
check_orphaned();
org.isotc211.x2005.gco.CodeListValueType target = null;
target = (org.isotc211.x2005.gco.CodeListValueType)get_store().find_element_user(MDIMAGINGCONDITIONCODE$0, 0);
if (target == null)
{
return null;
}
return target;
}
}
/**
* Sets the "MD_ImagingConditionCode" element
*/
public void setMDImagingConditionCode(org.isotc211.x2005.gco.CodeListValueType mdImagingConditionCode)
{
generatedSetterHelperImpl(mdImagingConditionCode, MDIMAGINGCONDITIONCODE$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);
}
/**
* Appends and returns a new empty "MD_ImagingConditionCode" element
*/
public org.isotc211.x2005.gco.CodeListValueType addNewMDImagingConditionCode()
{
synchronized (monitor())
{
check_orphaned();
org.isotc211.x2005.gco.CodeListValueType target = null;
target = (org.isotc211.x2005.gco.CodeListValueType)get_store().add_element_user(MDIMAGINGCONDITIONCODE$0);
return target;
}
}
}
| 2,344 | 0.676195 | 0.631399 | 67 | 33.985073 | 40.118294 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.283582 | false | false |
12
|
edce61eacc71693ca2d5e56c3874c95b9be0d213
| 18,107,582,129,457 |
f2ba7659af4b59f4930a64f379facd4fa44ed42b
|
/app/src/main/java/com/example/sendmessage/iu/ViewMessageActivity.java
|
004790b9710691213e6c4dfb2580c1fcfc9e827c
|
[] |
no_license
|
juanjolagosanchez/ChangeSizeText
|
https://github.com/juanjolagosanchez/ChangeSizeText
|
87e2cac46d884b78bec3e334a9a474c8586577ba
|
44101e5efae9f14ad7814d91af4116f74db064bf
|
refs/heads/main
| 2023-07-31T03:52:28.048000 | 2021-10-07T22:11:25 | 2021-10-07T22:11:25 | 414,665,632 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.sendmessage.iu;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.example.sendmessage.data.model.Message;
import com.example.sendmessage.databinding.ActivitySendmessageBinding;
import com.example.sendmessage.databinding.ActivityViewMessageBinding;
public class ViewMessageActivity extends AppCompatActivity {
private static final String TAG = "SendMessageProyect";
private ActivityViewMessageBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityViewMessageBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//1. Recogemos el intent que nos ha enviado la activity sendMessageActivity
Intent intent = getIntent();
//2. Recoger el objeto Bundle con el mismo metodo que se ha introducido en el intent
Bundle bundle = intent.getExtras();
//3. Asignar cada cadena a sus componentes
//binding.tvContentUser.setText(bundle.getString("user"));
//binding.tvContentMessage.setText(bundle.getString("message"));
//Aquí recogemos los datos usando la clase que hemos implementado
//Recogiendo el valor serializado del bundle y almacenandolo en nuestro objeto Message
Message message = new Message();
message = (Message)bundle.getSerializable("message");
binding.tvContentUser.setText(message.getUser().toString());
binding.tvContentMessage.setText(message.getMessage().toString());
Log.i(TAG, "viewMessageActivity -> onCreate()");
}
// region Metodos ciclo de vida
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "viewMessageActivity -> onStart()");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "viewMessageActivity -> OnResume");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "viewMessageActivity -> OnPause");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "viewMessageActivity -> onStop()");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "viewMessageActivity -> onDestroy()");
}
// endregion
}
|
UTF-8
|
Java
| 2,419 |
java
|
ViewMessageActivity.java
|
Java
|
[] | null |
[] |
package com.example.sendmessage.iu;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.example.sendmessage.data.model.Message;
import com.example.sendmessage.databinding.ActivitySendmessageBinding;
import com.example.sendmessage.databinding.ActivityViewMessageBinding;
public class ViewMessageActivity extends AppCompatActivity {
private static final String TAG = "SendMessageProyect";
private ActivityViewMessageBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityViewMessageBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//1. Recogemos el intent que nos ha enviado la activity sendMessageActivity
Intent intent = getIntent();
//2. Recoger el objeto Bundle con el mismo metodo que se ha introducido en el intent
Bundle bundle = intent.getExtras();
//3. Asignar cada cadena a sus componentes
//binding.tvContentUser.setText(bundle.getString("user"));
//binding.tvContentMessage.setText(bundle.getString("message"));
//Aquí recogemos los datos usando la clase que hemos implementado
//Recogiendo el valor serializado del bundle y almacenandolo en nuestro objeto Message
Message message = new Message();
message = (Message)bundle.getSerializable("message");
binding.tvContentUser.setText(message.getUser().toString());
binding.tvContentMessage.setText(message.getMessage().toString());
Log.i(TAG, "viewMessageActivity -> onCreate()");
}
// region Metodos ciclo de vida
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "viewMessageActivity -> onStart()");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "viewMessageActivity -> OnResume");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "viewMessageActivity -> OnPause");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "viewMessageActivity -> onStop()");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "viewMessageActivity -> onDestroy()");
}
// endregion
}
| 2,419 | 0.686931 | 0.685691 | 71 | 33.070423 | 26.596792 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535211 | false | false |
12
|
ebb11ef1b8eb7e799765b067b7c627f34a110f44
| 30,270,929,558,928 |
bf2eecaa06d04b68fa4e99ceb2921aff7b87274b
|
/cuatro/src/test/java/com/ufps/cuatro/util/generadores/codeobject/CodeProcessGeneratorSingleTest.java
|
4a2f7cd9a191777071ed0dbbc8c54208f800ed06
|
[] |
no_license
|
google-code/4dor
|
https://github.com/google-code/4dor
|
c072a06aea45b6c0b4749c930f4dc6e62fd74265
|
00629725b0f89853307c22f52f63b45c1e433d08
|
refs/heads/master
| 2018-01-09T09:13:56.951000 | 2015-03-13T15:47:45 | 2015-03-13T15:47:45 | 32,164,858 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ufps.cuatro.util.generadores.codeobject;
import java.util.ArrayList;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
*
* @author CATC
*/
public class CodeProcessGeneratorSingleTest extends TestCase {
public CodeProcessGeneratorSingleTest(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite(CodeProcessGeneratorSingleTest.class);
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of generateSourceCodeSyntaxImport method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxImport() {
// System.out.println("generateSourceCodeSintaxImport");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxImport(objSourceLinesCode);
}
/**
* Test of generateSourceCodeSyntaxDefinition method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxDefinition() {
// System.out.println("generateSourceCodeSintaxDefinition");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxDefinition(objSourceLinesCode, canonicalDefinition);
}
/**
* Test of generateSourceCodeSyntaxInitialization method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxInitialization() {
// System.out.println("generateSourceCodeSintaxInitialization");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxInitialization(objSourceLinesCode, canonicalDefinition);
}
/**
* Test of generateSourceCodeSyntaxInitializationPropertiesControls method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxInitializationPropertiesControls() {
// System.out.println("generateSourceCodeSintaxInitializationPropertiesControls");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxInitializationPropertiesControls(objSourceLinesCode, canonicalDefinition);
}
/**
* Test of generateSourceCodeSyntaxInitializationGridBagConstraintsControls method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxInitializationGridBagConstraintsControls() {
// System.out.println("generateSourceCodeSintaxInitializationGridBagConstraintsControls");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxInitializationGridBagConstraintsControls(objSourceLinesCode, canonicalDefinition);
}
/**
* Test of generateSourceCodeSyntaxControlsEventsDefinition method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxEventsControls() {
// System.out.println("generateSourceCodeSintaxEventsControls");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxControlsEventsDefinition(objSourceLinesCode, canonicalDefinition);
}
public class CodeProcessGeneratorSingleImpl implements CodeProcessGeneratorSingle {
public void generateSourceCodeSyntaxImport(ArrayList<CodeContextLine> objSourceLinesCode) {
}
public void generateSourceCodeSyntaxDefinition(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxInitialization(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxInitializationPropertiesControls(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxInitializationGridBagConstraintsControls(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxControlsEventsDefinition(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxControlsEventsImplement(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
|
UTF-8
|
Java
| 5,435 |
java
|
CodeProcessGeneratorSingleTest.java
|
Java
|
[
{
"context": "port junit.framework.TestSuite;\n\n/**\n *\n * @author CATC\n */\npublic class CodeProcessGeneratorSingleTest e",
"end": 301,
"score": 0.9995388984680176,
"start": 297,
"tag": "USERNAME",
"value": "CATC"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ufps.cuatro.util.generadores.codeobject;
import java.util.ArrayList;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
*
* @author CATC
*/
public class CodeProcessGeneratorSingleTest extends TestCase {
public CodeProcessGeneratorSingleTest(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite(CodeProcessGeneratorSingleTest.class);
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of generateSourceCodeSyntaxImport method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxImport() {
// System.out.println("generateSourceCodeSintaxImport");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxImport(objSourceLinesCode);
}
/**
* Test of generateSourceCodeSyntaxDefinition method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxDefinition() {
// System.out.println("generateSourceCodeSintaxDefinition");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxDefinition(objSourceLinesCode, canonicalDefinition);
}
/**
* Test of generateSourceCodeSyntaxInitialization method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxInitialization() {
// System.out.println("generateSourceCodeSintaxInitialization");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxInitialization(objSourceLinesCode, canonicalDefinition);
}
/**
* Test of generateSourceCodeSyntaxInitializationPropertiesControls method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxInitializationPropertiesControls() {
// System.out.println("generateSourceCodeSintaxInitializationPropertiesControls");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxInitializationPropertiesControls(objSourceLinesCode, canonicalDefinition);
}
/**
* Test of generateSourceCodeSyntaxInitializationGridBagConstraintsControls method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxInitializationGridBagConstraintsControls() {
// System.out.println("generateSourceCodeSintaxInitializationGridBagConstraintsControls");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxInitializationGridBagConstraintsControls(objSourceLinesCode, canonicalDefinition);
}
/**
* Test of generateSourceCodeSyntaxControlsEventsDefinition method, of class CodeProcessGeneratorSingle.
*/
public void testGenerateSourceCodeSintaxEventsControls() {
// System.out.println("generateSourceCodeSintaxEventsControls");
// ArrayList<CodeContextLine> objSourceLinesCode = null;
// boolean canonicalDefinition = false;
// CodeProcessGeneratorSingle instance = new CodeProcessGeneratorSingleImpl();
// instance.generateSourceCodeSyntaxControlsEventsDefinition(objSourceLinesCode, canonicalDefinition);
}
public class CodeProcessGeneratorSingleImpl implements CodeProcessGeneratorSingle {
public void generateSourceCodeSyntaxImport(ArrayList<CodeContextLine> objSourceLinesCode) {
}
public void generateSourceCodeSyntaxDefinition(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxInitialization(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxInitializationPropertiesControls(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxInitializationGridBagConstraintsControls(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxControlsEventsDefinition(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
}
public void generateSourceCodeSyntaxControlsEventsImplement(ArrayList<CodeContextLine> objSourceLinesCode, boolean canonicalDefinition) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
| 5,435 | 0.755842 | 0.755842 | 126 | 42.134922 | 43.158504 | 162 | false | false | 0 | 0 | 0 | 0 | 68 | 0.059614 | 0.468254 | false | false |
12
|
cf10e01401253e56e3aec9f6c97c7137f12ee979
| 24,867,860,686,757 |
d86e10e7a477a26c2c635942c4b1b71698a31ac6
|
/app/src/main/java/bin/xposed/Unblock163MusicClient/ui/SettingsActivity.java
|
7e4e3044dd8b3a9c3459732c22b3876b7f06ef45
|
[] |
no_license
|
leewp14/Unblock163MusicClient-Xposed
|
https://github.com/leewp14/Unblock163MusicClient-Xposed
|
a0499a0ba881898673c06598acbc5aabbf21daf8
|
f6d57ec27cc55baf3b8d323eb25837156541f475
|
refs/heads/master
| 2021-03-19T11:25:31.063000 | 2018-09-08T03:46:23 | 2018-09-08T03:46:23 | 105,525,834 | 1 | 0 | null | true | 2018-09-08T03:46:24 | 2017-10-02T11:13:39 | 2017-10-02T11:13:41 | 2018-09-08T03:46:24 | 387 | 0 | 0 | 0 |
Java
| false | null |
package bin.xposed.Unblock163MusicClient.ui;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.Toast;
import java.io.File;
import bin.xposed.Unblock163MusicClient.BuildConfig;
import bin.xposed.Unblock163MusicClient.R;
import bin.xposed.Unblock163MusicClient.Utility;
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
private int getActivatedModuleVersion() {
return -1;
}
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setWorldReadable();
addPreferencesFromResource(R.xml.pref_general);
checkState();
checkIcon();
}
private void checkState() {
if (getActivatedModuleVersion() == -1) {
showNotActive();
}
}
private void showNotActive() {
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(R.string.hint_reboot_not_active)
.setPositiveButton(R.string.active_now, (dialog, id) -> openXposed())
.setNegativeButton(R.string.cancel, null)
.show();
}
private void openXposed() {
if (Utility.isAppInstalled(this, "de.robv.android.xposed.installer")) {
Intent intent = new Intent("de.robv.android.xposed.installer.OPEN_SECTION");
if (getPackageManager().queryIntentActivities(intent, 0).isEmpty()) {
intent = getPackageManager().getLaunchIntentForPackage("de.robv.android.xposed.installer");
}
if (intent != null) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("section", "modules")
.putExtra("fragment", 1)
.putExtra("module", BuildConfig.APPLICATION_ID);
startActivity(intent);
}
} else {
Toast.makeText(this, R.string.xposed_installer_not_installed, Toast.LENGTH_SHORT).show();
}
}
private boolean isVXP() {
return System.getProperty("vxp") != null;
}
private void checkIcon() {
if (!isVXP() && Utility.isAppInstalled(this, "de.robv.android.xposed.installer")) {
final ComponentName aliasName = new ComponentName(this, SettingsActivity.this.getClass().getName() + "Alias");
final PackageManager packageManager = getPackageManager();
if (packageManager.getComponentEnabledSetting(aliasName) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(R.string.hint_hide_icon)
.setPositiveButton(R.string.ok, (dialog, id) -> packageManager.setComponentEnabledSetting(
aliasName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP)).show();
}
}
}
@SuppressWarnings({"deprecation", "ResultOfMethodCallIgnored"})
@SuppressLint({"SetWorldReadable", "WorldReadableFiles"})
private void setWorldReadable() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File dataDir = new File(getApplicationInfo().dataDir);
File prefsDir = new File(dataDir, "shared_prefs");
File prefsFile = new File(prefsDir, getPreferenceManager().getSharedPreferencesName() + ".xml");
if (prefsFile.exists()) {
for (File file : new File[]{dataDir, prefsDir, prefsFile}) {
file.setReadable(true, false);
file.setExecutable(true, false);
}
}
} else {
getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
}
}
@Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
setWorldReadable();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(this, R.string.hint_reboot_setting_changed, Toast.LENGTH_SHORT).show();
}
}
|
UTF-8
|
Java
| 5,000 |
java
|
SettingsActivity.java
|
Java
|
[] | null |
[] |
package bin.xposed.Unblock163MusicClient.ui;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.Toast;
import java.io.File;
import bin.xposed.Unblock163MusicClient.BuildConfig;
import bin.xposed.Unblock163MusicClient.R;
import bin.xposed.Unblock163MusicClient.Utility;
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
private int getActivatedModuleVersion() {
return -1;
}
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setWorldReadable();
addPreferencesFromResource(R.xml.pref_general);
checkState();
checkIcon();
}
private void checkState() {
if (getActivatedModuleVersion() == -1) {
showNotActive();
}
}
private void showNotActive() {
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(R.string.hint_reboot_not_active)
.setPositiveButton(R.string.active_now, (dialog, id) -> openXposed())
.setNegativeButton(R.string.cancel, null)
.show();
}
private void openXposed() {
if (Utility.isAppInstalled(this, "de.robv.android.xposed.installer")) {
Intent intent = new Intent("de.robv.android.xposed.installer.OPEN_SECTION");
if (getPackageManager().queryIntentActivities(intent, 0).isEmpty()) {
intent = getPackageManager().getLaunchIntentForPackage("de.robv.android.xposed.installer");
}
if (intent != null) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("section", "modules")
.putExtra("fragment", 1)
.putExtra("module", BuildConfig.APPLICATION_ID);
startActivity(intent);
}
} else {
Toast.makeText(this, R.string.xposed_installer_not_installed, Toast.LENGTH_SHORT).show();
}
}
private boolean isVXP() {
return System.getProperty("vxp") != null;
}
private void checkIcon() {
if (!isVXP() && Utility.isAppInstalled(this, "de.robv.android.xposed.installer")) {
final ComponentName aliasName = new ComponentName(this, SettingsActivity.this.getClass().getName() + "Alias");
final PackageManager packageManager = getPackageManager();
if (packageManager.getComponentEnabledSetting(aliasName) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(R.string.hint_hide_icon)
.setPositiveButton(R.string.ok, (dialog, id) -> packageManager.setComponentEnabledSetting(
aliasName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP)).show();
}
}
}
@SuppressWarnings({"deprecation", "ResultOfMethodCallIgnored"})
@SuppressLint({"SetWorldReadable", "WorldReadableFiles"})
private void setWorldReadable() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File dataDir = new File(getApplicationInfo().dataDir);
File prefsDir = new File(dataDir, "shared_prefs");
File prefsFile = new File(prefsDir, getPreferenceManager().getSharedPreferencesName() + ".xml");
if (prefsFile.exists()) {
for (File file : new File[]{dataDir, prefsDir, prefsFile}) {
file.setReadable(true, false);
file.setExecutable(true, false);
}
}
} else {
getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
}
}
@Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
setWorldReadable();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(this, R.string.hint_reboot_setting_changed, Toast.LENGTH_SHORT).show();
}
}
| 5,000 | 0.6346 | 0.6314 | 133 | 36.593987 | 31.136623 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548872 | false | false |
12
|
8d0970432b579c10bf104aaeb7d641c026312ead
| 15,255,723,845,139 |
51dc694a563a9276092cd6a41b0fb375b20c797c
|
/src-Plugins/PrintPetrinet/test3.java
|
c9a01af52fb86c65f464a64b534858e76dfe0a00
|
[] |
no_license
|
qihongda/ProM
|
https://github.com/qihongda/ProM
|
3e20033458e58158e3e58f616aa712ffbbc809fb
|
b4557495c98351da15bc62bce31aae6c98364a83
|
refs/heads/master
| 2021-01-25T04:58:22.770000 | 2017-06-30T09:12:59 | 2017-06-30T09:12:59 | 93,492,696 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package PrintPetrinet;
import java.util.ArrayList;
import java.util.List;
import nl.tue.astar.AStarException;
import org.deckfour.xes.classification.XEventClass;
import org.deckfour.xes.classification.XEventClassifier;
import org.deckfour.xes.info.XLogInfo;
import org.deckfour.xes.info.XLogInfoFactory;
import org.deckfour.xes.model.XLog;
import org.processmining.contexts.uitopia.UIPluginContext;
import org.processmining.contexts.uitopia.annotations.UITopiaVariant;
import org.processmining.framework.connections.ConnectionCannotBeObtained;
import org.processmining.framework.plugin.annotations.Plugin;
import org.processmining.models.graphbased.directed.petrinet.Petrinet;
import org.processmining.models.graphbased.directed.petrinet.PetrinetGraph;
import org.processmining.models.graphbased.directed.petrinet.elements.Transition;
import org.processmining.plugins.connectionfactories.logpetrinet.TransEvClassMapping;
import org.processmining.plugins.petrinet.replayer.PNLogReplayer;
import org.processmining.plugins.petrinet.replayresult.PNRepResult;
import org.processmining.plugins.petrinet.replayresult.StepTypes;
import org.processmining.plugins.replayer.replayresult.SyncReplayResult;
public class test3 {
@Plugin(name = "PrintAlignment", parameterLabels = { "a Petri net", "a XLog" }, returnLabels = { "An alignment" }, returnTypes = { PNRepResult.class }, userAccessible = true, help = "Print a Petrinet")
@UITopiaVariant(affiliation = "NULL", author = "hongda", email = "...")
public static void PrintPetrinet(UIPluginContext context, Petrinet net, XLog log)
throws ConnectionCannotBeObtained, AStarException {
//XEventClass dummyEvClass = new XEventClass("DUMMY", 99999);
//XEventClassifier eventClassifier = XLogInfoImpl.STANDARD_CLASSIFIER;
//costMOT = AlignmentTest.constructMOTCostFunction(net, log, eventClassifier, dummyEvClass);
//mapping = constructMapping(net, log, dummyEvClass, eventClassifier);
//PrintPetrinet.test3.constructMapping(net, log, dummyEvClass, eventClassifier);
List<List<Integer>> l = null;
PNRepResult result;
PNLogReplayer replayer = new PNLogReplayer();
result = replayer.replayLog(context, net, log);
System.out.println("++++++++++++++++++++++-------111-----");
for (SyncReplayResult res : result) {
System.out.println(res.getNodeInstance());
//System.out.println("++++++++++" + res.getNodeInstance().get(0));
System.out.println(res.getStepTypes());
System.out.println(res.getTraceIndex());
l = test3.getlocation(res);
res = test3.exchage(res, l);
}
//System.out.println(((List)l.get(0)).get(0));
System.out.println("++++++++++++++++++++++-------222-----");
//return "aaaa";
}
/**
* get a exchanged alignment
*
* @param res
* @return
*/
public static SyncReplayResult exchage(SyncReplayResult res, List<List<Integer>> l) {
List<Object> nodeInstance1 = new ArrayList<Object>(res.getNodeInstance());
//nodeInstance1.addAll(res.getNodeInstance());
List<StepTypes> stepTypes1 = new ArrayList<StepTypes>(res.getStepTypes());
//res.getStepTypes();
int i, j, k = 0;
for (int flag1 = 0; flag1 < l.size(); flag1++) {
i = l.get(flag1).get(0);
j = l.get(flag1).get(1);
k = l.get(flag1).get(2);
System.out.println("i = " + i + ", j = " + j + ", k = " + k);
for (int flag2 = 0; flag2 < ((k - j) + 1); flag2++) {
System.out.println("=====1======" + res.getNodeInstance().get(j + flag2));
nodeInstance1.remove(i + flag2);
//System.out.println(nodeInstance1);
nodeInstance1.add(i + flag2, res.getNodeInstance().get(j + flag2));
//System.out.println(nodeInstance1);
stepTypes1.remove(i + flag2);
stepTypes1.add(i + flag2, res.getStepTypes().get(j + flag2));
}
for (int flag2 = 0; flag2 < (j - i); flag2++) {
System.out.println("=====2======" + res.getNodeInstance().get(i + flag2));
nodeInstance1.remove(((i + k) - j) + 1 + flag2);
nodeInstance1.add(((i + k) - j) + 1 + flag2, res.getNodeInstance().get(i + flag2));
stepTypes1.remove(((i + k) - j) + 1 + flag2);
stepTypes1.add(((i + k) - j) + 1 + flag2, res.getStepTypes().get(i + flag2));
}
}
System.out.println("nodeInstance1 = " + nodeInstance1);
res.setNodeInstance(nodeInstance1);
System.out.println("stepTypes1 = " + stepTypes1);
res.setStepTypes(stepTypes1);
return res;
}
/**
* get a exchanged location
*
* @param res
* @return
*/
public static List<List<Integer>> getlocation(SyncReplayResult res) {
int i, j, k;
int mid = 0, max = 0;
List<List<Integer>> l = new ArrayList<List<Integer>>();
for (i = 0; i < (res.getStepTypes().size() - 1); i++)
{
for (j = i + 1; j < res.getStepTypes().size(); j++)
{
mid = j;
max = j;
for (k = j; k < res.getStepTypes().size(); k++)
{
if(test3.judge(i, j, k, res) && k > max)
{
max = k;
}
}
if(test3.judge(i, j, max, res))
{
List<Integer> flag = new ArrayList<Integer>();
flag.add(i);
flag.add(j);
flag.add(max);
System.out.println("++++++++++" + flag);
l.add(flag);
i = mid;
break;
}
}
}
return l;
}
/**
* get a exchanged location
*
* @param res
* @return
*/
public static boolean judge(int i, int j, int k, SyncReplayResult res) {
int flag = i;
while ((flag >= i) && (flag < j)) {
if (res.getStepTypes().get(flag) == org.processmining.plugins.petrinet.replayresult.StepTypes.MREAL) {
flag++;
continue;
}
return false;
}
while ((flag >= j) && (flag <= k)) {
if (res.getStepTypes().get(flag) == org.processmining.plugins.petrinet.replayresult.StepTypes.L) {
flag++;
continue;
}
return false;
}
return true;
}
public static TransEvClassMapping constructMapping(PetrinetGraph net, XLog log, XEventClass dummyEvClass,
XEventClassifier eventClassifier) {
TransEvClassMapping mapping = new TransEvClassMapping(eventClassifier, dummyEvClass);
XLogInfo summary = XLogInfoFactory.createLogInfo(log, eventClassifier);
System.out.println("++++++++++++++++++++++");
for (Transition t : net.getTransitions()) {
for (XEventClass evClass : summary.getEventClasses().getClasses()) {
String id = evClass.getId();
if (t.getLabel().equals(id)) {
mapping.put(t, evClass);
break;
}
}
}
return mapping;
}
}
|
UTF-8
|
Java
| 6,341 |
java
|
test3.java
|
Java
|
[
{
"context": "\n\t@UITopiaVariant(affiliation = \"NULL\", author = \"hongda\", email = \"...\")\n\tpublic static void PrintPetrine",
"end": 1477,
"score": 0.9657636284828186,
"start": 1471,
"tag": "NAME",
"value": "hongda"
}
] | null |
[] |
package PrintPetrinet;
import java.util.ArrayList;
import java.util.List;
import nl.tue.astar.AStarException;
import org.deckfour.xes.classification.XEventClass;
import org.deckfour.xes.classification.XEventClassifier;
import org.deckfour.xes.info.XLogInfo;
import org.deckfour.xes.info.XLogInfoFactory;
import org.deckfour.xes.model.XLog;
import org.processmining.contexts.uitopia.UIPluginContext;
import org.processmining.contexts.uitopia.annotations.UITopiaVariant;
import org.processmining.framework.connections.ConnectionCannotBeObtained;
import org.processmining.framework.plugin.annotations.Plugin;
import org.processmining.models.graphbased.directed.petrinet.Petrinet;
import org.processmining.models.graphbased.directed.petrinet.PetrinetGraph;
import org.processmining.models.graphbased.directed.petrinet.elements.Transition;
import org.processmining.plugins.connectionfactories.logpetrinet.TransEvClassMapping;
import org.processmining.plugins.petrinet.replayer.PNLogReplayer;
import org.processmining.plugins.petrinet.replayresult.PNRepResult;
import org.processmining.plugins.petrinet.replayresult.StepTypes;
import org.processmining.plugins.replayer.replayresult.SyncReplayResult;
public class test3 {
@Plugin(name = "PrintAlignment", parameterLabels = { "a Petri net", "a XLog" }, returnLabels = { "An alignment" }, returnTypes = { PNRepResult.class }, userAccessible = true, help = "Print a Petrinet")
@UITopiaVariant(affiliation = "NULL", author = "hongda", email = "...")
public static void PrintPetrinet(UIPluginContext context, Petrinet net, XLog log)
throws ConnectionCannotBeObtained, AStarException {
//XEventClass dummyEvClass = new XEventClass("DUMMY", 99999);
//XEventClassifier eventClassifier = XLogInfoImpl.STANDARD_CLASSIFIER;
//costMOT = AlignmentTest.constructMOTCostFunction(net, log, eventClassifier, dummyEvClass);
//mapping = constructMapping(net, log, dummyEvClass, eventClassifier);
//PrintPetrinet.test3.constructMapping(net, log, dummyEvClass, eventClassifier);
List<List<Integer>> l = null;
PNRepResult result;
PNLogReplayer replayer = new PNLogReplayer();
result = replayer.replayLog(context, net, log);
System.out.println("++++++++++++++++++++++-------111-----");
for (SyncReplayResult res : result) {
System.out.println(res.getNodeInstance());
//System.out.println("++++++++++" + res.getNodeInstance().get(0));
System.out.println(res.getStepTypes());
System.out.println(res.getTraceIndex());
l = test3.getlocation(res);
res = test3.exchage(res, l);
}
//System.out.println(((List)l.get(0)).get(0));
System.out.println("++++++++++++++++++++++-------222-----");
//return "aaaa";
}
/**
* get a exchanged alignment
*
* @param res
* @return
*/
public static SyncReplayResult exchage(SyncReplayResult res, List<List<Integer>> l) {
List<Object> nodeInstance1 = new ArrayList<Object>(res.getNodeInstance());
//nodeInstance1.addAll(res.getNodeInstance());
List<StepTypes> stepTypes1 = new ArrayList<StepTypes>(res.getStepTypes());
//res.getStepTypes();
int i, j, k = 0;
for (int flag1 = 0; flag1 < l.size(); flag1++) {
i = l.get(flag1).get(0);
j = l.get(flag1).get(1);
k = l.get(flag1).get(2);
System.out.println("i = " + i + ", j = " + j + ", k = " + k);
for (int flag2 = 0; flag2 < ((k - j) + 1); flag2++) {
System.out.println("=====1======" + res.getNodeInstance().get(j + flag2));
nodeInstance1.remove(i + flag2);
//System.out.println(nodeInstance1);
nodeInstance1.add(i + flag2, res.getNodeInstance().get(j + flag2));
//System.out.println(nodeInstance1);
stepTypes1.remove(i + flag2);
stepTypes1.add(i + flag2, res.getStepTypes().get(j + flag2));
}
for (int flag2 = 0; flag2 < (j - i); flag2++) {
System.out.println("=====2======" + res.getNodeInstance().get(i + flag2));
nodeInstance1.remove(((i + k) - j) + 1 + flag2);
nodeInstance1.add(((i + k) - j) + 1 + flag2, res.getNodeInstance().get(i + flag2));
stepTypes1.remove(((i + k) - j) + 1 + flag2);
stepTypes1.add(((i + k) - j) + 1 + flag2, res.getStepTypes().get(i + flag2));
}
}
System.out.println("nodeInstance1 = " + nodeInstance1);
res.setNodeInstance(nodeInstance1);
System.out.println("stepTypes1 = " + stepTypes1);
res.setStepTypes(stepTypes1);
return res;
}
/**
* get a exchanged location
*
* @param res
* @return
*/
public static List<List<Integer>> getlocation(SyncReplayResult res) {
int i, j, k;
int mid = 0, max = 0;
List<List<Integer>> l = new ArrayList<List<Integer>>();
for (i = 0; i < (res.getStepTypes().size() - 1); i++)
{
for (j = i + 1; j < res.getStepTypes().size(); j++)
{
mid = j;
max = j;
for (k = j; k < res.getStepTypes().size(); k++)
{
if(test3.judge(i, j, k, res) && k > max)
{
max = k;
}
}
if(test3.judge(i, j, max, res))
{
List<Integer> flag = new ArrayList<Integer>();
flag.add(i);
flag.add(j);
flag.add(max);
System.out.println("++++++++++" + flag);
l.add(flag);
i = mid;
break;
}
}
}
return l;
}
/**
* get a exchanged location
*
* @param res
* @return
*/
public static boolean judge(int i, int j, int k, SyncReplayResult res) {
int flag = i;
while ((flag >= i) && (flag < j)) {
if (res.getStepTypes().get(flag) == org.processmining.plugins.petrinet.replayresult.StepTypes.MREAL) {
flag++;
continue;
}
return false;
}
while ((flag >= j) && (flag <= k)) {
if (res.getStepTypes().get(flag) == org.processmining.plugins.petrinet.replayresult.StepTypes.L) {
flag++;
continue;
}
return false;
}
return true;
}
public static TransEvClassMapping constructMapping(PetrinetGraph net, XLog log, XEventClass dummyEvClass,
XEventClassifier eventClassifier) {
TransEvClassMapping mapping = new TransEvClassMapping(eventClassifier, dummyEvClass);
XLogInfo summary = XLogInfoFactory.createLogInfo(log, eventClassifier);
System.out.println("++++++++++++++++++++++");
for (Transition t : net.getTransitions()) {
for (XEventClass evClass : summary.getEventClasses().getClasses()) {
String id = evClass.getId();
if (t.getLabel().equals(id)) {
mapping.put(t, evClass);
break;
}
}
}
return mapping;
}
}
| 6,341 | 0.66551 | 0.652263 | 196 | 31.352041 | 30.987877 | 202 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.80102 | false | false |
12
|
b3fb928cf40da53d40d32569fa177617dbad95a4
| 22,076,131,957,176 |
0a66575d5f0be735b5225e3bc39e5efdbc3c3179
|
/src/main/java/spring/learning/proxy/factory/TestFactoryBean.java
|
b0bf22a6e0ddd0735c0dc8baf273f5859c534902
|
[] |
no_license
|
kangaukju/TobySpring
|
https://github.com/kangaukju/TobySpring
|
32dbf43839131c20b9c84aa5e64917c7981acad2
|
5c5579ec1d32d35bb056545f753ba450e3b3b896
|
refs/heads/master
| 2021-01-10T08:47:21.335000 | 2016-01-17T06:59:04 | 2016-01-17T06:59:04 | 49,278,864 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package spring.learning.proxy.factory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/learning/proxy/factory/FactoryBeanApplicationContext.xml")
public class TestFactoryBean {
@Autowired
private Message message;
@Autowired
ApplicationContext context;
@Test
public void checkFactoryBean() {
System.out.println("message object is "+message);
System.out.println("message's text is "+message.getText());
Object messageBean = context.getBean("message");
assertThat(messageBean, is(Message.class));
assertThat(((Message)messageBean).getText(), is(message.getText()));
}
@Test
public void getFactoryBean() {
Object factory = context.getBean("&message");
assertThat(factory, is(MessageFactoryBean.class));
}
}
|
UTF-8
|
Java
| 1,164 |
java
|
TestFactoryBean.java
|
Java
|
[] | null |
[] |
package spring.learning.proxy.factory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/learning/proxy/factory/FactoryBeanApplicationContext.xml")
public class TestFactoryBean {
@Autowired
private Message message;
@Autowired
ApplicationContext context;
@Test
public void checkFactoryBean() {
System.out.println("message object is "+message);
System.out.println("message's text is "+message.getText());
Object messageBean = context.getBean("message");
assertThat(messageBean, is(Message.class));
assertThat(((Message)messageBean).getText(), is(message.getText()));
}
@Test
public void getFactoryBean() {
Object factory = context.getBean("&message");
assertThat(factory, is(MessageFactoryBean.class));
}
}
| 1,164 | 0.792955 | 0.790378 | 36 | 31.333334 | 26.095976 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.361111 | false | false |
12
|
c62757d664b8ed1c618a7bfdf09200b973e397a7
| 25,778,393,778,826 |
6baa0c1d27aa16991f7093e79cf0f1baf46df878
|
/jpro-core/src/main/java/net/anjero/pro/module/seo/pojo/Seo.java
|
c5132decdbb4d2c1194ab2ca54b688df44618455
|
[] |
no_license
|
Anjero/JPro
|
https://github.com/Anjero/JPro
|
932effd3732c25772897b6fbb2a7e9e7b30718d7
|
66bd4e6ff6af45ed593e00f253b35aa102bee525
|
refs/heads/master
| 2020-12-02T23:47:11.432000 | 2017-04-10T15:14:09 | 2017-04-10T15:14:09 | 66,539,465 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.anjero.pro.module.seo.pojo;
import java.io.Serializable;
public class Seo implements Serializable {
private Integer id;
private String title;
private Integer companyId;
private String iconPath;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
public Integer getCompanyId() {
return companyId;
}
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath == null ? null : iconPath.trim();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", title=").append(title);
sb.append(", companyId=").append(companyId);
sb.append(", iconPath=").append(iconPath);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
UTF-8
|
Java
| 1,447 |
java
|
Seo.java
|
Java
|
[] | null |
[] |
package net.anjero.pro.module.seo.pojo;
import java.io.Serializable;
public class Seo implements Serializable {
private Integer id;
private String title;
private Integer companyId;
private String iconPath;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
public Integer getCompanyId() {
return companyId;
}
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath == null ? null : iconPath.trim();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", title=").append(title);
sb.append(", companyId=").append(companyId);
sb.append(", iconPath=").append(iconPath);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
| 1,447 | 0.599171 | 0.59848 | 62 | 22.354839 | 19.680592 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
460ea7aa395ba8d1c1228df2c97e1578b9019e84
| 33,852,932,231,820 |
a243aeb0203ef68f17cd024e1697097afa04d4af
|
/tygameserver-slave/src/main/java/com/netease/pangu/game/distribution/MasterCallService.java
|
a0e586f310da2a8669e2d7cce9e1da7df7f98daa
|
[] |
no_license
|
wang-shun/tygameserver
|
https://github.com/wang-shun/tygameserver
|
b9051cab6b9ed94800ab2421f4acbc18cae5092b
|
eba46ad34b48cd85a34d5abbd30466d4cd4e0cfe
|
refs/heads/master
| 2020-03-29T14:07:21.203000 | 2017-03-10T13:03:37 | 2017-03-10T13:03:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.netease.pangu.game.distribution;
import com.netease.pangu.distribution.proto.MasterServiceGrpc;
import com.netease.pangu.distribution.proto.MasterServiceGrpc.MasterServiceBlockingStub;
import com.netease.pangu.distribution.proto.RpcResponse;
import com.netease.pangu.game.service.RoomService;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicBoolean;
@Service
public class MasterCallService {
@Resource
private RoomService gameRoomManager;
private MasterServiceBlockingStub stub;
private AtomicBoolean isInit = new AtomicBoolean(false);
public void init(String ip, int port) {
ManagedChannel channel = ManagedChannelBuilder.forAddress(ip, port).usePlaintext(true).build();
stub = MasterServiceGrpc.newBlockingStub(channel);
isInit.set(true);
}
public boolean isInit() {
return isInit.get();
}
public RpcResponse addOrUpdateSlave(Slave worker) {
com.netease.pangu.distribution.proto.Slave.Builder request = com.netease.pangu.distribution.proto.Slave.newBuilder();
request.setName(worker.getName());
request.setIp(worker.getIp());
request.setPort(worker.getPort());
request.setCount(worker.getCount());
RpcResponse response = null;
try {
response = stub.addOrUpdateSlave(request.build());
} catch (StatusRuntimeException e) {
e.printStackTrace();
}
return response;
}
}
|
UTF-8
|
Java
| 1,644 |
java
|
MasterCallService.java
|
Java
|
[] | null |
[] |
package com.netease.pangu.game.distribution;
import com.netease.pangu.distribution.proto.MasterServiceGrpc;
import com.netease.pangu.distribution.proto.MasterServiceGrpc.MasterServiceBlockingStub;
import com.netease.pangu.distribution.proto.RpcResponse;
import com.netease.pangu.game.service.RoomService;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicBoolean;
@Service
public class MasterCallService {
@Resource
private RoomService gameRoomManager;
private MasterServiceBlockingStub stub;
private AtomicBoolean isInit = new AtomicBoolean(false);
public void init(String ip, int port) {
ManagedChannel channel = ManagedChannelBuilder.forAddress(ip, port).usePlaintext(true).build();
stub = MasterServiceGrpc.newBlockingStub(channel);
isInit.set(true);
}
public boolean isInit() {
return isInit.get();
}
public RpcResponse addOrUpdateSlave(Slave worker) {
com.netease.pangu.distribution.proto.Slave.Builder request = com.netease.pangu.distribution.proto.Slave.newBuilder();
request.setName(worker.getName());
request.setIp(worker.getIp());
request.setPort(worker.getPort());
request.setCount(worker.getCount());
RpcResponse response = null;
try {
response = stub.addOrUpdateSlave(request.build());
} catch (StatusRuntimeException e) {
e.printStackTrace();
}
return response;
}
}
| 1,644 | 0.729927 | 0.729927 | 47 | 33.978722 | 27.348413 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617021 | false | false |
12
|
4a2e831360e70c29f99487c594c3003e7d3634b9
| 1,537,598,337,893 |
37506165b3204f842d769f43c8726e8eeea000c0
|
/hm/src/연결요소의개수_bfs_11724.java
|
33422a8ee4cc75f5fca39b0ed6fba2f7290162f9
|
[] |
no_license
|
HyunminKo/AlgorithmStudy
|
https://github.com/HyunminKo/AlgorithmStudy
|
33d0f016a3b62f02ffd7e71cf4f78e06b91fe48c
|
16b505ecf38be1e46b4cdfa94aadd43dc1c2867b
|
refs/heads/master
| 2020-04-30T00:48:01.465000 | 2020-01-22T08:16:17 | 2020-01-22T08:16:17 | 176,511,909 | 2 | 7 | null | false | 2019-07-03T05:57:36 | 2019-03-19T12:56:00 | 2019-07-03T05:39:42 | 2019-07-03T05:57:36 | 122 | 0 | 1 | 0 |
Java
| false | false |
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class 연결요소의개수_bfs_11724 {
static int N,M;
static int[][] adjMatrix;
static boolean[] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt(); M = sc.nextInt();
adjMatrix = new int[N][N];
visited= new boolean[N];
for(int i = 0 ; i < M; i++){
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjMatrix[u][v] = 1;
adjMatrix[v][u] = 1;
}
int result = 0;
Queue<Integer> q = new LinkedList<>();
for(int i = 0 ; i < N; i++){
if(!visited[i]){
q.offer(i);
visited[i] = true;
while(!q.isEmpty()){
int p = q.poll();
for(int j = 0 ; j < N; j++){
if(p == j || visited[j] || adjMatrix[p][j] == 0) continue;
q.offer(j);
visited[j] = true;
}
}
result++;
}
}
System.out.println(result);
}
}
|
UTF-8
|
Java
| 1,218 |
java
|
연결요소의개수_bfs_11724.java
|
Java
|
[] | null |
[] |
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class 연결요소의개수_bfs_11724 {
static int N,M;
static int[][] adjMatrix;
static boolean[] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt(); M = sc.nextInt();
adjMatrix = new int[N][N];
visited= new boolean[N];
for(int i = 0 ; i < M; i++){
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjMatrix[u][v] = 1;
adjMatrix[v][u] = 1;
}
int result = 0;
Queue<Integer> q = new LinkedList<>();
for(int i = 0 ; i < N; i++){
if(!visited[i]){
q.offer(i);
visited[i] = true;
while(!q.isEmpty()){
int p = q.poll();
for(int j = 0 ; j < N; j++){
if(p == j || visited[j] || adjMatrix[p][j] == 0) continue;
q.offer(j);
visited[j] = true;
}
}
result++;
}
}
System.out.println(result);
}
}
| 1,218 | 0.416944 | 0.405316 | 39 | 29.871796 | 14.690271 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false |
12
|
ac619978ee16f3b8fcf7b99c712682f6972c85aa
| 20,263,655,766,356 |
40afd38f9e3d8623d88f87eaa7f4ea2bb1ffc897
|
/src/main/java/pl/pstarzyk/vouchershop/catalog/JdbcProductStorage.java
|
caa1b2a98210deb019088078f7f494ae1cc2d7a6
|
[] |
no_license
|
starzykp/pp5-20-21
|
https://github.com/starzykp/pp5-20-21
|
9865fb6fa6723dc38e0d8abb7f73454b69d07319
|
ea7cec051274d99324061630a2b273fd99a68be1
|
refs/heads/main
| 2023-03-20T02:35:14.862000 | 2021-03-03T10:27:37 | 2021-03-03T10:27:37 | 344,085,521 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pl.pstarzyk.vouchershop.catalog;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Optional;
public class JdbcProductStorage implements ProductStorage {
private final JdbcTemplate jdbcTemplate;
public JdbcProductStorage(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void save(Product product) {
jdbcTemplate.update("INSERT INTO `products_catalog__products` " +
"(`id`, `description`, `picture`, `price`) values " +
"(?,?,?,?)",
product.getId(),
product.getDescription(),
product.getPicture(),
product.getPrice()
);
}
@Override
public boolean isExists(String productId) {
int productsCount = jdbcTemplate.queryForObject(
"Select count(*) from `products_catalog__products` where id = ?",
new Object[]{productId},
Integer.class
);
return productsCount > 0;
}
@Override
public Optional<Product> load(String productId) {
return null;
}
@Override
public List<Product> allProducts() {
return null;
}
@Override
public void clean() {
jdbcTemplate.execute("delete form `products_catalog__products`");
}
}
|
UTF-8
|
Java
| 1,395 |
java
|
JdbcProductStorage.java
|
Java
|
[
{
"context": "package pl.pstarzyk.vouchershop.catalog;\n\n\nimport org.springframework",
"end": 19,
"score": 0.738448441028595,
"start": 12,
"tag": "USERNAME",
"value": "starzyk"
}
] | null |
[] |
package pl.pstarzyk.vouchershop.catalog;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Optional;
public class JdbcProductStorage implements ProductStorage {
private final JdbcTemplate jdbcTemplate;
public JdbcProductStorage(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void save(Product product) {
jdbcTemplate.update("INSERT INTO `products_catalog__products` " +
"(`id`, `description`, `picture`, `price`) values " +
"(?,?,?,?)",
product.getId(),
product.getDescription(),
product.getPicture(),
product.getPrice()
);
}
@Override
public boolean isExists(String productId) {
int productsCount = jdbcTemplate.queryForObject(
"Select count(*) from `products_catalog__products` where id = ?",
new Object[]{productId},
Integer.class
);
return productsCount > 0;
}
@Override
public Optional<Product> load(String productId) {
return null;
}
@Override
public List<Product> allProducts() {
return null;
}
@Override
public void clean() {
jdbcTemplate.execute("delete form `products_catalog__products`");
}
}
| 1,395 | 0.592832 | 0.592115 | 53 | 25.320755 | 23.327669 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45283 | false | false |
12
|
9f4cd3810e05798677ed0a19db8cc76f4c736be1
| 20,916,490,783,151 |
d2bc6d1d1ccf4aafc134b1de454ee028457b0192
|
/src/test2/place.java
|
8504b82afb15d254f01e3c10922a23b9ea54d820
|
[] |
no_license
|
John-ken/test
|
https://github.com/John-ken/test
|
88e8083bfa925cf3ec1a0420b96cc00263db955e
|
fb8f305699bd951972829f1d1f744d0ecc587be9
|
refs/heads/master
| 2021-01-11T11:16:29.037000 | 2017-06-21T14:52:23 | 2017-06-21T14:52:23 | 95,013,524 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package test2;
public class place {
String name ;
public place(){}
public place(String i){
name = i;
}
}
|
UTF-8
|
Java
| 112 |
java
|
place.java
|
Java
|
[] | null |
[] |
package test2;
public class place {
String name ;
public place(){}
public place(String i){
name = i;
}
}
| 112 | 0.642857 | 0.633929 | 9 | 11.444445 | 8.193644 | 24 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
12
|
185d02c8e4afaacaddf7c8c40eeb7611fd4c7162
| 32,246,614,458,377 |
c9b7b6fc3a66a13a7b4f4466c866cc78ecdc6639
|
/Constructor (1).java
|
9fd092bb01b4dbfdec8b2153b926ad6854fd35b2
|
[] |
no_license
|
Abhishek-Gupta-lab/Java
|
https://github.com/Abhishek-Gupta-lab/Java
|
9e1c66a4384a26289cf2e291021436d61184ebc9
|
143889c97dcca2fcb83eaedacf451c75cf438f5c
|
refs/heads/main
| 2023-01-20T04:24:03.335000 | 2020-11-30T05:00:48 | 2020-11-30T05:00:48 | 313,049,914 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Constructor
{
int n1,n2;
Constructor ()
{
n1=18;
n2=19;
}
Constructor(int x)
{
n1=x;
}
Constructor(int x,int y)
{
n1=x;
n2=y;
}
public void display()
{
System.out.println("Value1 = "+n1);
System.out.println("Value2 = "+n2);
}
public static void main(String args[])
{
Constructor d1 = new Constructor();
Constructor d2 = new Constructor(20);
Constructor d3 = new Constructor (20,30);
System.out.println("Inside default Constructor");
d1.display();
System.out.println("Inside parameterized Constructor1");
d2.display();
System.out.println("Inside parameterized Constructor2");
d3.display();
}
}
|
UTF-8
|
Java
| 797 |
java
|
Constructor (1).java
|
Java
|
[] | null |
[] |
public class Constructor
{
int n1,n2;
Constructor ()
{
n1=18;
n2=19;
}
Constructor(int x)
{
n1=x;
}
Constructor(int x,int y)
{
n1=x;
n2=y;
}
public void display()
{
System.out.println("Value1 = "+n1);
System.out.println("Value2 = "+n2);
}
public static void main(String args[])
{
Constructor d1 = new Constructor();
Constructor d2 = new Constructor(20);
Constructor d3 = new Constructor (20,30);
System.out.println("Inside default Constructor");
d1.display();
System.out.println("Inside parameterized Constructor1");
d2.display();
System.out.println("Inside parameterized Constructor2");
d3.display();
}
}
| 797 | 0.544542 | 0.508156 | 35 | 21.799999 | 18.522264 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
12
|
bbe1ed309d6d88df94161e588993818ecde8f8a0
| 9,929,964,405,122 |
e96650aeb62075770e8dd05e839a8205b60db0d1
|
/src/main/java/com/example/test/search/repository/SearchBookRestTemplate.java
|
e9bf83efc178f79a44ec68c991bfc31543cf4300
|
[
"Apache-2.0"
] |
permissive
|
ehbread/springtest
|
https://github.com/ehbread/springtest
|
d77c75280b2b1f548a48766d92565d1827236414
|
af9847dfec9fa3ffa59710bb5c8921d42dab9b3e
|
refs/heads/master
| 2020-03-22T14:53:43.677000 | 2018-07-15T00:53:47 | 2018-07-15T00:53:47 | 140,213,227 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.test.search.repository;
import java.net.URI;
import com.example.test.common.RestTemplateFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class SearchBookRestTemplate {
@Value("${appkey.kakao}")
private String appKey;
@Autowired
private RestTemplateFactory restTemplateFactory;
private HttpEntity<?> createHttpEntity(MultiValueMap<String, Object> paramMap) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Authorization", "KakaoAK " + appKey);
return new HttpEntity<>(paramMap, requestHeaders);
}
public <T> ResponseEntity<T> getSearch(MultiValueMap<String, Object> paramMap, Class<T> clazz) {
try {
return restTemplateFactory.getRestTemplate().exchange(getUrl(), HttpMethod.POST, createHttpEntity(paramMap), clazz);
} catch (Exception e) {
log.error("통신실패", e);
}
return null;
}
private URI getUrl() {
UriComponents uriCompornent = UriComponentsBuilder.newInstance().scheme("https").host("dapi.kakao.com").path("/v2/search/book").build();
return uriCompornent.toUri();
}
}
|
UTF-8
|
Java
| 1,598 |
java
|
SearchBookRestTemplate.java
|
Java
|
[] | null |
[] |
package com.example.test.search.repository;
import java.net.URI;
import com.example.test.common.RestTemplateFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class SearchBookRestTemplate {
@Value("${appkey.kakao}")
private String appKey;
@Autowired
private RestTemplateFactory restTemplateFactory;
private HttpEntity<?> createHttpEntity(MultiValueMap<String, Object> paramMap) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Authorization", "KakaoAK " + appKey);
return new HttpEntity<>(paramMap, requestHeaders);
}
public <T> ResponseEntity<T> getSearch(MultiValueMap<String, Object> paramMap, Class<T> clazz) {
try {
return restTemplateFactory.getRestTemplate().exchange(getUrl(), HttpMethod.POST, createHttpEntity(paramMap), clazz);
} catch (Exception e) {
log.error("통신실패", e);
}
return null;
}
private URI getUrl() {
UriComponents uriCompornent = UriComponentsBuilder.newInstance().scheme("https").host("dapi.kakao.com").path("/v2/search/book").build();
return uriCompornent.toUri();
}
}
| 1,598 | 0.786792 | 0.784277 | 55 | 27.927273 | 31.39592 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.218182 | false | false |
12
|
613d7367de9f99761ca6472a51540af927f862e0
| 3,770,981,292,089 |
4fea8d26c70ccdb1f815aa35c0939fd02da2aaf1
|
/ProjektTekken/src/com/company/Atak.java
|
dd38e70368edd3c0388e61b1794cd6d6ba5eb360
|
[] |
no_license
|
MikeW210/PAI-projekt
|
https://github.com/MikeW210/PAI-projekt
|
d7a6650a0d61421e8c32fad2393d39f231c68656
|
e39e65bf3ada6e619cb88a1d9401dff543263ce7
|
refs/heads/master
| 2020-04-22T15:54:19.342000 | 2019-02-13T10:55:21 | 2019-02-13T10:55:21 | 170,491,305 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company;
import java.util.ArrayList;
import java.util.Random;
public class Atak {
public static ArrayList<String> ataki = new ArrayList<>();
static{
ataki.add("Kopniak z półobrotu!");
ataki.add("Unik i prawy sierpowy!");
ataki.add("Szybki atak z zaskoczenia!");
ataki.add("Z kolana w brzuch!");
ataki.add("Prawy prosty i lewy podbródkowy!");
ataki.add("Ależ uniki, ależ on to zrobił!");
}
public Atak(){
}
static String sendAtak(){
Random random = new Random();
int random2 = random.nextInt(ataki.size());
return (String)ataki.get(random2);
}
}
|
UTF-8
|
Java
| 698 |
java
|
Atak.java
|
Java
|
[] | null |
[] |
package com.company;
import java.util.ArrayList;
import java.util.Random;
public class Atak {
public static ArrayList<String> ataki = new ArrayList<>();
static{
ataki.add("Kopniak z półobrotu!");
ataki.add("Unik i prawy sierpowy!");
ataki.add("Szybki atak z zaskoczenia!");
ataki.add("Z kolana w brzuch!");
ataki.add("Prawy prosty i lewy podbródkowy!");
ataki.add("Ależ uniki, ależ on to zrobił!");
}
public Atak(){
}
static String sendAtak(){
Random random = new Random();
int random2 = random.nextInt(ataki.size());
return (String)ataki.get(random2);
}
}
| 698 | 0.583815 | 0.580925 | 28 | 22.714285 | 20.514555 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
b3778c1dcf333509b0f441adc61a6a846efbca7e
| 15,401,752,793,326 |
d010373b6370d70df1b51189ff3fc0e44f3a8b8e
|
/app/src/main/java/com/whl/hp/work_house/tool/Config.java
|
76e49138c64fc830e847d395ef4c3308dcf8d51d
|
[] |
no_license
|
violinlin/Work_House
|
https://github.com/violinlin/Work_House
|
a0cf267eb6e1c7f9569137d338f29ac8ad8cd3e1
|
11f53bf580e9bfc263087a5b466eb11731f9d692
|
refs/heads/master
| 2021-01-10T01:26:12.988000 | 2015-10-15T12:34:44 | 2015-10-15T12:34:44 | 44,315,487 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.whl.hp.work_house.tool;
/**
* Created by hp-whl on 2015/9/23.
*/
public class Config {
//城市列表信息
public static final String CHOICE_CITY = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_" +
"Android19&act=kftcitylistnew&channel=71&devid=866500021200250&appname=QQHouse&mod=appkft";
// viewpagerde显示的图片信息
public static final String FIRST_PAGE_WEBVIEW = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920" +
"_XiaomiMI4LTE_1.8.3_Android19&devid=866500021200250&appname=QQHou" +
"se&mod=appkft&act=homepage&channel=71&cityid=%s";
//listView 的详情url
public static final String FIRST_PAGE_LISTVIEW = "http://ikft.house.qq.com/index.php?gu" +
"id=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&devid=8665" +
"00021200250&appname=QQHouse&mod=appkft&reqnum=%d&pageflag=%d&act=newslist&channel=71&buttonmore=%d&cityid=%s";
//资讯详情
public static final String NEWS_DETAIL = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&" +
"devid=866500021200250&appname=QQHouse&mod=appkft&act=newsdetail&channel=71&newsid=%s";
// 资讯评论详情
public static final String NEWS_COMMENT = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&devid=866500021200250&appname=QQHouse&mod=app" +
"kft&reqnum=20&pageflag=0&act=newscomment&channel=71&targetid=%s";
//找房
public static final String LOOKING_NEWHOUSE = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&rn=10&order=0&searchtype=normal&devid=8665000" +
"21200250&page=%d&appname=QQHouse&mod=appkft&act=searchhouse&channel=71&cityid=%s";
//新房详情
public static final String NEW_HOUSE_INFO = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3" +
"_Android19&hid=%s&devid=866500021200250&appname=QQHouse&mod=appkft&act=houseinfo&channel=71";
/**
* 找新房 评论
*/
public static final String NEW_HOUSE_COMMENT = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_A" +
"ndroid19&rn=0&hid=%s&devid=866500021200250&page=1&appname=QQHouse&mod=appkft&type=all&act=housecomment&channel=71";
//打折优惠 楼盘信息
public static final String DISCOUNT_SEAL = "http://ikft.house.qq.com/index.php?&page=%d&appname=QQHouse&mo" +
"d=appkft&act=discountslist&channel=71&cityid=1";
/**
* 打折优惠 楼盘评论
*/
public static final String DISCOUNT_HOUSE_COMMENT = "http://ikft.house.qq.com/index.php?&rn=0&hid=%s&page=1&appname=QQHouse&mod=appkft&typ" +
"e=all&act=housecomment&channel=%s";
/**
* 最新开盘
*/
public static final String NEWEST_HOUSE = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&rn=10&order=0&searchtype=normal&devid=866500021200250" +
"&page=%d&appname=QQHouse&mod=appkft&feature=996&act=searchhouse&channel=71&cityid=%s";
/**
* 看房团
*/
public static final String TEAM_HOUSE = "http://ikft.house.qq.com/index.php?guid=000000000000000&devua=appkft_1080_1776_GenymotionSamsungGalaxyS5-4.4.4-API19-1080x1920_1.8.3_Android19&devid=000000000000000&" +
"appname=QQHouse&mod=appkft&act=kftlist&channel=65&cityid=%s";
// 二手房:
public static String ERSHOU_URL="http://esf.db.house.qq.com/bj/search/sale/?rf=kanfang";
// 租房:
public static String ZUFANG_URL="http://esf.db.house.qq.com/bj/search/lease/?rf=kanfang";
// 资讯:
public static String ZIXUN_URL=" http://ikft.house.qq.com/index.php?devua=appkft_720_1280_XiaomiMI2A_2.3_Android19&devid=860954025171452&mod=appkft&buttonmore=1&cityid=%s&guid=860954025171452&appname=" +
"QQHouse&huid=H489647634&reqnum=20&pageflag=0&majorversion=v2&act=newslist&channel=27";
}
|
UTF-8
|
Java
| 4,227 |
java
|
Config.java
|
Java
|
[
{
"context": "age com.whl.hp.work_house.tool;\n\n/**\n * Created by hp-whl on 2015/9/23.\n */\npublic class Config {\n //城市列",
"end": 61,
"score": 0.9991794228553772,
"start": 55,
"tag": "USERNAME",
"value": "hp-whl"
}
] | null |
[] |
package com.whl.hp.work_house.tool;
/**
* Created by hp-whl on 2015/9/23.
*/
public class Config {
//城市列表信息
public static final String CHOICE_CITY = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_" +
"Android19&act=kftcitylistnew&channel=71&devid=866500021200250&appname=QQHouse&mod=appkft";
// viewpagerde显示的图片信息
public static final String FIRST_PAGE_WEBVIEW = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920" +
"_XiaomiMI4LTE_1.8.3_Android19&devid=866500021200250&appname=QQHou" +
"se&mod=appkft&act=homepage&channel=71&cityid=%s";
//listView 的详情url
public static final String FIRST_PAGE_LISTVIEW = "http://ikft.house.qq.com/index.php?gu" +
"id=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&devid=8665" +
"00021200250&appname=QQHouse&mod=appkft&reqnum=%d&pageflag=%d&act=newslist&channel=71&buttonmore=%d&cityid=%s";
//资讯详情
public static final String NEWS_DETAIL = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&" +
"devid=866500021200250&appname=QQHouse&mod=appkft&act=newsdetail&channel=71&newsid=%s";
// 资讯评论详情
public static final String NEWS_COMMENT = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&devid=866500021200250&appname=QQHouse&mod=app" +
"kft&reqnum=20&pageflag=0&act=newscomment&channel=71&targetid=%s";
//找房
public static final String LOOKING_NEWHOUSE = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&rn=10&order=0&searchtype=normal&devid=8665000" +
"21200250&page=%d&appname=QQHouse&mod=appkft&act=searchhouse&channel=71&cityid=%s";
//新房详情
public static final String NEW_HOUSE_INFO = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3" +
"_Android19&hid=%s&devid=866500021200250&appname=QQHouse&mod=appkft&act=houseinfo&channel=71";
/**
* 找新房 评论
*/
public static final String NEW_HOUSE_COMMENT = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_A" +
"ndroid19&rn=0&hid=%s&devid=866500021200250&page=1&appname=QQHouse&mod=appkft&type=all&act=housecomment&channel=71";
//打折优惠 楼盘信息
public static final String DISCOUNT_SEAL = "http://ikft.house.qq.com/index.php?&page=%d&appname=QQHouse&mo" +
"d=appkft&act=discountslist&channel=71&cityid=1";
/**
* 打折优惠 楼盘评论
*/
public static final String DISCOUNT_HOUSE_COMMENT = "http://ikft.house.qq.com/index.php?&rn=0&hid=%s&page=1&appname=QQHouse&mod=appkft&typ" +
"e=all&act=housecomment&channel=%s";
/**
* 最新开盘
*/
public static final String NEWEST_HOUSE = "http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&rn=10&order=0&searchtype=normal&devid=866500021200250" +
"&page=%d&appname=QQHouse&mod=appkft&feature=996&act=searchhouse&channel=71&cityid=%s";
/**
* 看房团
*/
public static final String TEAM_HOUSE = "http://ikft.house.qq.com/index.php?guid=000000000000000&devua=appkft_1080_1776_GenymotionSamsungGalaxyS5-4.4.4-API19-1080x1920_1.8.3_Android19&devid=000000000000000&" +
"appname=QQHouse&mod=appkft&act=kftlist&channel=65&cityid=%s";
// 二手房:
public static String ERSHOU_URL="http://esf.db.house.qq.com/bj/search/sale/?rf=kanfang";
// 租房:
public static String ZUFANG_URL="http://esf.db.house.qq.com/bj/search/lease/?rf=kanfang";
// 资讯:
public static String ZIXUN_URL=" http://ikft.house.qq.com/index.php?devua=appkft_720_1280_XiaomiMI2A_2.3_Android19&devid=860954025171452&mod=appkft&buttonmore=1&cityid=%s&guid=860954025171452&appname=" +
"QQHouse&huid=H489647634&reqnum=20&pageflag=0&majorversion=v2&act=newslist&channel=27";
}
| 4,227 | 0.706774 | 0.570555 | 67 | 60.02985 | 64.509392 | 213 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.238806 | false | false |
12
|
d376334b7f4b3ff1027e5a3ec4ebd8e0c0c36268
| 15,401,752,793,913 |
1a4b29179c353cfb326bb5e1b5ba95019e5ed858
|
/src/main/java/com/sogaa/system/service/part/dao/IPartDao.java
|
2c1415081521cacb248461f05e1009c66cf82542
|
[] |
no_license
|
qkq5539/sogaa-web
|
https://github.com/qkq5539/sogaa-web
|
219f0f224ce0bb7f32b2a191118a2e6866692b88
|
283f023e0a878769c8fabf7831533d7f40176e5a
|
refs/heads/master
| 2017-05-11T05:26:39.541000 | 2017-02-20T13:09:19 | 2017-02-20T13:09:19 | 82,620,688 | 2 | 0 | null | true | 2017-02-21T01:17:45 | 2017-02-21T01:17:45 | 2017-02-21T01:07:11 | 2017-02-20T13:09:36 | 5,734 | 0 | 0 | 0 | null | null | null |
package com.sogaa.system.service.part.dao;
import java.util.List;
import com.sogaa.system.service.part.bean.Part;
public interface IPartDao {
int insertPartBatch(List<Part> list);
}
|
UTF-8
|
Java
| 195 |
java
|
IPartDao.java
|
Java
|
[] | null |
[] |
package com.sogaa.system.service.part.dao;
import java.util.List;
import com.sogaa.system.service.part.bean.Part;
public interface IPartDao {
int insertPartBatch(List<Part> list);
}
| 195 | 0.74359 | 0.74359 | 9 | 19.666666 | 18.708286 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
12
|
615f38da1f7be1dd8461f4473237ff51fb5640d4
| 28,673,201,710,998 |
37e894abf347fba327ab40076fab854e0aecf1f4
|
/SpringBootApps/orderbootapp/src/main/java/com/rakuten/ProductClient.java
|
26a422e2a7fdc22e9ac1b01922dbb23a6312b7d2
|
[] |
no_license
|
NishanthNagendra/testrep
|
https://github.com/NishanthNagendra/testrep
|
009a210f24481094ad8fa295e3029bc3da7922cd
|
09c3944f276587570530b829297714f76ea64447
|
refs/heads/master
| 2023-01-13T20:40:55.364000 | 2020-01-26T11:29:49 | 2020-01-26T11:29:49 | 233,175,359 | 0 | 0 | null | false | 2023-01-05T05:24:53 | 2020-01-11T04:21:20 | 2020-01-26T11:30:02 | 2023-01-05T05:24:52 | 2,299 | 0 | 0 | 51 |
Java
| false | false |
/**
*
*/
package com.rakuten;
import java.util.Arrays;
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.rakuten.prj.entity.Product;
/**
* @author nishanth
*
*/
public class ProductClient {
/**
* @param args
*/
public static void main(String[] args) {
String uri = "http://localhost:8080/products";
RestTemplate template = new RestTemplate(); // template to make REST calls
getProductJson(template, uri);
getProductList(template, uri);
// addProduct(template, uri); // add product to database
}
// Body to post product
// {
// "name": "REST Product",
// "price": 2000,
// "category": "test",
// "qty": 100
// }
// private static void addProduct(RestTemplate template, String uri) {
// HttpHeaders headers = new HttpHeaders();
// headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
// headers.setContentType(MediaType.APPLICATION_JSON);
//
// Product p = new Product(0, "Adidas", 12000.00, "shoes", 100);
//
// ResponseEntity<Product> response = template.postForEntity(uri, p, Product.class);
// System.out.println(response.getStatusCode());
// System.out.println("Saved Product : " + response.getBody().getId());
// }
private static void getProductList(RestTemplate template, String uri) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
ResponseEntity<List<Product>> response = template.exchange(uri, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Product>>() {
});
System.out.println(response.getStatusCode());
List<Product> products = response.getBody();
for (Product p : products) {
System.out.println(p.getName() + "," + p.getPrice());
}
}
private static void getProductJson(RestTemplate template, String uri) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String productjson = template.getForObject(uri, String.class);
System.out.println(productjson);
}
}
|
UTF-8
|
Java
| 2,452 |
java
|
ProductClient.java
|
Java
|
[
{
"context": "rt com.rakuten.prj.entity.Product;\n\n/**\n * @author nishanth\n *\n */\npublic class ProductClient {\n\n\t/**\n\t * @pa",
"end": 439,
"score": 0.9956827163696289,
"start": 431,
"tag": "USERNAME",
"value": "nishanth"
}
] | null |
[] |
/**
*
*/
package com.rakuten;
import java.util.Arrays;
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.rakuten.prj.entity.Product;
/**
* @author nishanth
*
*/
public class ProductClient {
/**
* @param args
*/
public static void main(String[] args) {
String uri = "http://localhost:8080/products";
RestTemplate template = new RestTemplate(); // template to make REST calls
getProductJson(template, uri);
getProductList(template, uri);
// addProduct(template, uri); // add product to database
}
// Body to post product
// {
// "name": "REST Product",
// "price": 2000,
// "category": "test",
// "qty": 100
// }
// private static void addProduct(RestTemplate template, String uri) {
// HttpHeaders headers = new HttpHeaders();
// headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
// headers.setContentType(MediaType.APPLICATION_JSON);
//
// Product p = new Product(0, "Adidas", 12000.00, "shoes", 100);
//
// ResponseEntity<Product> response = template.postForEntity(uri, p, Product.class);
// System.out.println(response.getStatusCode());
// System.out.println("Saved Product : " + response.getBody().getId());
// }
private static void getProductList(RestTemplate template, String uri) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
ResponseEntity<List<Product>> response = template.exchange(uri, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Product>>() {
});
System.out.println(response.getStatusCode());
List<Product> products = response.getBody();
for (Product p : products) {
System.out.println(p.getName() + "," + p.getPrice());
}
}
private static void getProductJson(RestTemplate template, String uri) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String productjson = template.getForObject(uri, String.class);
System.out.println(productjson);
}
}
| 2,452 | 0.666803 | 0.65783 | 80 | 29.65 | 28.114986 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8875 | false | false |
12
|
f6bcf648d5da28cfd62f168f500048417d1425b3
| 18,580,028,525,866 |
a91a478807100c91ddd4d9db1914744ddc84dcf4
|
/app/src/main/java/com/junrrein/proyectofinal/backend/EventoRoom.java
|
d0688133f1fdee375e04d13785a7939b3c1acf5d
|
[] |
no_license
|
junrrein/proyecto-dismov
|
https://github.com/junrrein/proyecto-dismov
|
f823c374dbff9edd57a126c06ccbd33e684d4497
|
872d65abd0ae3b9985dbcc94d518ca4c85359bfd
|
refs/heads/master
| 2022-04-12T20:32:01.934000 | 2020-03-05T20:26:36 | 2020-03-05T20:26:36 | 231,671,657 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.junrrein.proyectofinal.backend;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
@Entity(tableName = "eventos")
public class EventoRoom {
@NonNull
@PrimaryKey
public String id = "";
public String nombre;
public String idUsuarioCreador;
public Double latitud;
public Double longitud;
public String fechaInicio;
public String horaInicio;
public Integer duracion;
public String descripcion;
public String tipo;
public Integer dislikes;
public String idUsuariosInteresados;
public String idUsuariosAsistentes;
public long ultimaActualizacion;
EventoRoom() {
}
EventoRoom(Evento evento) {
id = evento.getId();
nombre = evento.getNombre();
idUsuarioCreador = evento.getIdUsuarioCreador();
Ubicacion ubicacion = evento.getUbicacion();
latitud = ubicacion.latitud;
longitud = ubicacion.longitud;
fechaInicio = evento.getFechaInicio().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
horaInicio = evento.getHoraInicio().format(DateTimeFormatter.ofPattern("HH:mm"));
duracion = evento.getDuracion();
descripcion = evento.getDescripcion();
tipo = evento.getTipo();
dislikes = evento.getDislikes();
idUsuariosInteresados = String.join(" ", evento.getIdUsuariosInteresados());
idUsuariosAsistentes = String.join(" ", evento.getIdUsuariosAsistentes());
ultimaActualizacion = Instant.now().getEpochSecond();
}
}
|
UTF-8
|
Java
| 1,636 |
java
|
EventoRoom.java
|
Java
|
[] | null |
[] |
package com.junrrein.proyectofinal.backend;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
@Entity(tableName = "eventos")
public class EventoRoom {
@NonNull
@PrimaryKey
public String id = "";
public String nombre;
public String idUsuarioCreador;
public Double latitud;
public Double longitud;
public String fechaInicio;
public String horaInicio;
public Integer duracion;
public String descripcion;
public String tipo;
public Integer dislikes;
public String idUsuariosInteresados;
public String idUsuariosAsistentes;
public long ultimaActualizacion;
EventoRoom() {
}
EventoRoom(Evento evento) {
id = evento.getId();
nombre = evento.getNombre();
idUsuarioCreador = evento.getIdUsuarioCreador();
Ubicacion ubicacion = evento.getUbicacion();
latitud = ubicacion.latitud;
longitud = ubicacion.longitud;
fechaInicio = evento.getFechaInicio().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
horaInicio = evento.getHoraInicio().format(DateTimeFormatter.ofPattern("HH:mm"));
duracion = evento.getDuracion();
descripcion = evento.getDescripcion();
tipo = evento.getTipo();
dislikes = evento.getDislikes();
idUsuariosInteresados = String.join(" ", evento.getIdUsuariosInteresados());
idUsuariosAsistentes = String.join(" ", evento.getIdUsuariosAsistentes());
ultimaActualizacion = Instant.now().getEpochSecond();
}
}
| 1,636 | 0.700489 | 0.700489 | 51 | 31.078432 | 22.563934 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72549 | false | false |
12
|
e8ed23f40ccdddc3b2c1435ff12de8d1273491fd
| 12,652,973,714,116 |
f5c60589a6c6d1a73d0f92344bfd7c8936bdcf69
|
/app/src/main/java/com/scale/tribal/spotter/MapsActivity.java
|
7023a4f9141f8f912c35471a793c0013d8115e16
|
[] |
no_license
|
SaifJamilKhan/SpottrAndroid
|
https://github.com/SaifJamilKhan/SpottrAndroid
|
12da0bd0282cc7120bc6cc1b64de372eb7409fa6
|
b9a42c513e6414d69d5acccb8c8c4772859105fb
|
refs/heads/master
| 2021-09-03T07:25:20.945000 | 2018-01-07T00:57:53 | 2018-01-07T00:57:53 | 112,080,090 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.scale.tribal.spotter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "daren";
private GoogleMap mMap;
private ImageButton voiceInputBtn;
private SpeechRecognizer sr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
voiceInputBtn = findViewById(R.id.voice_input_btn);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
voiceInputBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
Log.i("111111","11111111");
voiceInputBtn.setEnabled(false);
voiceInputBtn.setAlpha(0.5f);
// scaleView(voiceInputBtn, 1.2f, 1);
}
});
navigateToMyLocation();
}
@SuppressLint("MissingPermission")
private void navigateToMyLocation() {
LocationManager lm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location gps_loc;
Location net_loc;
if (gps_enabled) {
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng();
}
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// mMap.animateCamera(cameraUpdate);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(sydney);
mMap.moveCamera(cameraUpdate);
}
class listener implements RecognitionListener
{
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
// mText.setText("error " + error);
}
public void onResults(Bundle results)
{
voiceInputBtn.setEnabled(true);
voiceInputBtn.setAlpha(1.0f);
Log.d(TAG, "onResults " + results);
ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
String text = (String) data.get(i);
Log.d(TAG, "result " + data.get(i));
if(isFindCommand(text)) {
int parkingNearIndex = text.indexOf("parking near");
final String address = text.substring(parkingNearIndex, text.length());
Log.v(TAG, "address found " + address);
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
navigateToAddress(address);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
return;
}
// mText.setText("results: "+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
private void navigateToAddress(String address) throws IOException {
Geocoder gc = new Geocoder(this);
List<Address> addresses = gc.getFromLocationName(address, 1);
Log.v(TAG, "trying address " + address);
if(addresses.size() > 0) {
Address firstAddress = addresses.get(0);
Log.v(TAG, "found addresses" + addresses.size());
CameraUpdate center =
CameraUpdateFactory.newLatLng(new LatLng(firstAddress.getLatitude(),
firstAddress.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mMap.animateCamera(center);
mMap.animateCamera(zoom);
}
}
private boolean isFindCommand(String text) {
String lowerText = text.toLowerCase();
return lowerText.contains("parking near");
}
public void scaleView(View v, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
startScale, endScale, // Start and end values for the X axis scaling
startScale, startScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_PARENT, 0.5f, // Pivot point of X scaling
Animation.RELATIVE_TO_PARENT, 0.5f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(500);
v.startAnimation(anim);
}
}
|
UTF-8
|
Java
| 8,207 |
java
|
MapsActivity.java
|
Java
|
[
{
"context": "allback {\n\n private static final String TAG = \"daren\";\n private GoogleMap mMap;\n private ImageBu",
"end": 1226,
"score": 0.9107410907745361,
"start": 1221,
"tag": "USERNAME",
"value": "daren"
}
] | null |
[] |
package com.scale.tribal.spotter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "daren";
private GoogleMap mMap;
private ImageButton voiceInputBtn;
private SpeechRecognizer sr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
voiceInputBtn = findViewById(R.id.voice_input_btn);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
voiceInputBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
Log.i("111111","11111111");
voiceInputBtn.setEnabled(false);
voiceInputBtn.setAlpha(0.5f);
// scaleView(voiceInputBtn, 1.2f, 1);
}
});
navigateToMyLocation();
}
@SuppressLint("MissingPermission")
private void navigateToMyLocation() {
LocationManager lm = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location gps_loc;
Location net_loc;
if (gps_enabled) {
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng();
}
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// mMap.animateCamera(cameraUpdate);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(sydney);
mMap.moveCamera(cameraUpdate);
}
class listener implements RecognitionListener
{
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
// mText.setText("error " + error);
}
public void onResults(Bundle results)
{
voiceInputBtn.setEnabled(true);
voiceInputBtn.setAlpha(1.0f);
Log.d(TAG, "onResults " + results);
ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
String text = (String) data.get(i);
Log.d(TAG, "result " + data.get(i));
if(isFindCommand(text)) {
int parkingNearIndex = text.indexOf("parking near");
final String address = text.substring(parkingNearIndex, text.length());
Log.v(TAG, "address found " + address);
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
navigateToAddress(address);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
return;
}
// mText.setText("results: "+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
private void navigateToAddress(String address) throws IOException {
Geocoder gc = new Geocoder(this);
List<Address> addresses = gc.getFromLocationName(address, 1);
Log.v(TAG, "trying address " + address);
if(addresses.size() > 0) {
Address firstAddress = addresses.get(0);
Log.v(TAG, "found addresses" + addresses.size());
CameraUpdate center =
CameraUpdateFactory.newLatLng(new LatLng(firstAddress.getLatitude(),
firstAddress.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mMap.animateCamera(center);
mMap.animateCamera(zoom);
}
}
private boolean isFindCommand(String text) {
String lowerText = text.toLowerCase();
return lowerText.contains("parking near");
}
public void scaleView(View v, float startScale, float endScale) {
Animation anim = new ScaleAnimation(
startScale, endScale, // Start and end values for the X axis scaling
startScale, startScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_PARENT, 0.5f, // Pivot point of X scaling
Animation.RELATIVE_TO_PARENT, 0.5f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setDuration(500);
v.startAnimation(anim);
}
}
| 8,207 | 0.62398 | 0.618984 | 223 | 35.802692 | 27.045662 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632287 | false | false |
12
|
d1b44647adf2ef86e3352e9b01ce1f58f62e9459
| 5,772,436,113,120 |
92f5a97e55561a680a307d1845233967e3d7f370
|
/supensour-core/src/main/java/com/supensour/core/utils/ConverterUtils.java
|
1c6d6f1a14400cdda5634774ebf688f0ec57dd9d
|
[
"Apache-2.0"
] |
permissive
|
supensour/supensour
|
https://github.com/supensour/supensour
|
7b9e31340ae782557e9585b8ef06c3075bf5de6a
|
dc2d23750c1482ea7b3330bbd055abb38d60eab0
|
refs/heads/master
| 2023-05-08T08:51:27.034000 | 2021-05-10T07:39:45 | 2021-05-10T07:39:45 | 304,039,831 | 0 | 1 |
Apache-2.0
| false | 2021-05-10T12:22:32 | 2020-10-14T14:24:54 | 2021-05-10T07:39:54 | 2021-05-10T12:21:08 | 79 | 0 | 1 | 0 |
Java
| false | false |
package com.supensour.core.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* @author Suprayan Yapura
* @since 0.1.0
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ConverterUtils {
/**
* Copy properties from source to target.
* If either source/target object is null, the original target will be returned.
*
* @param source source object to be copied from
* @param target target object to be copied to
* @param ignoreProperties list of property names to be ignored
*
* @param <R> request
* @param <T> target
*
* @return the target
*/
public static <R, T> T copyProperties(R source, T target, String... ignoreProperties) {
Optional.ofNullable(source)
.filter(s -> Objects.nonNull(target))
.ifPresent(s -> BeanUtils.copyProperties(source, target, ignoreProperties));
return target;
}
/**
* Copy properties from source to the target object provided by targetSupplier.
* If either source/target object is null, the original target will be returned.
*
* @param source source object to be copied from
* @param targetSupplier target supplier to provide target object
* @param ignoreProperties list of property names to be ignored
*
* @param <R> request
* @param <T> target
*
* @throws NullPointerException if targetSupplier is null
* @return the target
*/
public static <R, T> T copyProperties(R source, Supplier<T> targetSupplier, String... ignoreProperties) {
Objects.requireNonNull(targetSupplier, "Target supplier must not be null");
return copyProperties(source, targetSupplier.get(), ignoreProperties);
}
/**
* Copy properties from a collection of sources to the target object provided by targetSupplier.
* For each source, if either the source/target object is null, the original target will be returned.
* In case of empty/null sources, empty List will be returned.
*
* @param sources a collection of source objects to be copied from
* @param targetSupplier target supplier to provide target object
* @param ignoreProperties list of property names to be ignored
*
* @param <R> request
* @param <T> target
*
* @throws NullPointerException if targetSupplier is null
* @return the target
*/
public static <R, T> List<T> copyProperties(Collection<R> sources, Supplier<T> targetSupplier, String... ignoreProperties) {
Objects.requireNonNull(targetSupplier, "Target supplier must not be null");
return Optional.ofNullable(sources)
.map(allSources -> allSources.stream()
.map(source -> copyProperties(source, targetSupplier, ignoreProperties))
.collect(Collectors.toList()))
.orElseGet(Collections::emptyList);
}
}
|
UTF-8
|
Java
| 3,161 |
java
|
ConverterUtils.java
|
Java
|
[
{
"context": "mport java.util.stream.Collectors;\n\n/**\n * @author Suprayan Yapura\n * @since 0.1.0\n */\n@NoArgsConstructor(access = A",
"end": 378,
"score": 0.9998831152915955,
"start": 363,
"tag": "NAME",
"value": "Suprayan Yapura"
}
] | null |
[] |
package com.supensour.core.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* @author <NAME>
* @since 0.1.0
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ConverterUtils {
/**
* Copy properties from source to target.
* If either source/target object is null, the original target will be returned.
*
* @param source source object to be copied from
* @param target target object to be copied to
* @param ignoreProperties list of property names to be ignored
*
* @param <R> request
* @param <T> target
*
* @return the target
*/
public static <R, T> T copyProperties(R source, T target, String... ignoreProperties) {
Optional.ofNullable(source)
.filter(s -> Objects.nonNull(target))
.ifPresent(s -> BeanUtils.copyProperties(source, target, ignoreProperties));
return target;
}
/**
* Copy properties from source to the target object provided by targetSupplier.
* If either source/target object is null, the original target will be returned.
*
* @param source source object to be copied from
* @param targetSupplier target supplier to provide target object
* @param ignoreProperties list of property names to be ignored
*
* @param <R> request
* @param <T> target
*
* @throws NullPointerException if targetSupplier is null
* @return the target
*/
public static <R, T> T copyProperties(R source, Supplier<T> targetSupplier, String... ignoreProperties) {
Objects.requireNonNull(targetSupplier, "Target supplier must not be null");
return copyProperties(source, targetSupplier.get(), ignoreProperties);
}
/**
* Copy properties from a collection of sources to the target object provided by targetSupplier.
* For each source, if either the source/target object is null, the original target will be returned.
* In case of empty/null sources, empty List will be returned.
*
* @param sources a collection of source objects to be copied from
* @param targetSupplier target supplier to provide target object
* @param ignoreProperties list of property names to be ignored
*
* @param <R> request
* @param <T> target
*
* @throws NullPointerException if targetSupplier is null
* @return the target
*/
public static <R, T> List<T> copyProperties(Collection<R> sources, Supplier<T> targetSupplier, String... ignoreProperties) {
Objects.requireNonNull(targetSupplier, "Target supplier must not be null");
return Optional.ofNullable(sources)
.map(allSources -> allSources.stream()
.map(source -> copyProperties(source, targetSupplier, ignoreProperties))
.collect(Collectors.toList()))
.orElseGet(Collections::emptyList);
}
}
| 3,152 | 0.685859 | 0.68491 | 85 | 36.188236 | 31.442007 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458824 | false | false |
12
|
c3cee723f47a145ff87cb456ca4f7135c4270302
| 24,472,723,711,809 |
545ad2e099f15b36da1d753ff5c8e5f87f169b4c
|
/redis-jedis-standAlone/src/main/java/com/learn/redis/jedis/HsetAndHget.java
|
366faa46f499bf0ee778f9a09e8e908130bc98f9
|
[] |
no_license
|
wangjwc/My-Redis-Master
|
https://github.com/wangjwc/My-Redis-Master
|
5d4b92410d57be29180ddf49e871cb68e483d495
|
8bac48322cff3ac2676a68fc83f2ab05efcc61bf
|
refs/heads/main
| 2023-04-03T02:20:01.372000 | 2021-03-30T09:02:47 | 2021-03-30T09:02:47 | 350,192,775 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.learn.redis.jedis;
import com.learn.redis.jedis.pool.RedisPool;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.Map;
import java.util.Set;
public class HsetAndHget {
public static void main(String[] args) throws InterruptedException {
Jedis jedis = RedisPool.getResource();
jedis.hset("User","user_01","{id:user_01,name:user_1}");
jedis.hset("User","user_02","{id:user_02,name:user_2}");
Map<String, String> map = jedis.hgetAll("User");
System.out.println(map.toString());
Set<String> keys = jedis.hkeys("User");
System.out.println(keys.toString());
jedis.expire("User", 2); // 过期时间只能设置给一级key
System.out.println(jedis.hkeys("User"));
}
}
|
UTF-8
|
Java
| 845 |
java
|
HsetAndHget.java
|
Java
|
[
{
"context": " jedis.hset(\"User\",\"user_01\",\"{id:user_01,name:user_1}\");\n jedis.hset(\"User\",\"user_02\",\"{id:use",
"end": 446,
"score": 0.8976532816886902,
"start": 441,
"tag": "USERNAME",
"value": "user_"
},
{
"context": " jedis.hset(\"User\",\"user_02\",\"{id:user_02,name:user_2}\");\n\n Map<String, String> map = jedis.hg",
"end": 511,
"score": 0.7578366994857788,
"start": 506,
"tag": "USERNAME",
"value": "user_"
}
] | null |
[] |
package com.learn.redis.jedis;
import com.learn.redis.jedis.pool.RedisPool;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.Map;
import java.util.Set;
public class HsetAndHget {
public static void main(String[] args) throws InterruptedException {
Jedis jedis = RedisPool.getResource();
jedis.hset("User","user_01","{id:user_01,name:user_1}");
jedis.hset("User","user_02","{id:user_02,name:user_2}");
Map<String, String> map = jedis.hgetAll("User");
System.out.println(map.toString());
Set<String> keys = jedis.hkeys("User");
System.out.println(keys.toString());
jedis.expire("User", 2); // 过期时间只能设置给一级key
System.out.println(jedis.hkeys("User"));
}
}
| 845 | 0.668287 | 0.654921 | 27 | 29.481482 | 23.411568 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.888889 | false | false |
12
|
e26906cbc943dfeb479c988d7bbb5278b03639ce
| 15,582,141,369,103 |
8b18143d99cf8b1930f12e0fb8fb15da77e5f735
|
/gs-test-junit4/src/test/java/com/avanza/gs/test/RunningPuAsRuleTest.java
|
601bdacfc8f0cbbef3b8d38c227194e9a096c7a7
|
[
"Apache-2.0"
] |
permissive
|
AvanzaBank/gs-test
|
https://github.com/AvanzaBank/gs-test
|
bf3fe9f67a5b6ad33444d04b18b0be2e86f1a054
|
db462c64c76956416a1d58a1a4b0f4113a400a67
|
refs/heads/main
| 2023-02-03T12:57:13.613000 | 2022-12-19T11:11:02 | 2022-12-19T11:11:02 | 50,594,304 | 0 | 4 | null | false | 2022-12-05T15:54:04 | 2016-01-28T15:56:39 | 2021-11-02T19:12:11 | 2022-12-05T15:54:03 | 265 | 0 | 4 | 0 |
Java
| false | false |
/*
* Copyright 2017 Avanza Bank AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.avanza.gs.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openspaces.core.GigaSpace;
import com.avanza.gs.test.helpers.FruitPojo;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class RunningPuAsRuleTest {
@Rule
public final RunningPu runningPu = PuConfigurers.partitionedPu("/fruit-pu.xml")
.numberOfPrimaries(1)
.numberOfBackups(0)
.configure();
@Test
public void test_1_saveAndRead() {
GigaSpace gigaSpace = runningPu.getClusteredGigaSpace();
gigaSpace.write(new FruitPojo("apple"));
FruitPojo fruit = gigaSpace.readById(FruitPojo.class, "apple");
assertNotNull(fruit);
}
@Test
public void test_2_shouldBeResetBetweenTests() {
GigaSpace gigaSpace = runningPu.getClusteredGigaSpace();
FruitPojo fruit = gigaSpace.readById(FruitPojo.class, "apple");
assertNull(fruit);
}
}
|
UTF-8
|
Java
| 1,606 |
java
|
RunningPuAsRuleTest.java
|
Java
|
[] | null |
[] |
/*
* Copyright 2017 Avanza Bank AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.avanza.gs.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openspaces.core.GigaSpace;
import com.avanza.gs.test.helpers.FruitPojo;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class RunningPuAsRuleTest {
@Rule
public final RunningPu runningPu = PuConfigurers.partitionedPu("/fruit-pu.xml")
.numberOfPrimaries(1)
.numberOfBackups(0)
.configure();
@Test
public void test_1_saveAndRead() {
GigaSpace gigaSpace = runningPu.getClusteredGigaSpace();
gigaSpace.write(new FruitPojo("apple"));
FruitPojo fruit = gigaSpace.readById(FruitPojo.class, "apple");
assertNotNull(fruit);
}
@Test
public void test_2_shouldBeResetBetweenTests() {
GigaSpace gigaSpace = runningPu.getClusteredGigaSpace();
FruitPojo fruit = gigaSpace.readById(FruitPojo.class, "apple");
assertNull(fruit);
}
}
| 1,606 | 0.760274 | 0.752802 | 53 | 29.301888 | 25.19253 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.037736 | false | false |
12
|
e6b7e89c315ef84cd19e1c483bdad3c7115e80e6
| 2,723,009,311,231 |
d8fbe902a5674073c3a5a14803f39874bf4a17bd
|
/netsharp-weixin/src/main/java/org/netsharp/wx/ea/entity/WxeaMessageReciver.java
|
c1569ba959cf5c33672c9bc50e338ad04eed3211
|
[] |
no_license
|
xufangbo/netsharp
|
https://github.com/xufangbo/netsharp
|
90d5b3b49832a598ea1b56e987705b9b5f2dfdf0
|
09a0c45d0327974b1256a6c79ba923de4e3c09c5
|
refs/heads/master
| 2020-04-09T04:03:28.929000 | 2020-01-02T13:17:06 | 2020-01-02T13:17:06 | 160,008,609 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.netsharp.wx.ea.entity;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.netsharp.core.annotations.Column;
import org.netsharp.core.annotations.Reference;
import org.netsharp.core.annotations.Table;
import org.netsharp.entity.Entity;
import org.netsharp.organization.entity.Employee;
@Table(name = "wx_ea_message_receiver", header = "企业号消息接收人")
public class WxeaMessageReciver extends Entity {
/**
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
*/
private static final long serialVersionUID = -1774687311711457661L;
@Column(name = "pmconfig_id",header="平台消息id")
private Integer pmConfigId;
@Reference(foreignKey="pmConfigId")
@JsonIgnore
private WxeaMessage pmConfig;
@Column(name = "receiver_id",header="接收人id")
private Integer receiverId;
@Reference(foreignKey="receiverId")
private Employee receiver;
public Integer getPmConfigId() {
return pmConfigId;
}
public void setPmConfigId(Integer pmConfigId) {
this.pmConfigId = pmConfigId;
}
public WxeaMessage getPmConfig() {
return pmConfig;
}
public void setPmConfig(WxeaMessage pmConfig) {
this.pmConfig = pmConfig;
}
public Integer getReceiverId() {
return receiverId;
}
public void setReceiverId(Integer receiverId) {
this.receiverId = receiverId;
}
public Employee getReceiver() {
return receiver;
}
public void setReceiver(Employee receiver) {
this.receiver = receiver;
}
}
|
UTF-8
|
Java
| 1,489 |
java
|
WxeaMessageReciver.java
|
Java
|
[] | null |
[] |
package org.netsharp.wx.ea.entity;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.netsharp.core.annotations.Column;
import org.netsharp.core.annotations.Reference;
import org.netsharp.core.annotations.Table;
import org.netsharp.entity.Entity;
import org.netsharp.organization.entity.Employee;
@Table(name = "wx_ea_message_receiver", header = "企业号消息接收人")
public class WxeaMessageReciver extends Entity {
/**
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
*/
private static final long serialVersionUID = -1774687311711457661L;
@Column(name = "pmconfig_id",header="平台消息id")
private Integer pmConfigId;
@Reference(foreignKey="pmConfigId")
@JsonIgnore
private WxeaMessage pmConfig;
@Column(name = "receiver_id",header="接收人id")
private Integer receiverId;
@Reference(foreignKey="receiverId")
private Employee receiver;
public Integer getPmConfigId() {
return pmConfigId;
}
public void setPmConfigId(Integer pmConfigId) {
this.pmConfigId = pmConfigId;
}
public WxeaMessage getPmConfig() {
return pmConfig;
}
public void setPmConfig(WxeaMessage pmConfig) {
this.pmConfig = pmConfig;
}
public Integer getReceiverId() {
return receiverId;
}
public void setReceiverId(Integer receiverId) {
this.receiverId = receiverId;
}
public Employee getReceiver() {
return receiver;
}
public void setReceiver(Employee receiver) {
this.receiver = receiver;
}
}
| 1,489 | 0.753319 | 0.740042 | 62 | 22.080645 | 19.96311 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.145161 | false | false |
12
|
ab448a68141ce6ff77312c4fddedfb023d8a9d15
| 5,841,155,588,790 |
d63f1fc20659ddef45666bcf8594eaebe4ae2ca6
|
/src/main/java/com/example/jsfdemo/domain/Person.java
|
a48a15a655d9be35e6779454ed279e04a352cc82
|
[] |
no_license
|
lkwidzinski/jsfdemo
|
https://github.com/lkwidzinski/jsfdemo
|
eca4a317c9da50327ec99185e76d83660f819c74
|
d6788007a0e44d525098ad86e4d6f7cb79126c87
|
refs/heads/master
| 2020-12-24T21:44:35.335000 | 2013-01-21T15:02:26 | 2013-01-21T15:02:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.jsfdemo.domain;
import javax.validation.constraints.Size;
public class Person {
String firstName="";
String lastName="";
int pesel=0;
String additionalInfo="";
public Person(String firstName,String lastName, int pesel, String additionalInfo){
this.firstName=firstName;
this.lastName=lastName;
this.pesel=pesel;
this.additionalInfo=additionalInfo;
}
public Person() {}
@Size(min=3,max=20)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Size(min=3,max=20)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getPesel() {
return pesel;
}
public void setPesel(int pesel) {
this.pesel = pesel;
}
@Size(max=40)
public String getAdditionalInfo() {
return additionalInfo;
}
public void setAdditionalInfo(String additionalInfo) {
this.additionalInfo = additionalInfo;
}
public String toString(){
String s=String.format("%20s||%20s||%20s||%40s\n",firstName,lastName,pesel,additionalInfo);
return s;
}
}
|
UTF-8
|
Java
| 1,153 |
java
|
Person.java
|
Java
|
[
{
"context": "esel, String additionalInfo){\n\t\t\n\t\tthis.firstName=firstName;\n\t\tthis.lastName=lastName;\n\t\tthis.pesel=pesel;\n\t\t",
"end": 303,
"score": 0.8610080480575562,
"start": 294,
"tag": "NAME",
"value": "firstName"
}
] | null |
[] |
package com.example.jsfdemo.domain;
import javax.validation.constraints.Size;
public class Person {
String firstName="";
String lastName="";
int pesel=0;
String additionalInfo="";
public Person(String firstName,String lastName, int pesel, String additionalInfo){
this.firstName=firstName;
this.lastName=lastName;
this.pesel=pesel;
this.additionalInfo=additionalInfo;
}
public Person() {}
@Size(min=3,max=20)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Size(min=3,max=20)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getPesel() {
return pesel;
}
public void setPesel(int pesel) {
this.pesel = pesel;
}
@Size(max=40)
public String getAdditionalInfo() {
return additionalInfo;
}
public void setAdditionalInfo(String additionalInfo) {
this.additionalInfo = additionalInfo;
}
public String toString(){
String s=String.format("%20s||%20s||%20s||%40s\n",firstName,lastName,pesel,additionalInfo);
return s;
}
}
| 1,153 | 0.716392 | 0.701648 | 60 | 18.216667 | 19.478271 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.7 | false | false |
12
|
1d34324ab57c79d555dcc26ec2f987dd3f0f1506
| 8,461,085,644,208 |
beb2c9ebe5fc845148804bba44c9ddf1a8d776e3
|
/Defrac/src/java/com/adjazent/defrac/system/terminal/ICommand.java
|
7cf88db06f56b32fc179939b7c02849c95019488
|
[] |
no_license
|
alanross/defrac
|
https://github.com/alanross/defrac
|
9b0fbdc1f8e9cead15f601e57312f11041db8b07
|
9f29d3e51fa57d6f89d5e0640a501d719cf1bb97
|
refs/heads/master
| 2021-10-10T15:18:47.169000 | 2019-01-12T20:12:04 | 2019-01-12T20:12:04 | 16,837,457 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.adjazent.defrac.system.terminal;
/**
* @author Alan Ross
* @version 0.1
*/
public interface ICommand
{
/**
*
*/
String commandExecute( String[] args );
/**
*
*/
String getCommandName();
/**
*
*/
String getCommandInfo();
/**
*
*/
String getCommandUsage();
/**
*
*/
int getCommandMinParams();
/**
*
*/
int getCommandMaxParams();
}
|
UTF-8
|
Java
| 387 |
java
|
ICommand.java
|
Java
|
[
{
"context": "m.adjazent.defrac.system.terminal;\n\n/**\n * @author Alan Ross\n * @version 0.1\n */\npublic interface ICommand\n{\n\t",
"end": 70,
"score": 0.999785840511322,
"start": 61,
"tag": "NAME",
"value": "Alan Ross"
}
] | null |
[] |
package com.adjazent.defrac.system.terminal;
/**
* @author <NAME>
* @version 0.1
*/
public interface ICommand
{
/**
*
*/
String commandExecute( String[] args );
/**
*
*/
String getCommandName();
/**
*
*/
String getCommandInfo();
/**
*
*/
String getCommandUsage();
/**
*
*/
int getCommandMinParams();
/**
*
*/
int getCommandMaxParams();
}
| 384 | 0.565891 | 0.560724 | 38 | 9.157895 | 11.752998 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.815789 | false | false |
12
|
770b464efcc5091eae20b617a6a2fc35cc2b7033
| 8,890,582,339,040 |
fc47bbb09a983c27c52325c534b18ad0a7ea86ce
|
/src/com/filter/PathFilter.java
|
b5f902c0c8cc7b4ee16e2c854eb89d48e31e7cc0
|
[] |
no_license
|
munich04/GBC004
|
https://github.com/munich04/GBC004
|
9fbc8cc886f0e2218dd387e4a8327e885b154714
|
2c0a789e3bb5d8c3356ac5942644aaf60c00226f
|
refs/heads/master
| 2021-09-01T18:50:21.413000 | 2017-12-28T09:24:58 | 2017-12-28T09:24:58 | 115,604,478 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
*
* 打印;
* 传输;
*
* @author bayer
*
*/
public class PathFilter implements Filter{
//注意赋值以减少判断
private static String path = "";
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//synchronized
synchronized (PathFilter.class) {
if("".equals(this.path)){
this.path = ((HttpServletRequest)request).getContextPath();
}
}
//不要遗漏
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
//synchronized static
public synchronized static String getPath() {
return path;
}
}
|
GB18030
|
Java
| 1,034 |
java
|
PathFilter.java
|
Java
|
[
{
"context": "vletRequest;\n\n/**\n * \n * 打印;\n * 传输;\n * \n * @author bayer\n *\n */\npublic class PathFilter implements Filter{",
"end": 351,
"score": 0.9993903636932373,
"start": 346,
"tag": "USERNAME",
"value": "bayer"
}
] | null |
[] |
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
*
* 打印;
* 传输;
*
* @author bayer
*
*/
public class PathFilter implements Filter{
//注意赋值以减少判断
private static String path = "";
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//synchronized
synchronized (PathFilter.class) {
if("".equals(this.path)){
this.path = ((HttpServletRequest)request).getContextPath();
}
}
//不要遗漏
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
//synchronized static
public synchronized static String getPath() {
return path;
}
}
| 1,034 | 0.73494 | 0.73494 | 52 | 18.153847 | 20.117332 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.192308 | false | false |
12
|
a70f97de600b7d2dde91aad6c40cc0871ce02fe9
| 2,259,152,840,707 |
9cde82a76e93bfd6770e2b6afd98897f21bda594
|
/board/src/main/java/org/atree/domain/LikeVO.java
|
c2b238fe6a67cf3c341cca8e2a959cffccb94592
|
[] |
no_license
|
atree1/springProject
|
https://github.com/atree1/springProject
|
7ef990d3090ed61a9de25a743ae2bf592b1a755f
|
b04a212f5b1f9adef5159ead6b1021666de8e69f
|
refs/heads/master
| 2020-04-03T15:28:08.052000 | 2018-12-21T03:30:47 | 2018-12-21T03:30:47 | 155,363,476 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.atree.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class LikeVO {
private int bno;
private String userid;
}
|
UTF-8
|
Java
| 187 |
java
|
LikeVO.java
|
Java
|
[] | null |
[] |
package org.atree.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class LikeVO {
private int bno;
private String userid;
}
| 187 | 0.737968 | 0.737968 | 12 | 13.583333 | 11.206087 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false |
12
|
48b4a7103103a4441271a640b5a760000dca028c
| 15,977,278,341,914 |
da272a633fb1ebbb1304a1f5e941dc4b96426832
|
/chapter05/src/main/java/com/zgy/study/chapter05/subject03/demo05/App.java
|
b20e59149f72923a393c335c2ac258c55663e9b9
|
[] |
no_license
|
ZGYSYY/study-sprling5
|
https://github.com/ZGYSYY/study-sprling5
|
811f4d0fb56e79a16c80ca3d87158986851991e3
|
edefeea8e97ef0c369443c3f04035b72cd90363e
|
refs/heads/master
| 2022-12-20T00:56:09.192000 | 2019-12-11T10:06:39 | 2019-12-11T10:06:39 | 222,707,163 | 2 | 0 | null | false | 2022-12-15T23:25:16 | 2019-11-19T13:50:38 | 2022-03-07T06:02:26 | 2022-12-15T23:25:16 | 309 | 1 | 0 | 13 |
Java
| false | false |
package com.zgy.study.chapter05.subject03.demo05;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
/**
* @author ZGY <br>
* @date 2019/11/27 10:17 <br>
* @description App <br>
*/
public class App {
public static void main(String[] args) {
Guitarist guitarist = new Guitarist();
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("execution(* sing*(..))");
Advisor advisor = new DefaultPointcutAdvisor(pointcut, new SimpleAdvice());
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(guitarist);
proxyFactory.addAdvisor(advisor);
Guitarist proxy = (Guitarist) proxyFactory.getProxy();
proxy.sing();
proxy.sing2();
proxy.rest();
}
}
|
UTF-8
|
Java
| 972 |
java
|
App.java
|
Java
|
[
{
"context": "op.support.DefaultPointcutAdvisor;\n\n/**\n * @author ZGY <br>\n * @date 2019/11/27 10:17 <br>\n * @descripti",
"end": 294,
"score": 0.9996688961982727,
"start": 291,
"tag": "USERNAME",
"value": "ZGY"
}
] | null |
[] |
package com.zgy.study.chapter05.subject03.demo05;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
/**
* @author ZGY <br>
* @date 2019/11/27 10:17 <br>
* @description App <br>
*/
public class App {
public static void main(String[] args) {
Guitarist guitarist = new Guitarist();
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("execution(* sing*(..))");
Advisor advisor = new DefaultPointcutAdvisor(pointcut, new SimpleAdvice());
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(guitarist);
proxyFactory.addAdvisor(advisor);
Guitarist proxy = (Guitarist) proxyFactory.getProxy();
proxy.sing();
proxy.sing2();
proxy.rest();
}
}
| 972 | 0.703704 | 0.684156 | 29 | 32.517242 | 25.084164 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586207 | false | false |
12
|
410a06d73b645fe774a9a681ca38eff581a5e1b0
| 23,484,881,179,712 |
31003c198586cd07d313bba268f15e2c5fe1c652
|
/wow-excel-poi/src/main/java/com/github/nekolr/write/merge/LastCell.java
|
33f41ca3bc216c9309319dc95df1de56be7171ec
|
[
"MIT"
] |
permissive
|
nekolr/wow-excel
|
https://github.com/nekolr/wow-excel
|
44525b419ed1162b3dac8c6ae08ec8dbf75ae78c
|
65c0235a256630c6cb70849f4f88384a23573597
|
refs/heads/master
| 2023-07-26T18:05:01.432000 | 2021-09-11T02:14:38 | 2021-09-11T02:14:38 | 260,608,411 | 3 | 0 |
MIT
| false | 2021-05-30T01:30:18 | 2020-05-02T03:46:09 | 2021-05-29T15:37:46 | 2021-05-30T01:30:18 | 277 | 3 | 0 | 0 |
Java
| false | false |
package com.github.nekolr.write.merge;
import lombok.Data;
/**
* 上一个单元格的信息
*/
@Data
public class LastCell {
/**
* 上一个单元格的值
*/
private Object value;
/**
* 上一个单元格的列号
*/
private int colNum;
}
|
UTF-8
|
Java
| 283 |
java
|
LastCell.java
|
Java
|
[] | null |
[] |
package com.github.nekolr.write.merge;
import lombok.Data;
/**
* 上一个单元格的信息
*/
@Data
public class LastCell {
/**
* 上一个单元格的值
*/
private Object value;
/**
* 上一个单元格的列号
*/
private int colNum;
}
| 283 | 0.5671 | 0.5671 | 20 | 10.55 | 10.312492 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
12
|
650118090a4f4d7e16f7087d29e19db4dce150e8
| 2,319,282,370,888 |
cd264ee49fa9b3006ff8fec5169b5d02b5c36814
|
/src/main/java/com/f/validation/UpdateGroup.java
|
0c50b002ea141c8c98eca320a7c8635b05937989
|
[] |
no_license
|
wfm0105/payment
|
https://github.com/wfm0105/payment
|
ba481308f4fc2b544f471ef2389e48ce443c7aa0
|
6f95ea7182128894f999ab50d3fa54d31fb07dba
|
refs/heads/master
| 2021-10-12T00:58:01.977000 | 2019-01-31T09:55:17 | 2019-01-31T09:55:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.f.validation;
/**
* @author rebysfu@gmail.com
* @description:使用此group,只在修改的时候才进行验证
* @create 2019-01-04 上午11:20
**/
public interface UpdateGroup {
}
|
UTF-8
|
Java
| 202 |
java
|
UpdateGroup.java
|
Java
|
[
{
"context": "package com.f.validation;\n\n/**\n * @author rebysfu@gmail.com\n * @description:使用此group,只在修改的时候才进行验证\n * @create ",
"end": 59,
"score": 0.9999212026596069,
"start": 42,
"tag": "EMAIL",
"value": "rebysfu@gmail.com"
}
] | null |
[] |
package com.f.validation;
/**
* @author <EMAIL>
* @description:使用此group,只在修改的时候才进行验证
* @create 2019-01-04 上午11:20
**/
public interface UpdateGroup {
}
| 192 | 0.716867 | 0.644578 | 9 | 17.444445 | 14.166557 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false |
12
|
fbffe0dab488ed69a6e69b76018585a73fbe6cdb
| 22,084,721,850,366 |
cca87c4ade972a682c9bf0663ffdf21232c9b857
|
/com/google/android/gms/c/az.java
|
a7642de8bd0dacd56aac9177bd8ea8010d60d3ff
|
[] |
no_license
|
ZoranLi/wechat_reversing
|
https://github.com/ZoranLi/wechat_reversing
|
b246d43f7c2d7beb00a339e2f825fcb127e0d1a1
|
36b10ef49d2c75d69e3c8fdd5b1ea3baa2bba49a
|
refs/heads/master
| 2021-07-05T01:17:20.533000 | 2017-09-25T09:07:33 | 2017-09-25T09:07:33 | 104,726,592 | 12 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.google.android.gms.c;
import java.lang.reflect.Array;
public final class az<M extends ay<M>, T> {
protected final boolean aCA;
protected final Class<T> aCz;
public final int tag;
protected final int type;
private int ae(Object obj) {
int cu = bh.cu(this.tag);
switch (this.type) {
case 10:
return (ax.cn(cu) * 2) + ((be) obj).lH();
case 11:
return ax.b(cu, (be) obj);
default:
throw new IllegalArgumentException("Unknown type " + this.type);
}
}
private void b(Object obj, ax axVar) {
try {
axVar.co(this.tag);
switch (this.type) {
case 10:
be beVar = (be) obj;
int cu = bh.cu(this.tag);
beVar.a(axVar);
axVar.am(cu, 4);
return;
case 11:
axVar.b((be) obj);
return;
default:
throw new IllegalArgumentException("Unknown type " + this.type);
}
} catch (Throwable e) {
throw new IllegalStateException(e);
}
throw new IllegalStateException(e);
}
final void a(Object obj, ax axVar) {
if (this.aCA) {
int length = Array.getLength(obj);
for (int i = 0; i < length; i++) {
Object obj2 = Array.get(obj, i);
if (obj2 != null) {
b(obj2, axVar);
}
}
return;
}
b(obj, axVar);
}
final int ad(Object obj) {
int i = 0;
if (!this.aCA) {
return ae(obj);
}
int length = Array.getLength(obj);
for (int i2 = 0; i2 < length; i2++) {
if (Array.get(obj, i2) != null) {
i += ae(Array.get(obj, i2));
}
}
return i;
}
}
|
UTF-8
|
Java
| 2,001 |
java
|
az.java
|
Java
|
[] | null |
[] |
package com.google.android.gms.c;
import java.lang.reflect.Array;
public final class az<M extends ay<M>, T> {
protected final boolean aCA;
protected final Class<T> aCz;
public final int tag;
protected final int type;
private int ae(Object obj) {
int cu = bh.cu(this.tag);
switch (this.type) {
case 10:
return (ax.cn(cu) * 2) + ((be) obj).lH();
case 11:
return ax.b(cu, (be) obj);
default:
throw new IllegalArgumentException("Unknown type " + this.type);
}
}
private void b(Object obj, ax axVar) {
try {
axVar.co(this.tag);
switch (this.type) {
case 10:
be beVar = (be) obj;
int cu = bh.cu(this.tag);
beVar.a(axVar);
axVar.am(cu, 4);
return;
case 11:
axVar.b((be) obj);
return;
default:
throw new IllegalArgumentException("Unknown type " + this.type);
}
} catch (Throwable e) {
throw new IllegalStateException(e);
}
throw new IllegalStateException(e);
}
final void a(Object obj, ax axVar) {
if (this.aCA) {
int length = Array.getLength(obj);
for (int i = 0; i < length; i++) {
Object obj2 = Array.get(obj, i);
if (obj2 != null) {
b(obj2, axVar);
}
}
return;
}
b(obj, axVar);
}
final int ad(Object obj) {
int i = 0;
if (!this.aCA) {
return ae(obj);
}
int length = Array.getLength(obj);
for (int i2 = 0; i2 < length; i2++) {
if (Array.get(obj, i2) != null) {
i += ae(Array.get(obj, i2));
}
}
return i;
}
}
| 2,001 | 0.432784 | 0.422289 | 72 | 26.791666 | 17.442715 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false |
12
|
bcab8d5e0cbc68c5705df1325bc58ea1cc3888b9
| 17,729,625,010,591 |
5f007cdad14e89f7398f93bb44787a09b5660989
|
/Código Fonte/CriptoFX/src/main/java/br/edu/utfpr/auditoria/cripto/View/MainController.java
|
ad993e552f463460b6eb89e8878437f7cdbc0780
|
[] |
no_license
|
ricardoalvim-edu/criptojava
|
https://github.com/ricardoalvim-edu/criptojava
|
d8c3ff6023e6e052d1e871192388d6584746cf08
|
71806fcdedfeb923e937c9bf55a40ef794bfc24f
|
refs/heads/master
| 2020-07-15T09:48:11.923000 | 2016-11-20T01:36:43 | 2016-11-20T01:36:43 | 73,965,906 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.edu.utfpr.auditoria.cripto.View;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ResourceBundle;
import br.edu.utfpr.auditoria.cripto.AES;
import br.edu.utfpr.auditoria.cripto.RSA;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.text.Text;
public class MainController implements Initializable{
@FXML
private ComboBox<Text> cbTipo;
@FXML
private ComboBox<Text> cbTamanhoMsg;
@FXML
private ComboBox<Text> cbComprimentoChave;
@FXML
private Label tcripto;
@FXML
private Label tdecripto;
@FXML
private Label lbUncript;
@FXML
private Button btStart;
private Collection<Text> tipos = new ArrayList<>();
private Collection<Text> tamanhos = new ArrayList<>();
private Collection<Text> comprimentoAES = new ArrayList<>();
private Collection<Text> comprimentoRSA = new ArrayList<>();
public String texto = "teste-";
public String texto2M = "teste-teste-";
public String texto4M = "teste-teste-teste-teste-";
public String texto8M = "teste-teste-teste-teste-teste-teste-teste-teste-";
@Override
public void initialize(URL location, ResourceBundle resources) {
tipos.add(new Text("RSA"));
tipos.add(new Text("AES"));
tamanhos.add(new Text("M"));
tamanhos.add(new Text("2M"));
tamanhos.add(new Text("4M"));
tamanhos.add(new Text("8M"));
comprimentoAES.add(new Text("128 bits"));
comprimentoAES.add(new Text("256 bits"));
comprimentoRSA.add(new Text("512"));
comprimentoRSA.add(new Text("1024"));
// TODO Auto-generated method stub
cbTipo.getItems().removeAll(cbTipo.getItems());
cbTipo.getItems().addAll(tipos);
cbTipo.setOnAction(onTipo);
btStart.setOnAction(onStart);
cbTamanhoMsg.getItems().addAll(tamanhos);
}
EventHandler<ActionEvent> onTipo = new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
if (cbTipo.getValue().getText().equals("RSA")){
cbComprimentoChave.setDisable(false);
cbComprimentoChave.getItems().removeAll(cbComprimentoChave.getItems());
cbComprimentoChave.getItems().addAll(comprimentoRSA);
}
else if (cbTipo.getValue().getText().equals("AES")){
cbComprimentoChave.setDisable(true);
//cbComprimentoChave.getItems().removeAll(cbComprimentoChave.getItems());
//cbComprimentoChave.getItems().addAll(comprimentoAES);
}
}
};
EventHandler<ActionEvent> onStart = new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
long start = 0;
long elapsed = 0;
long total = 0;
// TODO Auto-generated method stub
if (cbTipo.getValue().getText().equals("AES")){
try {
String choiced = textSizeChoiced(cbTamanhoMsg.getValue().getText().toString());
start = System.currentTimeMillis();
byte[] textoencriptado = AES.encriptar(choiced, AES.chaveencriptacao);
elapsed = System.currentTimeMillis();
total = elapsed - start;
tcripto.setText(total + " ms");
total = 0;
start = System.currentTimeMillis();
String textodecriptado = AES.decriptar(textoencriptado, AES.chaveencriptacao);
elapsed = System.currentTimeMillis();
total = elapsed - start;
tdecripto.setText(total + " ms");
lbUncript.setText(textodecriptado);
total = 0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
if (cbTipo.getValue().getText().equals("RSA")){
try {
RSA rsa = new RSA(Integer.parseInt(cbComprimentoChave.getValue().getText()));
String choiced = textSizeChoiced(cbTamanhoMsg.getValue().getText().toString());
start = System.currentTimeMillis();
byte[] textoencriptado = rsa.encriptPublic(choiced);
elapsed = System.currentTimeMillis();
total = elapsed - start;
tcripto.setText(total + " ms");
total = 0;
start = System.currentTimeMillis();
String textodecriptado = rsa.descriptPrivate(textoencriptado);
elapsed = System.currentTimeMillis();
total = elapsed - start;
tdecripto.setText(total + " ms");
lbUncript.setText(textodecriptado);
total = 0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
};
public String textSizeChoiced(String choiced){
if (choiced.equals("M")){
return this.texto;
}
else if (choiced.equals("2M")){
return this.texto2M;
}
else if (choiced.equals("4M")){
return this.texto4M;
}
else if (choiced.equals("8M")){
return this.texto8M;
}
return null;
}
}
|
UTF-8
|
Java
| 4,824 |
java
|
MainController.java
|
Java
|
[] | null |
[] |
package br.edu.utfpr.auditoria.cripto.View;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ResourceBundle;
import br.edu.utfpr.auditoria.cripto.AES;
import br.edu.utfpr.auditoria.cripto.RSA;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.text.Text;
public class MainController implements Initializable{
@FXML
private ComboBox<Text> cbTipo;
@FXML
private ComboBox<Text> cbTamanhoMsg;
@FXML
private ComboBox<Text> cbComprimentoChave;
@FXML
private Label tcripto;
@FXML
private Label tdecripto;
@FXML
private Label lbUncript;
@FXML
private Button btStart;
private Collection<Text> tipos = new ArrayList<>();
private Collection<Text> tamanhos = new ArrayList<>();
private Collection<Text> comprimentoAES = new ArrayList<>();
private Collection<Text> comprimentoRSA = new ArrayList<>();
public String texto = "teste-";
public String texto2M = "teste-teste-";
public String texto4M = "teste-teste-teste-teste-";
public String texto8M = "teste-teste-teste-teste-teste-teste-teste-teste-";
@Override
public void initialize(URL location, ResourceBundle resources) {
tipos.add(new Text("RSA"));
tipos.add(new Text("AES"));
tamanhos.add(new Text("M"));
tamanhos.add(new Text("2M"));
tamanhos.add(new Text("4M"));
tamanhos.add(new Text("8M"));
comprimentoAES.add(new Text("128 bits"));
comprimentoAES.add(new Text("256 bits"));
comprimentoRSA.add(new Text("512"));
comprimentoRSA.add(new Text("1024"));
// TODO Auto-generated method stub
cbTipo.getItems().removeAll(cbTipo.getItems());
cbTipo.getItems().addAll(tipos);
cbTipo.setOnAction(onTipo);
btStart.setOnAction(onStart);
cbTamanhoMsg.getItems().addAll(tamanhos);
}
EventHandler<ActionEvent> onTipo = new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
if (cbTipo.getValue().getText().equals("RSA")){
cbComprimentoChave.setDisable(false);
cbComprimentoChave.getItems().removeAll(cbComprimentoChave.getItems());
cbComprimentoChave.getItems().addAll(comprimentoRSA);
}
else if (cbTipo.getValue().getText().equals("AES")){
cbComprimentoChave.setDisable(true);
//cbComprimentoChave.getItems().removeAll(cbComprimentoChave.getItems());
//cbComprimentoChave.getItems().addAll(comprimentoAES);
}
}
};
EventHandler<ActionEvent> onStart = new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event) {
long start = 0;
long elapsed = 0;
long total = 0;
// TODO Auto-generated method stub
if (cbTipo.getValue().getText().equals("AES")){
try {
String choiced = textSizeChoiced(cbTamanhoMsg.getValue().getText().toString());
start = System.currentTimeMillis();
byte[] textoencriptado = AES.encriptar(choiced, AES.chaveencriptacao);
elapsed = System.currentTimeMillis();
total = elapsed - start;
tcripto.setText(total + " ms");
total = 0;
start = System.currentTimeMillis();
String textodecriptado = AES.decriptar(textoencriptado, AES.chaveencriptacao);
elapsed = System.currentTimeMillis();
total = elapsed - start;
tdecripto.setText(total + " ms");
lbUncript.setText(textodecriptado);
total = 0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
if (cbTipo.getValue().getText().equals("RSA")){
try {
RSA rsa = new RSA(Integer.parseInt(cbComprimentoChave.getValue().getText()));
String choiced = textSizeChoiced(cbTamanhoMsg.getValue().getText().toString());
start = System.currentTimeMillis();
byte[] textoencriptado = rsa.encriptPublic(choiced);
elapsed = System.currentTimeMillis();
total = elapsed - start;
tcripto.setText(total + " ms");
total = 0;
start = System.currentTimeMillis();
String textodecriptado = rsa.descriptPrivate(textoencriptado);
elapsed = System.currentTimeMillis();
total = elapsed - start;
tdecripto.setText(total + " ms");
lbUncript.setText(textodecriptado);
total = 0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
};
public String textSizeChoiced(String choiced){
if (choiced.equals("M")){
return this.texto;
}
else if (choiced.equals("2M")){
return this.texto2M;
}
else if (choiced.equals("4M")){
return this.texto4M;
}
else if (choiced.equals("8M")){
return this.texto8M;
}
return null;
}
}
| 4,824 | 0.692164 | 0.685531 | 165 | 28.236364 | 21.617022 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.121212 | false | false |
12
|
4b00e5ce9694bd08f1b53345f18b9809790c518e
| 27,084,063,807,991 |
c4be1752abdb2ff1e4b99dd86463bd9e62e2af98
|
/core/src/com/mygdx/akurun/overlays/FinishMenu.java
|
0531e6985a5da0c348e814f4c1c383306346b165
|
[] |
no_license
|
Miguelchorat/AkuRun
|
https://github.com/Miguelchorat/AkuRun
|
7fa0b01ef1a3aa77a3c20e1c7e84056e5ba1a47d
|
799d84d9693d7341f85fd9c8aecdc1594585fb55
|
refs/heads/master
| 2021-01-05T07:42:08.136000 | 2020-03-10T13:15:06 | 2020-03-10T13:15:06 | 240,935,299 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mygdx.akurun.overlays;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.mygdx.akurun.GameplayScreen;
import com.mygdx.akurun.util.Constants;
public class FinishMenu {
public final Viewport viewport;
private Texture window;
private Texture restartIcon;
private Texture exitIcon;
private Texture header;
private Texture table;
GameplayScreen gameplayScreen;
BitmapFont font;
private FreeTypeFontGenerator generator;
private FreeTypeFontGenerator.FreeTypeFontParameter parameter;
public FinishMenu(GameplayScreen gameplayScreen) {
this.gameplayScreen = gameplayScreen;
this.viewport = new ExtendViewport(Constants.HUD_VIEWPORT_SIZE, Constants.HUD_VIEWPORT_SIZE);
window = new Texture(Constants.WINDOW_HUD);
restartIcon = new Texture(Constants.RESTART_HUD);
exitIcon = new Texture(Constants.EXIT_HUD);
header = new Texture(Constants.HEADER_LOSE_HUD);
table = new Texture(Constants.TABLE_HUD);
generator = new FreeTypeFontGenerator(Gdx.files.internal(Constants.FONT_HUD));
parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 30;
parameter.borderWidth = 2f;
parameter.borderColor= Color.BLACK;
font = generator.generateFont(parameter);
generator.dispose();
}
public void render(SpriteBatch batch,int score) {
viewport.apply();
batch.setProjectionMatrix(viewport.getCamera().combined);
batch.begin();
batch.draw(window,viewport.getWorldWidth()/3f,viewport.getWorldHeight()/6,window.getWidth()/3f,window.getHeight()/3f);
batch.draw(table,viewport.getWorldWidth()/2.8f,viewport.getWorldHeight()/2.8f,window.getWidth()/3.5f,window.getHeight()/4.5f);
font.draw(batch,"Score : "+score,viewport.getWorldWidth()/2.3f,viewport.getWorldHeight()/1.7f);
batch.draw(header,viewport.getWorldWidth()/3.5f,viewport.getWorldHeight()/1.5f,header.getWidth()/2.5f,header.getHeight()/3.5f);
batch.draw(restartIcon,viewport.getWorldWidth()/1.8f,viewport.getWorldHeight()/4.5f,Constants.HUD_MARGIN*1.4f,Constants.HUD_MARGIN*1.4f);
batch.draw(exitIcon,viewport.getWorldWidth()/2.5f,viewport.getWorldHeight()/4.5f,Constants.HUD_MARGIN*1.4f,Constants.HUD_MARGIN*1.4f);
if(Gdx.input.justTouched()){
Vector3 tmp = new Vector3(Gdx.input.getX(),Gdx.input.getY(),0);
viewport.getCamera().unproject(tmp);
Rectangle restartBounds = new Rectangle(viewport.getWorldWidth()/1.8f,viewport.getWorldHeight()/4.5f,Constants.HUD_MARGIN*1.4f,Constants.HUD_MARGIN*1.4f);
Rectangle exitBounds = new Rectangle(viewport.getWorldWidth()/2.5f,viewport.getWorldHeight()/4.5f,Constants.HUD_MARGIN*1.4f,Constants.HUD_MARGIN*1.4f);
if(restartBounds.contains(tmp.x,tmp.y)){
gameplayScreen.getTheme().dispose();
gameplayScreen.show();
}
if(exitBounds.contains(tmp.x,tmp.y)){
gameplayScreen.getTheme().dispose();
gameplayScreen.getGame().showMenuScreen();
gameplayScreen.dispose();
}
}
batch.end();
}
}
|
UTF-8
|
Java
| 3,656 |
java
|
FinishMenu.java
|
Java
|
[] | null |
[] |
package com.mygdx.akurun.overlays;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.mygdx.akurun.GameplayScreen;
import com.mygdx.akurun.util.Constants;
public class FinishMenu {
public final Viewport viewport;
private Texture window;
private Texture restartIcon;
private Texture exitIcon;
private Texture header;
private Texture table;
GameplayScreen gameplayScreen;
BitmapFont font;
private FreeTypeFontGenerator generator;
private FreeTypeFontGenerator.FreeTypeFontParameter parameter;
public FinishMenu(GameplayScreen gameplayScreen) {
this.gameplayScreen = gameplayScreen;
this.viewport = new ExtendViewport(Constants.HUD_VIEWPORT_SIZE, Constants.HUD_VIEWPORT_SIZE);
window = new Texture(Constants.WINDOW_HUD);
restartIcon = new Texture(Constants.RESTART_HUD);
exitIcon = new Texture(Constants.EXIT_HUD);
header = new Texture(Constants.HEADER_LOSE_HUD);
table = new Texture(Constants.TABLE_HUD);
generator = new FreeTypeFontGenerator(Gdx.files.internal(Constants.FONT_HUD));
parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 30;
parameter.borderWidth = 2f;
parameter.borderColor= Color.BLACK;
font = generator.generateFont(parameter);
generator.dispose();
}
public void render(SpriteBatch batch,int score) {
viewport.apply();
batch.setProjectionMatrix(viewport.getCamera().combined);
batch.begin();
batch.draw(window,viewport.getWorldWidth()/3f,viewport.getWorldHeight()/6,window.getWidth()/3f,window.getHeight()/3f);
batch.draw(table,viewport.getWorldWidth()/2.8f,viewport.getWorldHeight()/2.8f,window.getWidth()/3.5f,window.getHeight()/4.5f);
font.draw(batch,"Score : "+score,viewport.getWorldWidth()/2.3f,viewport.getWorldHeight()/1.7f);
batch.draw(header,viewport.getWorldWidth()/3.5f,viewport.getWorldHeight()/1.5f,header.getWidth()/2.5f,header.getHeight()/3.5f);
batch.draw(restartIcon,viewport.getWorldWidth()/1.8f,viewport.getWorldHeight()/4.5f,Constants.HUD_MARGIN*1.4f,Constants.HUD_MARGIN*1.4f);
batch.draw(exitIcon,viewport.getWorldWidth()/2.5f,viewport.getWorldHeight()/4.5f,Constants.HUD_MARGIN*1.4f,Constants.HUD_MARGIN*1.4f);
if(Gdx.input.justTouched()){
Vector3 tmp = new Vector3(Gdx.input.getX(),Gdx.input.getY(),0);
viewport.getCamera().unproject(tmp);
Rectangle restartBounds = new Rectangle(viewport.getWorldWidth()/1.8f,viewport.getWorldHeight()/4.5f,Constants.HUD_MARGIN*1.4f,Constants.HUD_MARGIN*1.4f);
Rectangle exitBounds = new Rectangle(viewport.getWorldWidth()/2.5f,viewport.getWorldHeight()/4.5f,Constants.HUD_MARGIN*1.4f,Constants.HUD_MARGIN*1.4f);
if(restartBounds.contains(tmp.x,tmp.y)){
gameplayScreen.getTheme().dispose();
gameplayScreen.show();
}
if(exitBounds.contains(tmp.x,tmp.y)){
gameplayScreen.getTheme().dispose();
gameplayScreen.getGame().showMenuScreen();
gameplayScreen.dispose();
}
}
batch.end();
}
}
| 3,656 | 0.704322 | 0.686269 | 79 | 45.278481 | 38.819263 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.151899 | false | false |
12
|
73978c280d83b84ba7df733b5c318ac1d7f2691e
| 27,084,063,808,766 |
1a7bcd7d99c978f5d336650fd3509c9015996a97
|
/src/StrToInt/StringToInteger.java
|
35bf4810a8c76ac14b629ecaecd5167d218fc599
|
[] |
no_license
|
karthikeyaJ/LeetCode
|
https://github.com/karthikeyaJ/LeetCode
|
cab05b444a491ffc79ddfeb65a5c8f5747bd8052
|
6bdd5461d22ae26b015dda99306c694719586b62
|
refs/heads/master
| 2021-01-10T08:47:16.618000 | 2015-11-24T18:55:56 | 2015-11-24T18:55:56 | 46,811,639 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package StrToInt;
import java.io.*;
class Solution {
public int myAtoi(String str) {
int k=0;
try{
if(str=="")
return 0;
else{
String numOnly = str.replaceAll("\\p{Alpha}","");
String s=String.valueOf(numOnly);
k=Integer.parseInt(s.trim());
}
}
catch(NumberFormatException nfe)
{
//System.out.println("Number Format Exception:"+nfe.getMessage());
}
return k;
}
}
public class StringToInteger {
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution s=new Solution();
int number=s.myAtoi(" -0012a3");
System.out.println(number);
}
}
|
UTF-8
|
Java
| 748 |
java
|
StringToInteger.java
|
Java
|
[] | null |
[] |
package StrToInt;
import java.io.*;
class Solution {
public int myAtoi(String str) {
int k=0;
try{
if(str=="")
return 0;
else{
String numOnly = str.replaceAll("\\p{Alpha}","");
String s=String.valueOf(numOnly);
k=Integer.parseInt(s.trim());
}
}
catch(NumberFormatException nfe)
{
//System.out.println("Number Format Exception:"+nfe.getMessage());
}
return k;
}
}
public class StringToInteger {
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution s=new Solution();
int number=s.myAtoi(" -0012a3");
System.out.println(number);
}
}
| 748 | 0.536096 | 0.526738 | 38 | 18.68421 | 18.339066 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false |
12
|
3fcc447fccbce478483d12ee9a9c5899c1dd9ec1
| 36,421,322,689,277 |
b3995035298c66483637347945eacfa46f46a717
|
/src/com/lge/posa/as3/EchoClient.java
|
c34b2000610231d2060ef072ad7f626979fb92eb
|
[] |
no_license
|
chisun-joung/POSA_AS1
|
https://github.com/chisun-joung/POSA_AS1
|
c61fa9aa2146610edf326c604fcdfa759f0872bd
|
26e4f72ec41754c32b4bec0bd5c7a147c49fe645
|
refs/heads/master
| 2016-03-28T16:33:23.262000 | 2013-05-12T10:52:23 | 2013-05-12T10:52:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lge.posa.as3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
/**
* @param args
*/
public static void main(String[] args) {
AcceptorConnectorClient r = new AcceptorConnectorClient(8889);
Thread t = new Thread(r);
t.start();
System.out.println("It's Client");
}
}
class AcceptorConnectorClient implements Runnable {
private Socket echoSocket;
private PrintWriter out;
private BufferedReader in;
public AcceptorConnectorClient(int port) {
try {
echoSocket = new Socket("localhost",port);
out = new PrintWriter(echoSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Dont't know about host: localhost");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: localhost");
}
}
@Override
public void run() {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
try {
while((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 1,531 |
java
|
EchoClient.java
|
Java
|
[] | null |
[] |
package com.lge.posa.as3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
/**
* @param args
*/
public static void main(String[] args) {
AcceptorConnectorClient r = new AcceptorConnectorClient(8889);
Thread t = new Thread(r);
t.start();
System.out.println("It's Client");
}
}
class AcceptorConnectorClient implements Runnable {
private Socket echoSocket;
private PrintWriter out;
private BufferedReader in;
public AcceptorConnectorClient(int port) {
try {
echoSocket = new Socket("localhost",port);
out = new PrintWriter(echoSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Dont't know about host: localhost");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: localhost");
}
}
@Override
public void run() {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
try {
while((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 1,531 | 0.694317 | 0.690398 | 63 | 23.301588 | 21.371717 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.857143 | false | false |
12
|
ebc4913d07fbaa8d4de67f37d1455a0808bf732f
| 24,584,392,857,092 |
c8685de2182e2d346225d6b9eb4523057a9ba6c7
|
/dhlk_tenant_plat/dhlk_basic_module_service/src/main/java/com/dhlk/basicmodule/service/service/impl/DmNetTypeServiceImpl.java
|
c50dea65575bffd0649739dea6d59a059c385845
|
[] |
no_license
|
957001352/project20201203
|
https://github.com/957001352/project20201203
|
bda6cc5797ca725b45a8e6d5fde1dbac76cbd75b
|
34515883d14e7779c6991b9b8bf70d60550a131f
|
refs/heads/main
| 2023-02-15T14:49:34.081000 | 2020-12-31T03:56:49 | 2020-12-31T03:56:49 | 318,063,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dhlk.basicmodule.service.service.impl;
import com.dhlk.basicmodule.service.dao.DmNetTypeDao;
import com.dhlk.basicmodule.service.service.DmNetTypeService;
import com.dhlk.entity.dm.DmNetType;
import com.dhlk.domain.Result;
import com.dhlk.exceptions.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dhlk.utils.CheckUtils;
import com.dhlk.utils.ResultUtils;
import java.util.Arrays;
/**
* @Description
* @Author lpsong
* @Date 2020/3/13
*/
@Service
public class DmNetTypeServiceImpl implements DmNetTypeService {
@Autowired
private DmNetTypeDao dmNetTypeDao;
@Override
public Result save(DmNetType dmNetType) throws MyException {
if(CheckUtils.isNull(dmNetType.getName())){
return ResultUtils.error("名称不能为空");
}
if(dmNetTypeDao.isRepeatName(dmNetType)>0){
return ResultUtils.error("名称重复");
}
//新增
Integer flag=0;
if (CheckUtils.isNull(dmNetType.getId())) {
flag=dmNetTypeDao.insert(dmNetType);
}else{//修改
flag=dmNetTypeDao.update(dmNetType);
}
return flag > 0 ? ResultUtils.success() : ResultUtils.failure();
}
@Override
public Result delete(String ids) throws MyException {
if (!CheckUtils.isNull(ids)) {
if (dmNetTypeDao.delete(Arrays.asList(ids.split(","))) > 0) {
return ResultUtils.success();
}
}
return ResultUtils.failure();
}
@Override
public Result findList(String name) throws MyException {
return ResultUtils.success(dmNetTypeDao.findList(name));
}
}
|
UTF-8
|
Java
| 1,744 |
java
|
DmNetTypeServiceImpl.java
|
Java
|
[
{
"context": " java.util.Arrays;\n\n/**\n * @Description\n * @Author lpsong\n * @Date 2020/3/13\n */\n@Service\npublic class DmNe",
"end": 519,
"score": 0.9996824264526367,
"start": 513,
"tag": "USERNAME",
"value": "lpsong"
}
] | null |
[] |
package com.dhlk.basicmodule.service.service.impl;
import com.dhlk.basicmodule.service.dao.DmNetTypeDao;
import com.dhlk.basicmodule.service.service.DmNetTypeService;
import com.dhlk.entity.dm.DmNetType;
import com.dhlk.domain.Result;
import com.dhlk.exceptions.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dhlk.utils.CheckUtils;
import com.dhlk.utils.ResultUtils;
import java.util.Arrays;
/**
* @Description
* @Author lpsong
* @Date 2020/3/13
*/
@Service
public class DmNetTypeServiceImpl implements DmNetTypeService {
@Autowired
private DmNetTypeDao dmNetTypeDao;
@Override
public Result save(DmNetType dmNetType) throws MyException {
if(CheckUtils.isNull(dmNetType.getName())){
return ResultUtils.error("名称不能为空");
}
if(dmNetTypeDao.isRepeatName(dmNetType)>0){
return ResultUtils.error("名称重复");
}
//新增
Integer flag=0;
if (CheckUtils.isNull(dmNetType.getId())) {
flag=dmNetTypeDao.insert(dmNetType);
}else{//修改
flag=dmNetTypeDao.update(dmNetType);
}
return flag > 0 ? ResultUtils.success() : ResultUtils.failure();
}
@Override
public Result delete(String ids) throws MyException {
if (!CheckUtils.isNull(ids)) {
if (dmNetTypeDao.delete(Arrays.asList(ids.split(","))) > 0) {
return ResultUtils.success();
}
}
return ResultUtils.failure();
}
@Override
public Result findList(String name) throws MyException {
return ResultUtils.success(dmNetTypeDao.findList(name));
}
}
| 1,744 | 0.671329 | 0.664918 | 60 | 27.616667 | 22.946381 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.366667 | false | false |
12
|
e8ee52e8a6723562414413fbff31a097c59ef165
| 34,067,680,624,645 |
409d2eab4fb92b7223e651dcb6c18b9e95448176
|
/GridStrategy/src/assembler/NewConditionDialog.java
|
42a9025fdbd827bbfde2fc66adeb981ac72b59be
|
[] |
no_license
|
oparish/GridStrategy
|
https://github.com/oparish/GridStrategy
|
392a4ed14db50f3eecfb1b1025fe97536fb764f2
|
7e3a0aca5b452892d685ddf5aa129a8ed1e91fb9
|
refs/heads/master
| 2021-01-18T22:58:20.565000 | 2016-05-07T19:23:37 | 2016-05-07T19:23:37 | 9,888,512 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package assembler;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import ai.ColumnCondition;
import ai.Condition;
import ai.CreditCondition;
import ai.GateCondition;
import ai.NoCondition;
import ai.Rule;
import ai.SpecificColumnCondition;
import ai.UnitCountCondition;
public class NewConditionDialog extends JDialog implements ActionListener
{
protected JButton okButton;
protected JButton cancelButton;
protected AssemblerList conditionOptions;
protected Assembler assembler;
NewConditionDialog(Assembler assembler)
{
super(assembler, true);
this.setLayout(new GridBagLayout());
this.setSize(500, 500);
this.assembler = assembler;
this.setupContents();
}
protected void setupContents()
{
this.setupConditionList(2);
this.setupOKButton();
this.setupCancelButton();
}
protected void setupOKButton()
{
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
this.okButton = new JButton("OK");
this.okButton.addActionListener(this);
this.add(this.okButton, gridBagConstraints);
}
protected void setupCancelButton()
{
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
this.cancelButton = new JButton("Cancel");
this.cancelButton.addActionListener(this);
this.add(this.cancelButton, gridBagConstraints);
}
protected void setupConditionList(int width)
{
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridwidth = width;
this.conditionOptions = new AssemblerList<Class<? extends Condition>>(new Class[]{ColumnCondition.class, UnitCountCondition.class, SpecificColumnCondition.class, GateCondition.class, CreditCondition.class, NoCondition.class}, AssemblerListType.CONDITIONCLASSES);
this.conditionOptions.setCellRenderer(new ConditionOptionsCellRenderer());
this.conditionOptions.setSelectedIndex(0);
this.add(new JScrollPane(this.conditionOptions), gridBagConstraints);
}
private class ConditionOptionsCellRenderer implements ListCellRenderer<Class<? extends Condition>>
{
@Override
public Component getListCellRendererComponent(
JList<? extends Class<? extends Condition>> arg0, Class<? extends Condition> conditionClass, int index, boolean selected,
boolean arg4)
{
String text = Condition.getConditionClassName(conditionClass);
if (selected)
{
return AssemblerList.getSelectedLabel(text);
}
else
{
return new JLabel(text);
}
}
}
@Override
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
if (source == this.okButton)
{
Condition condition = Condition.getConditionExample((Class<? extends Condition>) this.conditionOptions.getSelectedValue());
this.assembler.changeCondition(condition);
this.dispose();
}
else
{
this.dispose();
}
}
}
|
UTF-8
|
Java
| 3,330 |
java
|
NewConditionDialog.java
|
Java
|
[] | null |
[] |
package assembler;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import ai.ColumnCondition;
import ai.Condition;
import ai.CreditCondition;
import ai.GateCondition;
import ai.NoCondition;
import ai.Rule;
import ai.SpecificColumnCondition;
import ai.UnitCountCondition;
public class NewConditionDialog extends JDialog implements ActionListener
{
protected JButton okButton;
protected JButton cancelButton;
protected AssemblerList conditionOptions;
protected Assembler assembler;
NewConditionDialog(Assembler assembler)
{
super(assembler, true);
this.setLayout(new GridBagLayout());
this.setSize(500, 500);
this.assembler = assembler;
this.setupContents();
}
protected void setupContents()
{
this.setupConditionList(2);
this.setupOKButton();
this.setupCancelButton();
}
protected void setupOKButton()
{
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
this.okButton = new JButton("OK");
this.okButton.addActionListener(this);
this.add(this.okButton, gridBagConstraints);
}
protected void setupCancelButton()
{
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
this.cancelButton = new JButton("Cancel");
this.cancelButton.addActionListener(this);
this.add(this.cancelButton, gridBagConstraints);
}
protected void setupConditionList(int width)
{
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridwidth = width;
this.conditionOptions = new AssemblerList<Class<? extends Condition>>(new Class[]{ColumnCondition.class, UnitCountCondition.class, SpecificColumnCondition.class, GateCondition.class, CreditCondition.class, NoCondition.class}, AssemblerListType.CONDITIONCLASSES);
this.conditionOptions.setCellRenderer(new ConditionOptionsCellRenderer());
this.conditionOptions.setSelectedIndex(0);
this.add(new JScrollPane(this.conditionOptions), gridBagConstraints);
}
private class ConditionOptionsCellRenderer implements ListCellRenderer<Class<? extends Condition>>
{
@Override
public Component getListCellRendererComponent(
JList<? extends Class<? extends Condition>> arg0, Class<? extends Condition> conditionClass, int index, boolean selected,
boolean arg4)
{
String text = Condition.getConditionClassName(conditionClass);
if (selected)
{
return AssemblerList.getSelectedLabel(text);
}
else
{
return new JLabel(text);
}
}
}
@Override
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
if (source == this.okButton)
{
Condition condition = Condition.getConditionExample((Class<? extends Condition>) this.conditionOptions.getSelectedValue());
this.assembler.changeCondition(condition);
this.dispose();
}
else
{
this.dispose();
}
}
}
| 3,330 | 0.776577 | 0.771772 | 116 | 27.706896 | 32.864933 | 264 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.060345 | false | false |
12
|
ed80c0b53c74bb8dd21e68398f22ed7333fd5550
| 36,850,819,413,984 |
850aabdf0230116a3df5535bde4969d04a359af1
|
/app/src/main/java/com/douglas/jointlyapp/ui/chat/ChatContract.java
|
aecf0cfa72fc5a67997b3eb80f7b80103a93fff6
|
[] |
no_license
|
DouglasWarner/JointlyApp
|
https://github.com/DouglasWarner/JointlyApp
|
7815b51558f46a7d9f41477e80110418299831a7
|
02ab1f1698b246d0bdb482c952bfac2eff919425
|
refs/heads/master
| 2023-06-04T22:35:51.291000 | 2021-03-02T22:54:40 | 2021-03-02T22:54:40 | 308,017,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.douglas.jointlyapp.ui.chat;
import com.douglas.jointlyapp.data.model.Chat;
import com.douglas.jointlyapp.ui.base.BaseListView;
import com.douglas.jointlyapp.ui.base.BasePresenter;
public interface ChatContract {
interface View extends BaseListView<Chat>
{
void setNoData();
void showProgress();
void hideProgress();
void onSuccessSendMessage(Chat chat);
}
interface Presenter extends BasePresenter
{
void loadChat(int idInitiative);
void sendMessage(int idInitiative, String userEmail, String message);
}
}
|
UTF-8
|
Java
| 595 |
java
|
ChatContract.java
|
Java
|
[] | null |
[] |
package com.douglas.jointlyapp.ui.chat;
import com.douglas.jointlyapp.data.model.Chat;
import com.douglas.jointlyapp.ui.base.BaseListView;
import com.douglas.jointlyapp.ui.base.BasePresenter;
public interface ChatContract {
interface View extends BaseListView<Chat>
{
void setNoData();
void showProgress();
void hideProgress();
void onSuccessSendMessage(Chat chat);
}
interface Presenter extends BasePresenter
{
void loadChat(int idInitiative);
void sendMessage(int idInitiative, String userEmail, String message);
}
}
| 595 | 0.712605 | 0.712605 | 22 | 26.045454 | 22.235266 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
12
|
0d2aa09458fae3f3e7e2b93a49791417bbf05dd9
| 18,786,186,990,979 |
f56fc41a9ba51f7f4b056595589105259b9f6d36
|
/libenc/JOggOpusComments.java
|
605d4ef76401aaa55e266734b833b39163123661
|
[] |
no_license
|
ggrandes-clones/jopus
|
https://github.com/ggrandes-clones/jopus
|
adbcfaf18948f53714211cd819f3bceaac0a0f00
|
c179bf2012cb2542386c91a309720527a559ec4c
|
refs/heads/master
| 2020-11-27T23:19:22.695000 | 2019-12-22T23:33:27 | 2019-12-22T23:33:27 | 229,644,009 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package libenc;
import java.nio.charset.Charset;
import java.util.Arrays;
import celt.Jcelt;
/** Opaque comments struct. */
/**
Comments will be stored in the Vorbis style.
It is described in the "Structure" section of
http://www.xiph.org/ogg/vorbis/doc/v-comment.html
However, Opus and other non-vorbis formats omit the "framing_bit".
The comment header is decoded as follows:
1) [vendor_length] = read an unsigned integer of 32 bits
2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets
3) [user_comment_list_length] = read an unsigned integer of 32 bits
4) iterate [user_comment_list_length] times {
5) [length] = read an unsigned integer of 32 bits
6) this iteration's user comment = read a UTF-8 vector as [length] octets
}
7) done.
*/
public final class JOggOpusComments {// java: check ope_comments_copy if a new field is added or removed.
byte[] comment;
// int comment_length;// java: comment.length
boolean seen_file_icons;
/** Create a new comments object. The vendor string is optional. */
/** Create a new comments object.
@return Newly-created comments object. */
public static final JOggOpusComments ope_comments_create() {
// char vendor_str[1024];
final JOggOpusComments c = new JOggOpusComments();
// final byte[] libopus_str = Jcelt.opus_get_version_string();
// snprintf( vendor_str, sizeof(vendor_str), "%s, %s %s", libopus_str, PACKAGE_NAME, PACKAGE_VERSION );
final String vendor_str = String.format( "%s, %s %s", Jcelt.opus_get_version_string(), JOggOpusEnc.PACKAGE_NAME, JOggOpusEnc.PACKAGE_VERSION );
c.opeint_comment_init( vendor_str );
c.seen_file_icons = false;
if( c.comment == null ) {
return null;
}
return c;
}
/** Create a deep copy of a comments object. */
/** Create a deep copy of a comments object.
@param comments Comments object to copy
@return Deep copy of input. */
public static final JOggOpusComments ope_comments_copy(final JOggOpusComments comments) {
final JOggOpusComments c = new JOggOpusComments();
// if( c == null ) return null;
//memcpy(c, comments, sizeof(*c));
// c.comment_length = comments.comment_length;
c.seen_file_icons = comments.seen_file_icons;
c.comment = new byte[ comments.comment.length ];
//if( c.comment == null ) {
// free(c);
// return null;
//} else {
// memcpy(c.comment, comments.comment, comments.comment_length);
// return c;
//}
c.comment = Arrays.copyOf( comments.comment, comments.comment.length );
return c;
}
/** Destroys a comments object. */
/** Destroys a comments object.
@param comments Comments object to destroy*/
public static final void ope_comments_destroy(JOggOpusComments comments) {
comments.comment = null;
comments = null;
}
/** Add a comment. */
/** Add a comment.
@param comments [in,out] Where to add the comments
@param tag Tag for the comment (must not contain = char)
@param val Value for the tag
@return Error code
*/
public final int ope_comments_add(final String tag, final String val) {
if( tag == null || val == null ) {
return JOggOpusEnc.OPE_BAD_ARG;
}
if( tag.indexOf('=') >= 0 ) {
return JOggOpusEnc.OPE_BAD_ARG;
}
// if( opeint_comment_add( &comments.comment, &comments.comment_length, tag, val) ) return OPE_ALLOC_FAIL;
if( this.opeint_comment_add( tag, val) ) {
return JOggOpusEnc.OPE_ALLOC_FAIL;
}
return JOggOpusEnc.OPE_OK;
}
/** Add a comment. */
/** Add a comment as a single tag=value string.
@param comments [in,out] Where to add the comments
@param tag_and_val string of the form tag=value (must contain = char)
@return Error code
*/
public final int ope_comments_add_string(final String tag_and_val) {
if( tag_and_val.indexOf('=') < 0 ) {
return JOggOpusEnc.OPE_BAD_ARG;
}
if( this.opeint_comment_add( null, tag_and_val) ) {
return JOggOpusEnc.OPE_ALLOC_FAIL;
}
return JOggOpusEnc.OPE_OK;
}
private static final int readint(final byte[] buf, int offset) {
int v = ((int)buf[ offset++ ]) & 0xFF;
v |= ((int)buf[ offset++ ] << 8) & 0xFF00;
v |= ((int)buf[ offset++ ] << 16) & 0xFF0000;
v |= ((int)buf[ offset ] << 24);// & 0xFF000000;
return v;
}
private static final void writeint(final byte[] buf, int offset, final int val) {
buf[ offset++ ] = (byte)val;
buf[ offset++ ] = (byte)(val >> 8);
buf[ offset++ ] = (byte)(val >> 16);
buf[ offset ] = (byte)(val >> 24);
}
// java: char **comments, int* length are replaced by JOggOpusComments
final void opeint_comment_init(final String vendor_string)
{
/*The 'vendor' field should be the actual encoding library used.*/
// int vendor_length = strlen(vendor_string);
// int user_comment_list_length = 0;
// int len = 8 + 4 + vendor_length + 4;
// char *p = (char*)malloc(len);
// if( p == NULL ) {
// len = 0;
// } else {
// memcpy(p, "OpusTags", 8);
// writeint(p, 8, vendor_length);
// memcpy(p + 12, vendor_string, vendor_length);
// writeint(p, 12 + vendor_length, user_comment_list_length);
//}
// *length = len;
// *comments = p;
// java:
final byte sbyte[] = vendor_string.getBytes( Charset.forName("UTF-8") );
final int vendor_length = sbyte.length;
final int user_comment_list_length = 0;
final int len = 8 + 4 + vendor_length + 4;
final byte[] p = new byte[ len ];
System.arraycopy( "OpusTags".getBytes( Charset.forName("UTF-8") ), 0, p, 0, 8 );
writeint( p, 8, vendor_length );
System.arraycopy( p, 12, sbyte, 0, vendor_length );
writeint( p, 12 + vendor_length, user_comment_list_length );
// this.comment_length = len;
this.comment = p;
}
private static final int strlen(final byte[] str, int offset) {
do {
if( str[offset] == '\0' ) {
return offset;
}
offset++;
} while( offset < str.length );
return offset;
}
// java: char **comments, int* length are replaced by JOggOpusComments
/**
*
* @param comments the comments
* @param tag the tag name.
* @param val 0-ended data.
* @return false - ok.
*/
final boolean opeint_comment_add(final String tag, final byte[] val)
{
byte[] p = this.comment;
final int vendor_length = readint( p, 8 );
final int user_comment_list_length = readint( p, 8 + 4 + vendor_length );
//int tag_len = (tag ? strlen( tag ) + 1 : 0);
final byte[] stag = tag != null ? tag.getBytes( Charset.forName("UTF-8") ) : new byte[0];
final int val_len = strlen( val, 0 );
//int len = (*length) + 4 + tag_len + val_len;
final int len = this.comment.length + 4 + 1 + stag.length + val_len;
p = Arrays.copyOf( p, len );
// if( p == null ) return true;
writeint( p, this.comment.length, 1 + stag.length + val_len );/* length of comment */
if( tag != null ) {
System.arraycopy( tag, 0, p, this.comment.length + 4, stag.length );/* comment tag */
p[this.comment.length + 4 + stag.length] = '=';/* separator */
}
System.arraycopy( val, 0, p, this.comment.length + 4 + 1 + stag.length, val_len );/* comment */
writeint( p, 8 + 4 + vendor_length, user_comment_list_length + 1 );
this.comment = p;
// this.comment_length = len;
return false;
}
// java: char **comments, int* length are replaced by JOggOpusComments
final boolean opeint_comment_add(final String tag, String val)
{
byte[] p = this.comment;
final int vendor_length = readint( p, 8 );
final int user_comment_list_length = readint( p, 8 + 4 + vendor_length );
//int tag_len = (tag ? strlen( tag ) + 1 : 0);
//int val_len = strlen( val );
//int len = (*length) + 4 + tag_len + val_len;
//p = Arrays.copyOf( p, len );
//if( p == null ) return true;
//writeint( p, *length, tag_len + val_len ); /* length of comment */
//if( tag ) {
// memcpy( p + *length + 4, tag, tag_len ); /* comment tag */
// (p + *length + 4)[tag_len - 1] = '='; /* separator */
//}
//memcpy( p + *length + 4 + tag_len, val, val_len ); /* comment */
//writeint( p, 8 + 4 + vendor_length, user_comment_list_length + 1 );
//*comments = p;
//*length = len;
if( tag != null && ! tag.isEmpty() ) {
val = tag + '=' + val;
}
final byte[] sbyte = val.getBytes( Charset.forName("UTF-8") );
final int len = this.comment.length + 4 + sbyte.length;
p = Arrays.copyOf( p, len );
writeint( p, this.comment.length, sbyte.length );// length of comment
System.arraycopy( sbyte, 0, p, this.comment.length + 4, sbyte.length );// comment
writeint( p, 8 + 4 + vendor_length, user_comment_list_length + 1 );
this.comment = p;
// this.comment_length = len;
return false;
}
/**
* Java changed: a new comment buffer is returned
*
* @param comments a buffer
* @param amount a required size
* @return the buffer to hold data
*/
static final byte[] opeint_comment_pad(byte[] comments, final int amount)
{
if( amount > 0 ) {
if( comments == null ) {
final int newlen = (amount + 255) / 255 * 255 - 1;
comments = new byte[ newlen ];
return comments;
}
/*Make sure there is at least amount worth of padding free, and
round up to the maximum that fits in the current ogg segments.*/
final int newlen = (comments.length + amount + 255) / 255 * 255 - 1;
comments = Arrays.copyOf( comments, newlen );
// if( p == NULL ) return;
// for( int i = comments.comment_length; i < newlen; i++ ) p[i] = 0;// java: already zeroed
}
return comments;
}
/** Add a picture from a file.
@param comments [in,out] Where to add the comments
@param filename File name for the picture
@param picture_type Type of picture (-1 for default)
@param description Description (NULL means no comment)
@return Error code
*/
public final int ope_comments_add_picture(final String filename, final int picture_type, final String description) {
//int err;
//byte[] picture_data = Jpicture.opeint_parse_picture_specification( filename, picture_type, description, &err, &comments.seen_file_icons );
//if( picture_data == null || err != OPE_OK ) {
// return err;
//}
//JOpusHeader.opeint_comment_add( comments, "METADATA_BLOCK_PICTURE", picture_data );
//picture_data = null;
return JOggOpusEnc.OPE_OK;// TODO java: read a picture
}
/** Add a picture already in memory.
@param comments [in,out] Where to add the comments
@param ptr Pointer to picture in memory
@param size Size of picture pointed to by ptr
@param picture_type Type of picture (-1 for default)
@param description Description (NULL means no comment)
@return Error code
*/
public final int ope_comments_add_picture_from_memory(final byte[] ptr, final int size, final int picture_type, final String description ) {
//int err;
//final byte[] picture_data = JOpusHeader.opeint_parse_picture_specification_from_memory( ptr, size, picture_type, description, &err, &comments.seen_file_icons );
//if( picture_data == null || err != OPE_OK ) {
// return err;
//}
//JOpusHeader.opeint_comment_add( comments, "METADATA_BLOCK_PICTURE", picture_data );
// picture_data = null;
return JOggOpusEnc.OPE_OK;// TODO java: read a picture
}
}
|
UTF-8
|
Java
| 11,412 |
java
|
JOggOpusComments.java
|
Java
|
[] | null |
[] |
package libenc;
import java.nio.charset.Charset;
import java.util.Arrays;
import celt.Jcelt;
/** Opaque comments struct. */
/**
Comments will be stored in the Vorbis style.
It is described in the "Structure" section of
http://www.xiph.org/ogg/vorbis/doc/v-comment.html
However, Opus and other non-vorbis formats omit the "framing_bit".
The comment header is decoded as follows:
1) [vendor_length] = read an unsigned integer of 32 bits
2) [vendor_string] = read a UTF-8 vector as [vendor_length] octets
3) [user_comment_list_length] = read an unsigned integer of 32 bits
4) iterate [user_comment_list_length] times {
5) [length] = read an unsigned integer of 32 bits
6) this iteration's user comment = read a UTF-8 vector as [length] octets
}
7) done.
*/
public final class JOggOpusComments {// java: check ope_comments_copy if a new field is added or removed.
byte[] comment;
// int comment_length;// java: comment.length
boolean seen_file_icons;
/** Create a new comments object. The vendor string is optional. */
/** Create a new comments object.
@return Newly-created comments object. */
public static final JOggOpusComments ope_comments_create() {
// char vendor_str[1024];
final JOggOpusComments c = new JOggOpusComments();
// final byte[] libopus_str = Jcelt.opus_get_version_string();
// snprintf( vendor_str, sizeof(vendor_str), "%s, %s %s", libopus_str, PACKAGE_NAME, PACKAGE_VERSION );
final String vendor_str = String.format( "%s, %s %s", Jcelt.opus_get_version_string(), JOggOpusEnc.PACKAGE_NAME, JOggOpusEnc.PACKAGE_VERSION );
c.opeint_comment_init( vendor_str );
c.seen_file_icons = false;
if( c.comment == null ) {
return null;
}
return c;
}
/** Create a deep copy of a comments object. */
/** Create a deep copy of a comments object.
@param comments Comments object to copy
@return Deep copy of input. */
public static final JOggOpusComments ope_comments_copy(final JOggOpusComments comments) {
final JOggOpusComments c = new JOggOpusComments();
// if( c == null ) return null;
//memcpy(c, comments, sizeof(*c));
// c.comment_length = comments.comment_length;
c.seen_file_icons = comments.seen_file_icons;
c.comment = new byte[ comments.comment.length ];
//if( c.comment == null ) {
// free(c);
// return null;
//} else {
// memcpy(c.comment, comments.comment, comments.comment_length);
// return c;
//}
c.comment = Arrays.copyOf( comments.comment, comments.comment.length );
return c;
}
/** Destroys a comments object. */
/** Destroys a comments object.
@param comments Comments object to destroy*/
public static final void ope_comments_destroy(JOggOpusComments comments) {
comments.comment = null;
comments = null;
}
/** Add a comment. */
/** Add a comment.
@param comments [in,out] Where to add the comments
@param tag Tag for the comment (must not contain = char)
@param val Value for the tag
@return Error code
*/
public final int ope_comments_add(final String tag, final String val) {
if( tag == null || val == null ) {
return JOggOpusEnc.OPE_BAD_ARG;
}
if( tag.indexOf('=') >= 0 ) {
return JOggOpusEnc.OPE_BAD_ARG;
}
// if( opeint_comment_add( &comments.comment, &comments.comment_length, tag, val) ) return OPE_ALLOC_FAIL;
if( this.opeint_comment_add( tag, val) ) {
return JOggOpusEnc.OPE_ALLOC_FAIL;
}
return JOggOpusEnc.OPE_OK;
}
/** Add a comment. */
/** Add a comment as a single tag=value string.
@param comments [in,out] Where to add the comments
@param tag_and_val string of the form tag=value (must contain = char)
@return Error code
*/
public final int ope_comments_add_string(final String tag_and_val) {
if( tag_and_val.indexOf('=') < 0 ) {
return JOggOpusEnc.OPE_BAD_ARG;
}
if( this.opeint_comment_add( null, tag_and_val) ) {
return JOggOpusEnc.OPE_ALLOC_FAIL;
}
return JOggOpusEnc.OPE_OK;
}
private static final int readint(final byte[] buf, int offset) {
int v = ((int)buf[ offset++ ]) & 0xFF;
v |= ((int)buf[ offset++ ] << 8) & 0xFF00;
v |= ((int)buf[ offset++ ] << 16) & 0xFF0000;
v |= ((int)buf[ offset ] << 24);// & 0xFF000000;
return v;
}
private static final void writeint(final byte[] buf, int offset, final int val) {
buf[ offset++ ] = (byte)val;
buf[ offset++ ] = (byte)(val >> 8);
buf[ offset++ ] = (byte)(val >> 16);
buf[ offset ] = (byte)(val >> 24);
}
// java: char **comments, int* length are replaced by JOggOpusComments
final void opeint_comment_init(final String vendor_string)
{
/*The 'vendor' field should be the actual encoding library used.*/
// int vendor_length = strlen(vendor_string);
// int user_comment_list_length = 0;
// int len = 8 + 4 + vendor_length + 4;
// char *p = (char*)malloc(len);
// if( p == NULL ) {
// len = 0;
// } else {
// memcpy(p, "OpusTags", 8);
// writeint(p, 8, vendor_length);
// memcpy(p + 12, vendor_string, vendor_length);
// writeint(p, 12 + vendor_length, user_comment_list_length);
//}
// *length = len;
// *comments = p;
// java:
final byte sbyte[] = vendor_string.getBytes( Charset.forName("UTF-8") );
final int vendor_length = sbyte.length;
final int user_comment_list_length = 0;
final int len = 8 + 4 + vendor_length + 4;
final byte[] p = new byte[ len ];
System.arraycopy( "OpusTags".getBytes( Charset.forName("UTF-8") ), 0, p, 0, 8 );
writeint( p, 8, vendor_length );
System.arraycopy( p, 12, sbyte, 0, vendor_length );
writeint( p, 12 + vendor_length, user_comment_list_length );
// this.comment_length = len;
this.comment = p;
}
private static final int strlen(final byte[] str, int offset) {
do {
if( str[offset] == '\0' ) {
return offset;
}
offset++;
} while( offset < str.length );
return offset;
}
// java: char **comments, int* length are replaced by JOggOpusComments
/**
*
* @param comments the comments
* @param tag the tag name.
* @param val 0-ended data.
* @return false - ok.
*/
final boolean opeint_comment_add(final String tag, final byte[] val)
{
byte[] p = this.comment;
final int vendor_length = readint( p, 8 );
final int user_comment_list_length = readint( p, 8 + 4 + vendor_length );
//int tag_len = (tag ? strlen( tag ) + 1 : 0);
final byte[] stag = tag != null ? tag.getBytes( Charset.forName("UTF-8") ) : new byte[0];
final int val_len = strlen( val, 0 );
//int len = (*length) + 4 + tag_len + val_len;
final int len = this.comment.length + 4 + 1 + stag.length + val_len;
p = Arrays.copyOf( p, len );
// if( p == null ) return true;
writeint( p, this.comment.length, 1 + stag.length + val_len );/* length of comment */
if( tag != null ) {
System.arraycopy( tag, 0, p, this.comment.length + 4, stag.length );/* comment tag */
p[this.comment.length + 4 + stag.length] = '=';/* separator */
}
System.arraycopy( val, 0, p, this.comment.length + 4 + 1 + stag.length, val_len );/* comment */
writeint( p, 8 + 4 + vendor_length, user_comment_list_length + 1 );
this.comment = p;
// this.comment_length = len;
return false;
}
// java: char **comments, int* length are replaced by JOggOpusComments
final boolean opeint_comment_add(final String tag, String val)
{
byte[] p = this.comment;
final int vendor_length = readint( p, 8 );
final int user_comment_list_length = readint( p, 8 + 4 + vendor_length );
//int tag_len = (tag ? strlen( tag ) + 1 : 0);
//int val_len = strlen( val );
//int len = (*length) + 4 + tag_len + val_len;
//p = Arrays.copyOf( p, len );
//if( p == null ) return true;
//writeint( p, *length, tag_len + val_len ); /* length of comment */
//if( tag ) {
// memcpy( p + *length + 4, tag, tag_len ); /* comment tag */
// (p + *length + 4)[tag_len - 1] = '='; /* separator */
//}
//memcpy( p + *length + 4 + tag_len, val, val_len ); /* comment */
//writeint( p, 8 + 4 + vendor_length, user_comment_list_length + 1 );
//*comments = p;
//*length = len;
if( tag != null && ! tag.isEmpty() ) {
val = tag + '=' + val;
}
final byte[] sbyte = val.getBytes( Charset.forName("UTF-8") );
final int len = this.comment.length + 4 + sbyte.length;
p = Arrays.copyOf( p, len );
writeint( p, this.comment.length, sbyte.length );// length of comment
System.arraycopy( sbyte, 0, p, this.comment.length + 4, sbyte.length );// comment
writeint( p, 8 + 4 + vendor_length, user_comment_list_length + 1 );
this.comment = p;
// this.comment_length = len;
return false;
}
/**
* Java changed: a new comment buffer is returned
*
* @param comments a buffer
* @param amount a required size
* @return the buffer to hold data
*/
static final byte[] opeint_comment_pad(byte[] comments, final int amount)
{
if( amount > 0 ) {
if( comments == null ) {
final int newlen = (amount + 255) / 255 * 255 - 1;
comments = new byte[ newlen ];
return comments;
}
/*Make sure there is at least amount worth of padding free, and
round up to the maximum that fits in the current ogg segments.*/
final int newlen = (comments.length + amount + 255) / 255 * 255 - 1;
comments = Arrays.copyOf( comments, newlen );
// if( p == NULL ) return;
// for( int i = comments.comment_length; i < newlen; i++ ) p[i] = 0;// java: already zeroed
}
return comments;
}
/** Add a picture from a file.
@param comments [in,out] Where to add the comments
@param filename File name for the picture
@param picture_type Type of picture (-1 for default)
@param description Description (NULL means no comment)
@return Error code
*/
public final int ope_comments_add_picture(final String filename, final int picture_type, final String description) {
//int err;
//byte[] picture_data = Jpicture.opeint_parse_picture_specification( filename, picture_type, description, &err, &comments.seen_file_icons );
//if( picture_data == null || err != OPE_OK ) {
// return err;
//}
//JOpusHeader.opeint_comment_add( comments, "METADATA_BLOCK_PICTURE", picture_data );
//picture_data = null;
return JOggOpusEnc.OPE_OK;// TODO java: read a picture
}
/** Add a picture already in memory.
@param comments [in,out] Where to add the comments
@param ptr Pointer to picture in memory
@param size Size of picture pointed to by ptr
@param picture_type Type of picture (-1 for default)
@param description Description (NULL means no comment)
@return Error code
*/
public final int ope_comments_add_picture_from_memory(final byte[] ptr, final int size, final int picture_type, final String description ) {
//int err;
//final byte[] picture_data = JOpusHeader.opeint_parse_picture_specification_from_memory( ptr, size, picture_type, description, &err, &comments.seen_file_icons );
//if( picture_data == null || err != OPE_OK ) {
// return err;
//}
//JOpusHeader.opeint_comment_add( comments, "METADATA_BLOCK_PICTURE", picture_data );
// picture_data = null;
return JOggOpusEnc.OPE_OK;// TODO java: read a picture
}
}
| 11,412 | 0.627936 | 0.615668 | 303 | 35.663368 | 29.596609 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.39934 | false | false |
0
|
c16cde037b46fb16ce640e61356abd7f0fb946cd
| 19,086,834,691,327 |
eafc645080b6b4adad138a31cd929217159582eb
|
/atbw2/src/FibonacciNumber.java
|
9a378c04c9d1f10ec8a8169aa58514ed78a3f177
|
[] |
no_license
|
emgusev/study
|
https://github.com/emgusev/study
|
8ba4f6719c8b271d49f83e0355545b9fb59679fa
|
47dc96b22be7148185eb60b38863dbbd871baad9
|
refs/heads/master
| 2020-03-23T19:57:08.524000 | 2018-09-11T03:37:47 | 2018-09-11T03:37:47 | 142,011,974 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
/**
* Created by egusev on 23.07.18.
*/
public class FibonacciNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if(n < 0 || n > 45) {
return;
}
int[] fib = new int[n+1];
if(n==0) {
System.out.println(0);
return;
}
if(n==1) {
System.out.println(1);
return;
}
fib[0] = 0;
fib[1] = 1;
for(int i=2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
System.out.println(fib[n]);
}
}
|
UTF-8
|
Java
| 664 |
java
|
FibonacciNumber.java
|
Java
|
[
{
"context": "import java.util.Scanner;\n\n/**\n * Created by egusev on 23.07.18.\n */\npublic class FibonacciNumber {\n ",
"end": 51,
"score": 0.999589741230011,
"start": 45,
"tag": "USERNAME",
"value": "egusev"
}
] | null |
[] |
import java.util.Scanner;
/**
* Created by egusev on 23.07.18.
*/
public class FibonacciNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if(n < 0 || n > 45) {
return;
}
int[] fib = new int[n+1];
if(n==0) {
System.out.println(0);
return;
}
if(n==1) {
System.out.println(1);
return;
}
fib[0] = 0;
fib[1] = 1;
for(int i=2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
System.out.println(fib[n]);
}
}
| 664 | 0.430723 | 0.399096 | 29 | 21.896551 | 13.641582 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586207 | false | false |
0
|
afa007f3a28b52ec7763786334df467e18b7b4a6
| 19,086,834,690,994 |
0670cdd07590a9f52b02ce2f48a39d6c92d7570d
|
/src/main/java/com/gs/spider/controller/home/HomeController.java
|
e0c666aa769ec2d6522f34d36345aa0966f6cd49
|
[] |
no_license
|
miki-hmt/java-spider
|
https://github.com/miki-hmt/java-spider
|
b527184f7c3ade66960756fcfea6028dd43df0be
|
93603c41ac600be707957e42b988342684694a05
|
refs/heads/main
| 2023-01-01T18:50:15.954000 | 2020-10-27T12:18:22 | 2020-10-27T12:18:22 | 307,688,278 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.gs.spider.controller.home;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.gs.spider.controller.BaseController;
import com.gs.spider.utils.AppInfo;
@Controller
@RequestMapping("/")
public class HomeController extends BaseController {
private final static Logger logger = LogManager.getLogger(HomeController.class);
@RequestMapping(value = { "/", "" }, method = RequestMethod.GET)
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView("panel/welcome/welcome");
modelAndView.addObject("appName", AppInfo.APP_NAME).addObject("appVersion", AppInfo.APP_VERSION)
.addObject("onlineDocumentation", AppInfo.ONLINE_DOCUMENTATION);
return modelAndView;
}
}
|
UTF-8
|
Java
| 973 |
java
|
HomeController.java
|
Java
|
[] | null |
[] |
package com.gs.spider.controller.home;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.gs.spider.controller.BaseController;
import com.gs.spider.utils.AppInfo;
@Controller
@RequestMapping("/")
public class HomeController extends BaseController {
private final static Logger logger = LogManager.getLogger(HomeController.class);
@RequestMapping(value = { "/", "" }, method = RequestMethod.GET)
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView("panel/welcome/welcome");
modelAndView.addObject("appName", AppInfo.APP_NAME).addObject("appVersion", AppInfo.APP_VERSION)
.addObject("onlineDocumentation", AppInfo.ONLINE_DOCUMENTATION);
return modelAndView;
}
}
| 973 | 0.801644 | 0.799589 | 26 | 36.423077 | 28.540354 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.230769 | false | false |
0
|
10cfa82d48fab771a9d33e60b486994360bd4d32
| 38,920,993,681,043 |
0e0873d3f3a1248dbea0c5b055147fe02a4c8ddc
|
/src/main/java/com/tvajjala/reactive/spring/config/CustomAuthenticationEntryPoint.java
|
007db0c728bee441509a06f9b6443d2758ec90c2
|
[] |
no_license
|
spring-micro-services/reactive-spring
|
https://github.com/spring-micro-services/reactive-spring
|
47059120035d4cfd3e5dc49860eec1f3d117a64a
|
24d879388c9bbb4ec7624775d5a4c42937c5c278
|
refs/heads/master
| 2020-09-27T18:26:09.379000 | 2020-01-19T19:30:32 | 2020-01-19T19:30:32 | 226,579,190 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tvajjala.reactive.spring.config;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CustomAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
public CustomAuthenticationEntryPoint(String realmName){
super.setRealmName(realmName);
}
@Override
public void setRealmName(String realmName) {
super.setRealmName(realmName);
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
//customize your response here
response.addHeader("WWW-Authenticate", "Basic realm=\"TVAJJALA\"");
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
}
}
|
UTF-8
|
Java
| 1,055 |
java
|
CustomAuthenticationEntryPoint.java
|
Java
|
[] | null |
[] |
package com.tvajjala.reactive.spring.config;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CustomAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
public CustomAuthenticationEntryPoint(String realmName){
super.setRealmName(realmName);
}
@Override
public void setRealmName(String realmName) {
super.setRealmName(realmName);
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
//customize your response here
response.addHeader("WWW-Authenticate", "Basic realm=\"TVAJJALA\"");
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
}
}
| 1,055 | 0.788626 | 0.788626 | 30 | 34.166668 | 36.351143 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
894a3028378e0ed8fdc2373bab0aba591c258ea2
| 29,326,036,704,263 |
2a352b7bb0a3034f1b0a6261e5994db4ca42a4c7
|
/src/main/java/com/example/model/dto/PersonResponse.java
|
591c9291f9eab51644068c1922f964bedbd5792b
|
[] |
no_license
|
edwardKatsCourse/java-3h-jpa-1-introduction
|
https://github.com/edwardKatsCourse/java-3h-jpa-1-introduction
|
d2953dbcad79720e5c860cbe85eac27898de999e
|
f810afe1e0fc81e965c21d786af84955fb408ce1
|
refs/heads/master
| 2020-06-23T17:51:37.345000 | 2019-07-24T20:30:44 | 2019-07-24T20:30:44 | 198,705,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.model.dto;
import lombok.*;
import java.time.LocalDate;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
@ToString
public class PersonResponse {
private Long id;
private String name;
private LocalDate dateOfBirth;
}
|
UTF-8
|
Java
| 267 |
java
|
PersonResponse.java
|
Java
|
[] | null |
[] |
package com.example.model.dto;
import lombok.*;
import java.time.LocalDate;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
@ToString
public class PersonResponse {
private Long id;
private String name;
private LocalDate dateOfBirth;
}
| 267 | 0.764045 | 0.764045 | 18 | 13.833333 | 11.407844 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
0
|
fa7efe3beecf09617d02cd2a8dbfba6e02245c76
| 17,300,128,286,896 |
f8cbf08637e76667dd50b1dbba3eb25c12444f43
|
/src/main/java/com/szo/app/model/package-info.java
|
f591e11812b76294117ac8b56e06ac84a2b670d9
|
[] |
no_license
|
szogroup/szojava
|
https://github.com/szogroup/szojava
|
fb42d51e99bb5fbd3403e5ed007885e829d1c470
|
fadf2629feed21273dbeeb4dd6dc94b98a28abd5
|
refs/heads/master
| 2016-03-30T12:27:52.164000 | 2015-04-23T09:38:19 | 2015-04-23T09:38:19 | 28,994,898 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
*
* The classes in this package represent PetClinic's business layer.
*
*/
package com.szo.app.model;
|
UTF-8
|
Java
| 112 |
java
|
package-info.java
|
Java
|
[] | null |
[] |
/**
*
* The classes in this package represent PetClinic's business layer.
*
*/
package com.szo.app.model;
| 112 | 0.678571 | 0.678571 | 6 | 17.333334 | 24.232668 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false |
0
|
8541829023471aaaa7caa28197f0ee3fad8582ee
| 30,631,706,771,536 |
aa66fd183298b06fcff37fed8cfa11d454505e1a
|
/app/src/main/java/com/travel/money/splitter/utils/ImageUtils.java
|
b585f384a2da41681a91ab63b3ba5a72abdb8a16
|
[] |
no_license
|
vlebedynskyi/TME
|
https://github.com/vlebedynskyi/TME
|
eef81566982571a7dc9e320566bed955801e0d5c
|
a14b31783d87776bfd60aa98677b04815435d4b2
|
refs/heads/master
| 2016-03-31T16:57:37.675000 | 2014-08-07T13:40:40 | 2014-08-07T13:40:40 | 20,535,322 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.travel.money.splitter.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.travel.money.splitter.R;
import java.io.InputStream;
/**
* Created by vetalll on 6/10/14.
*/
public class ImageUtils {
public static class PreparedOptions {
public static final DisplayImageOptions contactImageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(false)
.showImageForEmptyUri(R.drawable.ic_contact_picture)
.showImageOnFail(R.drawable.ic_contact_picture)
.showImageOnLoading(R.drawable.ic_contact_picture)
.delayBeforeLoading(100)
.displayer(new FadeInBitmapDisplayer(350))
.build();
public static final DisplayImageOptions categoryImageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(false)
.cacheOnDisk(false)
.showImageForEmptyUri(R.drawable.other)
.showImageOnFail(R.drawable.other)
.build();
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
public static Bitmap getBitmapFromUri(Uri uri, Context c, int width, int height) {
try {
InputStream s = c.getContentResolver().openInputStream(uri);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(s, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
s = c.getContentResolver().openInputStream(uri);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(s, null, options);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
UTF-8
|
Java
| 3,829 |
java
|
ImageUtils.java
|
Java
|
[
{
"context": "R;\n\nimport java.io.InputStream;\n\n/**\n * Created by vetalll on 6/10/14.\n */\npublic class ImageUtils {\n pub",
"end": 405,
"score": 0.9996463656425476,
"start": 398,
"tag": "USERNAME",
"value": "vetalll"
}
] | null |
[] |
package com.travel.money.splitter.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.travel.money.splitter.R;
import java.io.InputStream;
/**
* Created by vetalll on 6/10/14.
*/
public class ImageUtils {
public static class PreparedOptions {
public static final DisplayImageOptions contactImageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(false)
.showImageForEmptyUri(R.drawable.ic_contact_picture)
.showImageOnFail(R.drawable.ic_contact_picture)
.showImageOnLoading(R.drawable.ic_contact_picture)
.delayBeforeLoading(100)
.displayer(new FadeInBitmapDisplayer(350))
.build();
public static final DisplayImageOptions categoryImageOptions = new DisplayImageOptions.Builder()
.cacheInMemory(false)
.cacheOnDisk(false)
.showImageForEmptyUri(R.drawable.other)
.showImageOnFail(R.drawable.other)
.build();
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
public static Bitmap getBitmapFromUri(Uri uri, Context c, int width, int height) {
try {
InputStream s = c.getContentResolver().openInputStream(uri);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(s, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
s = c.getContentResolver().openInputStream(uri);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(s, null, options);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| 3,829 | 0.649517 | 0.644816 | 89 | 42.022472 | 31.252497 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52809 | false | false |
0
|
4527056ea61073ea6b2ce6991db5f73c2996180a
| 1,503,238,578,634 |
a0d1480e101654dfea5ddfa628eb37da35f0a65e
|
/FeedBackManagementSystem/src/com/cg/fbms/dao/FacultyMaintenanceDAOImpl.java
|
71549c2555c0e60fe11917d7b229e97644363c76
|
[] |
no_license
|
rajesh226-gif/feedbackManagementSystem
|
https://github.com/rajesh226-gif/feedbackManagementSystem
|
999a5778c01e6b8e4c5778fb29aeb357f465dae2
|
d550655eb974b93f1b3c1a41897a1e7fe3c7acb1
|
refs/heads/master
| 2022-12-28T17:50:47.457000 | 2020-10-12T10:13:52 | 2020-10-12T10:13:52 | 303,332,894 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cg.fbms.dao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import com.cg.fbms.dto.CourseFacultyMapping;
import com.cg.fbms.dto.CourseMaster;
import com.cg.fbms.dto.Faculty;
import com.cg.fbms.utility.JPAUtility;
public class FacultyMaintenanceDAOImpl implements IFacultyMaintenanceDAO, QueryConstants {
EntityManagerFactory factory = null;
EntityManager manager = null;
EntityTransaction transaction = null;
private ArrayList<Faculty> facultyList = null;
@Override
public boolean addFacultySkillSet(Faculty facultySkill) {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
transaction = manager.getTransaction();
boolean flag = false;
try {
transaction.begin();
manager.persist(facultySkill);
transaction.commit();
flag = true;
return flag;
} catch (PersistenceException persistExp) {
// TODO: handle exception
transaction.rollback();
System.err.println(persistExp.getMessage());
return flag;
}
finally {
manager.close();
}
}
@Override
public ArrayList<Faculty> displayAllFacultyList() {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
ArrayList<Faculty> facultyList = null;
try {
facultyList = (ArrayList<Faculty>) manager.createQuery(GET_ALL_FACULTY_LIST, Faculty.class).getResultList();
} catch (PersistenceException persistExp) {
System.err.println(persistExp.getMessage());
} finally {
manager.close();
}
return facultyList;
}
@Override
public Faculty displayFacultyById(int facultyId) {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
Faculty faculty = null;
try {
faculty = manager.find(Faculty.class, facultyId);
} catch (PersistenceException persistExp) {
System.err.println(persistExp.getMessage());
}
return faculty;
}
@Override
public ArrayList<Integer> getAllFacultyId() {
ArrayList<Integer> allFaculytId = new ArrayList<Integer>();
facultyList = new FacultyMaintenanceDAOImpl().displayAllFacultyList();
for (Faculty faculty : facultyList) {
allFaculytId.add(faculty.getFacultyId());
}
return allFaculytId;
}
@Override
public ArrayList<Faculty> getFacultyBySkill(String courseName) {
facultyList = new FacultyMaintenanceDAOImpl().displayAllFacultyList();
ArrayList<Faculty> facultyHavingParticularSkill = new ArrayList<Faculty>();
for (Faculty facultySkill : facultyList) {
List<String> skillSet = Arrays.asList(facultySkill.getFacultySkillSet().split(","));
if (skillSet.contains(courseName)) {
facultyHavingParticularSkill.add(facultySkill);
}
}
return facultyHavingParticularSkill;
}
// for mapping part of course and faculty
@Override
public boolean courseFacultyMapping(CourseFacultyMapping courseFacultyMapping) {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
transaction = manager.getTransaction();
boolean status = false;
try {
transaction.begin();
manager.persist(courseFacultyMapping);
transaction.commit();
status = true;
} catch (PersistenceException persistExp) {
System.err.println(persistExp.getMessage());
}
finally {
manager.close();
}
return status;
}
@Override
public ArrayList<Faculty> getMappedFacultyWithCourse(int courseId) {
// TODO Auto-generated method stub
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
ArrayList<Faculty> allFacultyId = null;
try {
Query query = manager.createQuery(GET_ALL_FACULTY_ID_BY_COURSENAME);
query.setParameter(1, courseId);
allFacultyId = (ArrayList<Faculty>) query.getResultList();
} catch (PersistenceException p) {
System.err.println(p);
} finally {
manager.close();
}
return allFacultyId;
}
@Override
public ArrayList<Faculty> getFacultyNotMappedWithCourse(CourseMaster courseMaster) {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
ArrayList<Faculty> facultyNotMappedWithCourse = new ArrayList<Faculty>();
IFacultyMaintenanceDAO facultyMaintenanceDAO = new FacultyMaintenanceDAOImpl();
ArrayList<Faculty> facultyDetailsBySkill = facultyMaintenanceDAO
.getFacultyBySkill(courseMaster.getCourseName());
ArrayList<Integer> mappedFacultyId = null;
try {
Query query = manager.createQuery(GET_ALL_FACULTY_ID_BY_COURSENAME);
query.setParameter(1, courseMaster.getCourseId());
mappedFacultyId = (ArrayList<Integer>) query.getResultList();
} catch (PersistenceException p) {
System.out.println(p);
} finally {
manager.close();
}
for (Faculty allFaultyWithCourse : facultyDetailsBySkill) {
if (!mappedFacultyId.contains(allFaultyWithCourse.getFacultyId())) {
facultyNotMappedWithCourse.add(allFaultyWithCourse);
}
}
return facultyNotMappedWithCourse;
}
}
|
UTF-8
|
Java
| 5,117 |
java
|
FacultyMaintenanceDAOImpl.java
|
Java
|
[] | null |
[] |
package com.cg.fbms.dao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import com.cg.fbms.dto.CourseFacultyMapping;
import com.cg.fbms.dto.CourseMaster;
import com.cg.fbms.dto.Faculty;
import com.cg.fbms.utility.JPAUtility;
public class FacultyMaintenanceDAOImpl implements IFacultyMaintenanceDAO, QueryConstants {
EntityManagerFactory factory = null;
EntityManager manager = null;
EntityTransaction transaction = null;
private ArrayList<Faculty> facultyList = null;
@Override
public boolean addFacultySkillSet(Faculty facultySkill) {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
transaction = manager.getTransaction();
boolean flag = false;
try {
transaction.begin();
manager.persist(facultySkill);
transaction.commit();
flag = true;
return flag;
} catch (PersistenceException persistExp) {
// TODO: handle exception
transaction.rollback();
System.err.println(persistExp.getMessage());
return flag;
}
finally {
manager.close();
}
}
@Override
public ArrayList<Faculty> displayAllFacultyList() {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
ArrayList<Faculty> facultyList = null;
try {
facultyList = (ArrayList<Faculty>) manager.createQuery(GET_ALL_FACULTY_LIST, Faculty.class).getResultList();
} catch (PersistenceException persistExp) {
System.err.println(persistExp.getMessage());
} finally {
manager.close();
}
return facultyList;
}
@Override
public Faculty displayFacultyById(int facultyId) {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
Faculty faculty = null;
try {
faculty = manager.find(Faculty.class, facultyId);
} catch (PersistenceException persistExp) {
System.err.println(persistExp.getMessage());
}
return faculty;
}
@Override
public ArrayList<Integer> getAllFacultyId() {
ArrayList<Integer> allFaculytId = new ArrayList<Integer>();
facultyList = new FacultyMaintenanceDAOImpl().displayAllFacultyList();
for (Faculty faculty : facultyList) {
allFaculytId.add(faculty.getFacultyId());
}
return allFaculytId;
}
@Override
public ArrayList<Faculty> getFacultyBySkill(String courseName) {
facultyList = new FacultyMaintenanceDAOImpl().displayAllFacultyList();
ArrayList<Faculty> facultyHavingParticularSkill = new ArrayList<Faculty>();
for (Faculty facultySkill : facultyList) {
List<String> skillSet = Arrays.asList(facultySkill.getFacultySkillSet().split(","));
if (skillSet.contains(courseName)) {
facultyHavingParticularSkill.add(facultySkill);
}
}
return facultyHavingParticularSkill;
}
// for mapping part of course and faculty
@Override
public boolean courseFacultyMapping(CourseFacultyMapping courseFacultyMapping) {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
transaction = manager.getTransaction();
boolean status = false;
try {
transaction.begin();
manager.persist(courseFacultyMapping);
transaction.commit();
status = true;
} catch (PersistenceException persistExp) {
System.err.println(persistExp.getMessage());
}
finally {
manager.close();
}
return status;
}
@Override
public ArrayList<Faculty> getMappedFacultyWithCourse(int courseId) {
// TODO Auto-generated method stub
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
ArrayList<Faculty> allFacultyId = null;
try {
Query query = manager.createQuery(GET_ALL_FACULTY_ID_BY_COURSENAME);
query.setParameter(1, courseId);
allFacultyId = (ArrayList<Faculty>) query.getResultList();
} catch (PersistenceException p) {
System.err.println(p);
} finally {
manager.close();
}
return allFacultyId;
}
@Override
public ArrayList<Faculty> getFacultyNotMappedWithCourse(CourseMaster courseMaster) {
factory = JPAUtility.getFactory();
manager = factory.createEntityManager();
ArrayList<Faculty> facultyNotMappedWithCourse = new ArrayList<Faculty>();
IFacultyMaintenanceDAO facultyMaintenanceDAO = new FacultyMaintenanceDAOImpl();
ArrayList<Faculty> facultyDetailsBySkill = facultyMaintenanceDAO
.getFacultyBySkill(courseMaster.getCourseName());
ArrayList<Integer> mappedFacultyId = null;
try {
Query query = manager.createQuery(GET_ALL_FACULTY_ID_BY_COURSENAME);
query.setParameter(1, courseMaster.getCourseId());
mappedFacultyId = (ArrayList<Integer>) query.getResultList();
} catch (PersistenceException p) {
System.out.println(p);
} finally {
manager.close();
}
for (Faculty allFaultyWithCourse : facultyDetailsBySkill) {
if (!mappedFacultyId.contains(allFaultyWithCourse.getFacultyId())) {
facultyNotMappedWithCourse.add(allFaultyWithCourse);
}
}
return facultyNotMappedWithCourse;
}
}
| 5,117 | 0.750635 | 0.750244 | 196 | 25.107143 | 24.268139 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.923469 | false | false |
0
|
de16d14111b614310e43544c90d156534669c4fc
| 20,529,943,697,632 |
484c2b3ab42ccfcddee179748ec66e2f175d890d
|
/CoreJava/src/c73/Example3.java
|
b1286424160c8214624d19b88e11f4da367e408e
|
[] |
no_license
|
praneethve/CoreJava
|
https://github.com/praneethve/CoreJava
|
df01b677129740ddad950ba9806c9fe2b0ca9732
|
4e506c975fffc1591ee41b127a3f7d86b8c305c2
|
refs/heads/master
| 2023-03-08T21:38:00.585000 | 2021-02-25T03:56:13 | 2021-02-25T03:56:13 | 333,289,934 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package c73;
import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
class Student2{
int id;
String name;
int age;
public Student2(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
public class Example3 {
public static void main(String[] args) {
List<Student> studentlist = new ArrayList<Student>();
studentlist.add(new Student(11,"Praneeth",22));
studentlist.add(new Student(22,"Alpati",18));
studentlist.add(new Student(33,"Vishnu",22));
studentlist.add(new Student(44,"Krishna",23));
studentlist.add(new Student(55,"Yeswanth",18));
Double avgAge = studentlist.stream()
.collect(Collectors.averagingInt(s->s.age));
System.out.println("Average Age of Students is: "+avgAge);
}
}
|
UTF-8
|
Java
| 948 |
java
|
Example3.java
|
Java
|
[
{
"context": "nt>(); \r\n studentlist.add(new Student(11,\"Praneeth\",22)); \r\n studentlist.add(new Studen",
"end": 504,
"score": 0.9997385144233704,
"start": 496,
"tag": "NAME",
"value": "Praneeth"
},
{
"context": "; \r\n studentlist.add(new Student(22,\"Alpati\",18)); \r\n studentlist.add(new Studen",
"end": 566,
"score": 0.9997332692146301,
"start": 560,
"tag": "NAME",
"value": "Alpati"
},
{
"context": "; \r\n studentlist.add(new Student(33,\"Vishnu\",22)); \r\n studentlist.add(new Studen",
"end": 628,
"score": 0.9996991157531738,
"start": 622,
"tag": "NAME",
"value": "Vishnu"
},
{
"context": "; \r\n studentlist.add(new Student(44,\"Krishna\",23)); \r\n studentlist.add(new Studen",
"end": 691,
"score": 0.9997155070304871,
"start": 684,
"tag": "NAME",
"value": "Krishna"
},
{
"context": "; \r\n studentlist.add(new Student(55,\"Yeswanth\",18)); \r\n Double avgAge = studentlist.strea",
"end": 755,
"score": 0.9997449517250061,
"start": 747,
"tag": "NAME",
"value": "Yeswanth"
}
] | null |
[] |
package c73;
import java.util.stream.Collectors;
import java.util.List;
import java.util.ArrayList;
class Student2{
int id;
String name;
int age;
public Student2(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
public class Example3 {
public static void main(String[] args) {
List<Student> studentlist = new ArrayList<Student>();
studentlist.add(new Student(11,"Praneeth",22));
studentlist.add(new Student(22,"Alpati",18));
studentlist.add(new Student(33,"Vishnu",22));
studentlist.add(new Student(44,"Krishna",23));
studentlist.add(new Student(55,"Yeswanth",18));
Double avgAge = studentlist.stream()
.collect(Collectors.averagingInt(s->s.age));
System.out.println("Average Age of Students is: "+avgAge);
}
}
| 948 | 0.582278 | 0.555907 | 28 | 31.857143 | 21.867645 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.071429 | false | false |
0
|
0fd99c0b1d9a2ecb29e64185362fa37efcb76ed0
| 7,000,796,711,741 |
32de861bc2cccaf59b84c18f77a40b80743af084
|
/artifact/release/JPonyo/trunk/common/src/main/java/net/sf/ponyo/jponyo/common/async/Closeable.java
|
3b181e2b6713c6f31190fa1ed3301a2ac5923f22
|
[] |
no_license
|
christophpickl/ponyo-svn
|
https://github.com/christophpickl/ponyo-svn
|
f2419d9e880c3dc0da2f8863fb5766a94b60ac4a
|
99971a27e7f9ee803ac70e5aabbaccaa3a82c1ed
|
refs/heads/master
| 2021-03-08T19:28:49.379000 | 2012-09-14T20:50:57 | 2012-09-14T20:50:57 | 56,807,836 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.sf.ponyo.jponyo.common.async;
/**
* Compared to <code>java.io.Closeable</code> this interface does not declare a checked exception to be thrown.
*
* Onca a <code>Closeable</code> has been closed, any further method calls will respond with an
* <code>IllegalStateException</code>.
*
* @since 0.1
*/
public interface Closeable {
/**
* It is most likely you will get an <code>IllegalStateException</code> if called more than once.
*
* @since 0.1
*/
void close();
}
|
UTF-8
|
Java
| 499 |
java
|
Closeable.java
|
Java
|
[] | null |
[] |
package net.sf.ponyo.jponyo.common.async;
/**
* Compared to <code>java.io.Closeable</code> this interface does not declare a checked exception to be thrown.
*
* Onca a <code>Closeable</code> has been closed, any further method calls will respond with an
* <code>IllegalStateException</code>.
*
* @since 0.1
*/
public interface Closeable {
/**
* It is most likely you will get an <code>IllegalStateException</code> if called more than once.
*
* @since 0.1
*/
void close();
}
| 499 | 0.691383 | 0.683367 | 20 | 23.950001 | 34.802982 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
0
|
af0484451b131f597c59edacc8a24ef50569097f
| 33,311,766,374,519 |
046370e11a390c98dfd85202acb22295da927900
|
/src/main/java/com/shildon/treehole/controller/FileUploadController.java
|
0402253fa94a6495eecc60fc163e911adc4be941
|
[] |
no_license
|
shildondu/treehole
|
https://github.com/shildondu/treehole
|
87a417ea4468fe4597258573ee6958260bfd90aa
|
1f898c8601f643feb8fc8d8ca94f87504a4efb86
|
refs/heads/master
| 2021-01-22T14:11:25.086000 | 2016-10-07T14:45:19 | 2016-10-07T14:45:19 | 57,668,254 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.shildon.treehole.controller;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import com.shildon.treehole.model.User;
import com.shildon.treehole.service.UserService;
import com.shildon.treehole.support.Callback;
import com.shildon.treehole.support.ResultMap;
/**
*
* @author shildon<shildondu@gmail.com>
* @date May 4, 2016
*/
@Controller
@ControllerAdvice
public class FileUploadController extends BaseController {
@Resource
private ServletContext servletContext;
@Resource
private UserService userService;
@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
@ResponseBody
public ResultMap<User> handleFormUpload(final String id, final String name,
final MultipartFile file, final HttpSession httpSession) {
return execute(new Callback<User>() {
@Override
public boolean callback(ResultMap<User> resultMap) {
User user = userService.get(id);
String rootPath = servletContext.getRealPath("/avatar");
String fullPath = rootPath + "/" + name;
String relativePath = "avatar/" + name;
File localFile = new File(fullPath);
try (RandomAccessFile randomAccessFile = new RandomAccessFile(localFile, "rw")) {
byte[] fileData = file.getBytes();
randomAccessFile.write(fileData);
user.setAvatarPath(relativePath);
if (userService.update(user)) {
httpSession.setAttribute("user", user);
resultMap.addResult(user);
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
});
}
@ExceptionHandler(MaxUploadSizeExceededException.class)
@ResponseBody
public ResultMap<String> handleUploadException(final MaxUploadSizeExceededException e) {
return execute(new Callback<String>() {
@Override
public boolean callback(ResultMap<String> resultMap) {
resultMap.addResult("文件大小超出!");
return false;
}
});
}
}
|
UTF-8
|
Java
| 2,585 |
java
|
FileUploadController.java
|
Java
|
[
{
"context": "ehole.support.ResultMap;\n\n/**\n * \n * @author shildon<shildondu@gmail.com>\n * @date May 4, 2016\n */\n@Co",
"end": 941,
"score": 0.4488978683948517,
"start": 939,
"tag": "USERNAME",
"value": "on"
},
{
"context": "le.support.ResultMap;\n\n/**\n * \n * @author shildon<shildondu@gmail.com>\n * @date May 4, 2016\n */\n@Controller\n@Controller",
"end": 961,
"score": 0.9999288320541382,
"start": 942,
"tag": "EMAIL",
"value": "shildondu@gmail.com"
}
] | null |
[] |
package com.shildon.treehole.controller;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import com.shildon.treehole.model.User;
import com.shildon.treehole.service.UserService;
import com.shildon.treehole.support.Callback;
import com.shildon.treehole.support.ResultMap;
/**
*
* @author shildon<<EMAIL>>
* @date May 4, 2016
*/
@Controller
@ControllerAdvice
public class FileUploadController extends BaseController {
@Resource
private ServletContext servletContext;
@Resource
private UserService userService;
@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
@ResponseBody
public ResultMap<User> handleFormUpload(final String id, final String name,
final MultipartFile file, final HttpSession httpSession) {
return execute(new Callback<User>() {
@Override
public boolean callback(ResultMap<User> resultMap) {
User user = userService.get(id);
String rootPath = servletContext.getRealPath("/avatar");
String fullPath = rootPath + "/" + name;
String relativePath = "avatar/" + name;
File localFile = new File(fullPath);
try (RandomAccessFile randomAccessFile = new RandomAccessFile(localFile, "rw")) {
byte[] fileData = file.getBytes();
randomAccessFile.write(fileData);
user.setAvatarPath(relativePath);
if (userService.update(user)) {
httpSession.setAttribute("user", user);
resultMap.addResult(user);
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
});
}
@ExceptionHandler(MaxUploadSizeExceededException.class)
@ResponseBody
public ResultMap<String> handleUploadException(final MaxUploadSizeExceededException e) {
return execute(new Callback<String>() {
@Override
public boolean callback(ResultMap<String> resultMap) {
resultMap.addResult("文件大小超出!");
return false;
}
});
}
}
| 2,573 | 0.753984 | 0.75204 | 85 | 29.270588 | 23.5259 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.411765 | false | false |
0
|
0fb9116dbd75b8eae04a0a09d08fe716f81ccc09
| 11,562,051,980,113 |
41383bfbe38eef928c1cd1cebc2232eb49be85f9
|
/midp/src/i18n/i18n_main/reference/classes/com/sun/midp/l10n/LocalizedStringszhCN.java
|
2a338c206d2571e77f12aab413b72784a1e91cfb
|
[] |
no_license
|
ruitaomu/pspkvm
|
https://github.com/ruitaomu/pspkvm
|
d208d608f667fd64238b00f25b403177e14c739a
|
9f68194f987ff038d35409f4d386598025600ef0
|
refs/heads/master
| 2021-03-27T11:49:53.137000 | 2011-09-03T16:48:34 | 2011-09-03T16:48:34 | 60,471,263 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sun.midp.l10n;
import com.sun.midp.i18n.ResourceBundle;
import com.sun.midp.i18n.ResourceConstants;
/**
* The zh-CN localization of ResourceBundle
*
* LocalizedStringsBasezhCN.java is generated from
* src/configuration/configurator/share/l10n/zh-CN.xml
*/
public class LocalizedStringszhCN extends LocalizedStringsBasezhCN
implements ResourceBundle {
public String getString(int index) {
return getContent(index);
}
public String getLocalizedDateString(String dayOfWeek,
String date,
String month,
String year) {
return dayOfWeek + ", " + year + " " + month + " " + date;
}
public String getLocalizedTimeString(String hour, String min,
String sec, String ampm) {
if((ampm != null) && (ampm.equals("PM"))) {
int h24 = Integer.parseInt(hour);
h24 += 12;
return(h24 + ":" + min + ":" + sec);
} else {
return(hour + ":" + min + ":" + sec);
}
}
public String getLocalizedDateTimeString(String dayOfWeek, String date,
String month, String year,
String hour, String min,
String sec, String ampm) {
return getLocalizedDateString(dayOfWeek,
date,
month,
year) + " " +
getLocalizedTimeString(hour,
min,
sec,
ampm);
}
public int getLocalizedFirstDayOfWeek() {
return java.util.Calendar.SUNDAY;
}
public boolean isLocalizedAMPMafterTime() {
return false;
}
}
|
UTF-8
|
Java
| 1,991 |
java
|
LocalizedStringszhCN.java
|
Java
|
[] | null |
[] |
package com.sun.midp.l10n;
import com.sun.midp.i18n.ResourceBundle;
import com.sun.midp.i18n.ResourceConstants;
/**
* The zh-CN localization of ResourceBundle
*
* LocalizedStringsBasezhCN.java is generated from
* src/configuration/configurator/share/l10n/zh-CN.xml
*/
public class LocalizedStringszhCN extends LocalizedStringsBasezhCN
implements ResourceBundle {
public String getString(int index) {
return getContent(index);
}
public String getLocalizedDateString(String dayOfWeek,
String date,
String month,
String year) {
return dayOfWeek + ", " + year + " " + month + " " + date;
}
public String getLocalizedTimeString(String hour, String min,
String sec, String ampm) {
if((ampm != null) && (ampm.equals("PM"))) {
int h24 = Integer.parseInt(hour);
h24 += 12;
return(h24 + ":" + min + ":" + sec);
} else {
return(hour + ":" + min + ":" + sec);
}
}
public String getLocalizedDateTimeString(String dayOfWeek, String date,
String month, String year,
String hour, String min,
String sec, String ampm) {
return getLocalizedDateString(dayOfWeek,
date,
month,
year) + " " +
getLocalizedTimeString(hour,
min,
sec,
ampm);
}
public int getLocalizedFirstDayOfWeek() {
return java.util.Calendar.SUNDAY;
}
public boolean isLocalizedAMPMafterTime() {
return false;
}
}
| 1,991 | 0.470116 | 0.462079 | 57 | 32.894737 | 23.873707 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561404 | false | false |
0
|
e1a30e323fe19be8629aff69f1a9405f29c6c6c0
| 2,671,469,690,821 |
06b12238587f13a03825aed407f3a13bc16db92b
|
/src/main/java/com/mindtree/shoppingcart/repository/ProductRepository.java
|
f0c40cce9c6092852196b115a3aba76c39638ad4
|
[] |
no_license
|
deepakjena-design/SpringBoot
|
https://github.com/deepakjena-design/SpringBoot
|
e8ffe2c496cc85fbb1a2d36ceb396ce99bb3ab98
|
f17f874d647474a67832ba5cc727ec3f2d9fcb9e
|
refs/heads/master
| 2022-11-15T15:55:26.666000 | 2020-06-26T16:01:01 | 2020-06-26T16:01:01 | 275,193,758 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mindtree.shoppingcart.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mindtree.shoppingcart.entity.Product;
public interface ProductRepository extends JpaRepository<Product, Integer>{
public Optional<Product> findByProductName(String name);
public List<Product> findByCategory(String category);
}
|
UTF-8
|
Java
| 413 |
java
|
ProductRepository.java
|
Java
|
[] | null |
[] |
package com.mindtree.shoppingcart.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mindtree.shoppingcart.entity.Product;
public interface ProductRepository extends JpaRepository<Product, Integer>{
public Optional<Product> findByProductName(String name);
public List<Product> findByCategory(String category);
}
| 413 | 0.811138 | 0.811138 | 19 | 20.736841 | 25.991581 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789474 | false | false |
0
|
33725d8e44908dc2c20048d960c01df1c8be80ac
| 16,234,976,403,378 |
f3fac6ceb914a8848176ae60ec2ceec79e2c32c2
|
/src/main/java/com/fama/agenda/converter/AdesaoConverter.java
|
1b574f6c2a95439db824c065c94f1eaa6fdec702
|
[] |
no_license
|
eltonjhony/Agenda
|
https://github.com/eltonjhony/Agenda
|
4a6322806ae48b359f274ee80a5abf2f051858c0
|
6d99530fcd232dd960d7f4820f7ee3f89400d2fc
|
refs/heads/master
| 2020-05-15T12:40:35.098000 | 2015-12-12T20:42:18 | 2015-12-12T20:42:18 | 182,273,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fama.agenda.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.fama.agenda.model.Adesao;
import com.fama.agenda.repository.Termos;
import com.fama.agenda.util.cdi.CDIServiceLocator;
/**
* @author Elton Jhony R. Oliveira
*/
@FacesConverter(forClass = Adesao.class)
public class AdesaoConverter implements Converter {
private Termos oficios;
public AdesaoConverter() {
oficios = CDIServiceLocator.getBean(Termos.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
Adesao retorno = null;
if (value != null) {
Long id = new Long(value);
retorno = oficios.porId(id);
}
return retorno;
}
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
Adesao oficio = (Adesao) value;
if (value != null) {
return (oficio.getId() == null ? null : oficio.getId().toString());
}
return "";
}
}
|
UTF-8
|
Java
| 1,076 |
java
|
AdesaoConverter.java
|
Java
|
[
{
"context": "agenda.util.cdi.CDIServiceLocator;\n\n/**\n * @author Elton Jhony R. Oliveira\n */\n\n@FacesConverter(forClass = Adesao.class)\npub",
"end": 370,
"score": 0.9998503923416138,
"start": 347,
"tag": "NAME",
"value": "Elton Jhony R. Oliveira"
}
] | null |
[] |
package com.fama.agenda.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.fama.agenda.model.Adesao;
import com.fama.agenda.repository.Termos;
import com.fama.agenda.util.cdi.CDIServiceLocator;
/**
* @author <NAME>
*/
@FacesConverter(forClass = Adesao.class)
public class AdesaoConverter implements Converter {
private Termos oficios;
public AdesaoConverter() {
oficios = CDIServiceLocator.getBean(Termos.class);
}
@Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
Adesao retorno = null;
if (value != null) {
Long id = new Long(value);
retorno = oficios.porId(id);
}
return retorno;
}
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
Adesao oficio = (Adesao) value;
if (value != null) {
return (oficio.getId() == null ? null : oficio.getId().toString());
}
return "";
}
}
| 1,059 | 0.733271 | 0.733271 | 50 | 20.52 | 21.026878 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.26 | false | false |
0
|
f253adaa3c2d828ec26043a6bc85f1bdfeed3a70
| 14,989,435,891,199 |
fbd1421fc1851140c5d90cbbc13bbbe781c0492f
|
/src/main/java/com/example/controller/TicketController.java
|
b9cd9d4bcb67e6ae385a9afc2bd6fe8277fd60fa
|
[] |
no_license
|
Shivamrai007/raildemo
|
https://github.com/Shivamrai007/raildemo
|
82ce2c8b83382c8fe33c88099756f4f590cf91c3
|
e8f714cef4c78d428a0d50519fd4d8ee9e08639f
|
refs/heads/main
| 2023-04-30T21:28:25.458000 | 2021-05-15T07:38:21 | 2021-05-15T07:38:21 | 367,569,363 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.controller;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.dto.TicketDTO;
import com.example.exception.TrainNotFoundException;
import com.example.exception.UserNotFoundException;
import com.example.exception.handling.Message;
import com.example.model.Tickets;
import com.example.service.TicketService;
/**
* @author shivam.rai
*
*/
@RestController
@RequestMapping("/ticket")
public class TicketController {
@Autowired
TicketService ticketService;
private Logger logger = LoggerFactory.getLogger(TicketController.class);
/**
* @param ticketDTO
* @return
* @throws MethodArgumentNotValidException
* @throws UserNotFoundException
* @throws TrainNotFoundException
*/
@PostMapping("")
public ResponseEntity<?> saveTicket(@RequestBody @Valid TicketDTO ticketDTO)
throws MethodArgumentNotValidException, UserNotFoundException, TrainNotFoundException {
logger.info("Train Saved Process Initiated...");
TicketDTO ticketDTO2 = ticketService.saveTicket(ticketDTO);
return new ResponseEntity<TicketDTO>(ticketDTO2, HttpStatus.CREATED);
}
/**
* @param userId
* @return
* @throws Exception
*/
@GetMapping("/{userId}")
public List<TicketDTO> getTicketByUserId(@PathVariable Long userId) throws Exception {
return ticketService.getTicketByUserId(String.valueOf(userId));
}
/**
* @param ticketId
*/
@DeleteMapping("/{ticketId}")
public void deleteTicketById(@PathVariable Long ticketId) {
logger.info("Deleting ticket Initiated...");
ticketService.deleteTicketById(ticketId);
}
}
|
UTF-8
|
Java
| 2,422 |
java
|
TicketController.java
|
Java
|
[
{
"context": ".example.service.TicketService;\r\n\r\n/**\r\n * @author shivam.rai\r\n *\r\n */\r\n@RestController\r\n@RequestMapping(\"/ticket",
"end": 1175,
"score": 0.9377132058143616,
"start": 1165,
"tag": "NAME",
"value": "shivam.rai"
}
] | null |
[] |
package com.example.controller;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.dto.TicketDTO;
import com.example.exception.TrainNotFoundException;
import com.example.exception.UserNotFoundException;
import com.example.exception.handling.Message;
import com.example.model.Tickets;
import com.example.service.TicketService;
/**
* @author shivam.rai
*
*/
@RestController
@RequestMapping("/ticket")
public class TicketController {
@Autowired
TicketService ticketService;
private Logger logger = LoggerFactory.getLogger(TicketController.class);
/**
* @param ticketDTO
* @return
* @throws MethodArgumentNotValidException
* @throws UserNotFoundException
* @throws TrainNotFoundException
*/
@PostMapping("")
public ResponseEntity<?> saveTicket(@RequestBody @Valid TicketDTO ticketDTO)
throws MethodArgumentNotValidException, UserNotFoundException, TrainNotFoundException {
logger.info("Train Saved Process Initiated...");
TicketDTO ticketDTO2 = ticketService.saveTicket(ticketDTO);
return new ResponseEntity<TicketDTO>(ticketDTO2, HttpStatus.CREATED);
}
/**
* @param userId
* @return
* @throws Exception
*/
@GetMapping("/{userId}")
public List<TicketDTO> getTicketByUserId(@PathVariable Long userId) throws Exception {
return ticketService.getTicketByUserId(String.valueOf(userId));
}
/**
* @param ticketId
*/
@DeleteMapping("/{ticketId}")
public void deleteTicketById(@PathVariable Long ticketId) {
logger.info("Deleting ticket Initiated...");
ticketService.deleteTicketById(ticketId);
}
}
| 2,422 | 0.775805 | 0.774154 | 76 | 29.868422 | 25.547346 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.013158 | false | false |
0
|
55a8fa2dd8d35c166912fb24264b942af3e3ccf2
| 18,021,682,799,101 |
59e6813a71c3e63a4982384fb62837d4f5f5fad1
|
/src/main/java/com/example/demo/util/JDKProxyFactory.java
|
48d6abe87b1f88dee887e19cba0b28e3d26ced45
|
[] |
no_license
|
afterchj/spring-boot
|
https://github.com/afterchj/spring-boot
|
157327e1e46ec72c9a3348ea169ab60fdd2a3c60
|
df9cc14846d8eb9f8a04f362920f7289ddecb092
|
refs/heads/master
| 2023-04-01T14:50:20.195000 | 2023-04-01T04:24:42 | 2023-04-01T04:24:42 | 138,696,108 | 0 | 1 | null | false | 2020-06-28T03:43:26 | 2018-06-26T06:46:57 | 2020-06-28T03:26:23 | 2020-06-28T03:43:01 | 3,690 | 0 | 0 | 0 |
Java
| false | false |
package com.example.demo.util;
import java.lang.reflect.Proxy;
/**
* Created by after on 2020/2/17.
*/
public class JDKProxyFactory {
public static Object getProxy(Object target){
Object proxy= Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new MyInvocationHandle(target));
return proxy;
}
}
|
UTF-8
|
Java
| 366 |
java
|
JDKProxyFactory.java
|
Java
|
[] | null |
[] |
package com.example.demo.util;
import java.lang.reflect.Proxy;
/**
* Created by after on 2020/2/17.
*/
public class JDKProxyFactory {
public static Object getProxy(Object target){
Object proxy= Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new MyInvocationHandle(target));
return proxy;
}
}
| 366 | 0.718579 | 0.699454 | 14 | 25.142857 | 37.034458 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
0
|
9dc45c9e07a80d95321917d16bd4c35cb745e17d
| 36,344,013,295,340 |
036a39557bd4bc46442902adc2c96314b2b2bb99
|
/src/main/java/nl/hhs/databazen/model/Employee.java
|
b6c19ab06093235def089bad3d5025ba3933de85
|
[] |
no_license
|
Sarkoutmahmoud/db
|
https://github.com/Sarkoutmahmoud/db
|
be930340b344f8e5aa113a522048a8d3c92b453d
|
87a17e32e35212501634738ef8dd97f65acbf07e
|
refs/heads/master
| 2020-05-04T03:12:02.434000 | 2019-04-02T14:48:30 | 2019-04-02T14:48:30 | 178,942,231 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package nl.hhs.databazen.model;
public class Employee {
private int employeeId;
private String firstName;
private String lastName;
private String position;
private String phoneNumber;
private String extension;
private String fax;
private String email;
private String startDate;
private String departementId;
private String managerId;
private String street;
private String city;
private String state;
private String zipCode;
private String status;
private String ssNumber;
private String salary;
private String terminationDate;
private String birthDate;
private String beneHealthIns;
private String beneLifeIns;
private String beneDayCare;
private String sex;
private String resume;
private String jobNumber;
Employee(int employeeId,
String firstName,
String lastName,
String position,
String phoneNumber,
String extension,
String fax,
String email,
String startDate,
String departementId,
String managerId,
String street,
String city,
String state,
String zipCode,
String status,
String ssNumber,
String salary,
String terminationDate,
String birthDate,
String beneHealthIns,
String beneLifeIns,
String beneDayCare,
String sex,
String resume,
String jobNumber) {
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
this.phoneNumber = phoneNumber;
this.extension = extension;
this.fax = fax;
this.email = email;
this.startDate = startDate;
this.departementId = departementId;
this.managerId = managerId;
this.street = street;
this.city = city;
this.state = state;
this.zipCode = zipCode;
this.status = status;
this.ssNumber = ssNumber;
this.salary = salary;
this.terminationDate = terminationDate;
this.birthDate = birthDate;
this.beneHealthIns = beneHealthIns;
this.beneLifeIns = beneLifeIns;
this.beneDayCare = beneDayCare;
this.sex = sex;
this.resume = resume;
this.jobNumber = jobNumber;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getDepartementId() {
return departementId;
}
public void setDepartementId(String departementId) {
this.departementId = departementId;
}
public String getManagerId() {
return managerId;
}
public void setManagerId(String managerId) {
this.managerId = managerId;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSsNumber() {
return ssNumber;
}
public void setSsNumber(String ssNumber) {
this.ssNumber = ssNumber;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getTerminationDate() {
return terminationDate;
}
public void setTerminationDate(String terminationDate) {
this.terminationDate = terminationDate;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getBeneHealthIns() {
return beneHealthIns;
}
public void setBeneHealthIns(String beneHealthIns) {
this.beneHealthIns = beneHealthIns;
}
public String getBeneLifeIns() {
return beneLifeIns;
}
public void setBeneLifeIns(String beneLifeIns) {
this.beneLifeIns = beneLifeIns;
}
public String getBeneDayCare() {
return beneDayCare;
}
public void setBeneDayCare(String beneDayCare) {
this.beneDayCare = beneDayCare;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getResume() {
return resume;
}
public void setResume(String resume) {
this.resume = resume;
}
public String getJobNumber() {
return jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
@Override
public String toString() {
String result = "\n";
if(employeeId != 0) result += "Employee id: " + employeeId + "\n";
if(firstName != null) result += "First Name: " + firstName + "\n";
if(lastName != null) result += "Last Name: " + lastName + "\n";
if(position != null) result += "Position: " + position + "\n";
if(phoneNumber != null) result += "Phone number: " + phoneNumber + "\n";
if(extension != null) result += "Extension: " + extension + "\n";
if(fax != null) result += "Fax: " + fax + "\n";
if(email != null) result += "Email: " + email + "\n";
if(startDate != null) result += "Start date: " + startDate + "\n";
if(departementId != null) result += "Departement id: " + departementId + "\n";
if(managerId != null) result += "Manager id: " + managerId + "\n";
if(street != null) result += "Street: " + street + "\n";
if(city != null) result +="City: " + city + "\n";
if(state != null) result += "State: " + state + "\n";
if(zipCode != null) result += "Zip code: " + zipCode + "\n";
if(status != null) result += "Status: " + status + "\n";
if(ssNumber != null) result += "ss number: " + ssNumber + "\n";
if(salary != null) result += "Salary: " + salary + "\n";
if(terminationDate != null) result += "Termination date: " + terminationDate + "\n";
if(birthDate != null) result += "Birth date: " + birthDate + "\n";
if(beneHealthIns != null) result += "BeneHealthIns: " + beneHealthIns + "\n";
if(beneLifeIns != null) result += "BeneLifeIns: " + beneLifeIns + "\n";
if(beneDayCare != null) result += "BeneDayCare: " + beneDayCare + "\n";
if(sex != null) result += "Sex: " + sex + "\n";
if(resume != null) result += "Resume: " + resume + "\n";
if(jobNumber != null) result += "Job number: " + jobNumber;
return result;
}
}
|
UTF-8
|
Java
| 8,673 |
java
|
Employee.java
|
Java
|
[
{
"context": " {\n\n private int employeeId;\n private String firstName;\n private String lastName;\n private String ",
"end": 114,
"score": 0.9927451014518738,
"start": 105,
"tag": "NAME",
"value": "firstName"
},
{
"context": ";\n private String firstName;\n private String lastName;\n private String position;\n private String ",
"end": 143,
"score": 0.9956725835800171,
"start": 135,
"tag": "NAME",
"value": "lastName"
},
{
"context": "mployee(int employeeId,\n String firstName,\n String lastName,\n ",
"end": 881,
"score": 0.9969566464424133,
"start": 872,
"tag": "NAME",
"value": "firstName"
},
{
"context": " String firstName,\n String lastName,\n String position,\n ",
"end": 918,
"score": 0.9972956776618958,
"start": 910,
"tag": "NAME",
"value": "lastName"
},
{
"context": ".employeeId = employeeId;\n this.firstName = firstName;\n this.lastName = lastName;\n this.p",
"end": 1847,
"score": 0.9995967149734497,
"start": 1838,
"tag": "NAME",
"value": "firstName"
},
{
"context": "his.firstName = firstName;\n this.lastName = lastName;\n this.position = position;\n this.p",
"end": 1881,
"score": 0.9995450377464294,
"start": 1873,
"tag": "NAME",
"value": "lastName"
}
] | null |
[] |
package nl.hhs.databazen.model;
public class Employee {
private int employeeId;
private String firstName;
private String lastName;
private String position;
private String phoneNumber;
private String extension;
private String fax;
private String email;
private String startDate;
private String departementId;
private String managerId;
private String street;
private String city;
private String state;
private String zipCode;
private String status;
private String ssNumber;
private String salary;
private String terminationDate;
private String birthDate;
private String beneHealthIns;
private String beneLifeIns;
private String beneDayCare;
private String sex;
private String resume;
private String jobNumber;
Employee(int employeeId,
String firstName,
String lastName,
String position,
String phoneNumber,
String extension,
String fax,
String email,
String startDate,
String departementId,
String managerId,
String street,
String city,
String state,
String zipCode,
String status,
String ssNumber,
String salary,
String terminationDate,
String birthDate,
String beneHealthIns,
String beneLifeIns,
String beneDayCare,
String sex,
String resume,
String jobNumber) {
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
this.phoneNumber = phoneNumber;
this.extension = extension;
this.fax = fax;
this.email = email;
this.startDate = startDate;
this.departementId = departementId;
this.managerId = managerId;
this.street = street;
this.city = city;
this.state = state;
this.zipCode = zipCode;
this.status = status;
this.ssNumber = ssNumber;
this.salary = salary;
this.terminationDate = terminationDate;
this.birthDate = birthDate;
this.beneHealthIns = beneHealthIns;
this.beneLifeIns = beneLifeIns;
this.beneDayCare = beneDayCare;
this.sex = sex;
this.resume = resume;
this.jobNumber = jobNumber;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getDepartementId() {
return departementId;
}
public void setDepartementId(String departementId) {
this.departementId = departementId;
}
public String getManagerId() {
return managerId;
}
public void setManagerId(String managerId) {
this.managerId = managerId;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSsNumber() {
return ssNumber;
}
public void setSsNumber(String ssNumber) {
this.ssNumber = ssNumber;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getTerminationDate() {
return terminationDate;
}
public void setTerminationDate(String terminationDate) {
this.terminationDate = terminationDate;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getBeneHealthIns() {
return beneHealthIns;
}
public void setBeneHealthIns(String beneHealthIns) {
this.beneHealthIns = beneHealthIns;
}
public String getBeneLifeIns() {
return beneLifeIns;
}
public void setBeneLifeIns(String beneLifeIns) {
this.beneLifeIns = beneLifeIns;
}
public String getBeneDayCare() {
return beneDayCare;
}
public void setBeneDayCare(String beneDayCare) {
this.beneDayCare = beneDayCare;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getResume() {
return resume;
}
public void setResume(String resume) {
this.resume = resume;
}
public String getJobNumber() {
return jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
@Override
public String toString() {
String result = "\n";
if(employeeId != 0) result += "Employee id: " + employeeId + "\n";
if(firstName != null) result += "First Name: " + firstName + "\n";
if(lastName != null) result += "Last Name: " + lastName + "\n";
if(position != null) result += "Position: " + position + "\n";
if(phoneNumber != null) result += "Phone number: " + phoneNumber + "\n";
if(extension != null) result += "Extension: " + extension + "\n";
if(fax != null) result += "Fax: " + fax + "\n";
if(email != null) result += "Email: " + email + "\n";
if(startDate != null) result += "Start date: " + startDate + "\n";
if(departementId != null) result += "Departement id: " + departementId + "\n";
if(managerId != null) result += "Manager id: " + managerId + "\n";
if(street != null) result += "Street: " + street + "\n";
if(city != null) result +="City: " + city + "\n";
if(state != null) result += "State: " + state + "\n";
if(zipCode != null) result += "Zip code: " + zipCode + "\n";
if(status != null) result += "Status: " + status + "\n";
if(ssNumber != null) result += "ss number: " + ssNumber + "\n";
if(salary != null) result += "Salary: " + salary + "\n";
if(terminationDate != null) result += "Termination date: " + terminationDate + "\n";
if(birthDate != null) result += "Birth date: " + birthDate + "\n";
if(beneHealthIns != null) result += "BeneHealthIns: " + beneHealthIns + "\n";
if(beneLifeIns != null) result += "BeneLifeIns: " + beneLifeIns + "\n";
if(beneDayCare != null) result += "BeneDayCare: " + beneDayCare + "\n";
if(sex != null) result += "Sex: " + sex + "\n";
if(resume != null) result += "Resume: " + resume + "\n";
if(jobNumber != null) result += "Job number: " + jobNumber;
return result;
}
}
| 8,673 | 0.569468 | 0.569353 | 327 | 25.525993 | 20.632767 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48318 | false | false |
0
|
c6942e79f7571fc61b6d80a100921eee30c255af
| 39,341,900,431,668 |
95c7cba8253d5890a71bdd49628e5011c582cf66
|
/com-aopandannotation/src/main/java/com/tujia/com/aopandannotation/config/SwaggerConfiguration.java
|
d1306639b51403a9a8dfe74ff02c605b5554b92b
|
[] |
no_license
|
zhouheng001/com-java
|
https://github.com/zhouheng001/com-java
|
90fca4eb7d7a53bc252b81653f228d11e337f2bd
|
c92e0c9b15c5df3d8c6795c1df0ac0b41e39d181
|
refs/heads/master
| 2022-12-22T19:55:45.186000 | 2022-02-08T09:30:31 | 2022-02-08T09:30:31 | 162,463,259 | 0 | 1 | null | false | 2022-12-16T08:51:40 | 2018-12-19T16:26:35 | 2022-02-08T09:30:51 | 2022-12-16T08:51:38 | 10,161 | 0 | 0 | 28 |
Java
| false | false |
package com.tujia.com.aopandannotation.config;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.collect.Lists;
import com.tujia.com.aopandannotation.ComAopandannotationApplication;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.io.UnsupportedEncodingException;
import static springfox.documentation.schema.AlternateTypeRules.newRule;
/**
* @author zhouheng-os
* @Date 2019/10/15
* @Description swagger配置类
*/
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Autowired
private Environment env;
@Autowired
private TypeResolver typeResolver;
@Bean
public Docket test_api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("test_api")
.select()
.apis(RequestHandlerSelectors.basePackage("com.tujia.com.aopandannotation.controller.test"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)), typeResolver.resolve(WildcardType.class)))
// .enableUrlTemplating(true)
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
// .host("")
.apiInfo(apiInfo("test_api","文档中可以查询及测试接口调用参数和结果","4.4"));
// .securitySchemes(Lists.newArrayList(apiKey()))
// .securityContexts(Lists.newArrayList(securityContext()));
}
@Bean
public Docket h5_api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("h5-api")
.select()
.apis(RequestHandlerSelectors.basePackage("com.tujia.com.aopandannotation.controller.h5"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)), typeResolver.resolve(WildcardType.class)))
// .enableUrlTemplating(true)
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
.host("127.0.0.3")
.apiInfo(apiInfo("h5_api","文档中可以查询及测试接口调用参数和结果","4.4"));
// .securitySchemes(Lists.newArrayList(apiKey()))
// .securityContexts(Lists.newArrayList(securityContext()));
}
private ApiInfo apiInfo(String title,String description,String version){
return new ApiInfoBuilder()
.title(title)
.description(description)
.version(version)
.build();
}
}
|
UTF-8
|
Java
| 3,845 |
java
|
SwaggerConfiguration.java
|
Java
|
[
{
"context": "schema.AlternateTypeRules.newRule;\n\n/**\n * @author zhouheng-os\n * @Date 2019/10/15\n * @Description swagger配置类\n *",
"end": 1252,
"score": 0.7023846507072449,
"start": 1241,
"tag": "USERNAME",
"value": "zhouheng-os"
},
{
"context": " .forCodeGeneration(false)\n .host(\"127.0.0.3\")\n .apiInfo(apiInfo(\"h5_api\",\"文档中可",
"end": 3285,
"score": 0.9996344447135925,
"start": 3276,
"tag": "IP_ADDRESS",
"value": "127.0.0.3"
}
] | null |
[] |
package com.tujia.com.aopandannotation.config;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.collect.Lists;
import com.tujia.com.aopandannotation.ComAopandannotationApplication;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.io.UnsupportedEncodingException;
import static springfox.documentation.schema.AlternateTypeRules.newRule;
/**
* @author zhouheng-os
* @Date 2019/10/15
* @Description swagger配置类
*/
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Autowired
private Environment env;
@Autowired
private TypeResolver typeResolver;
@Bean
public Docket test_api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("test_api")
.select()
.apis(RequestHandlerSelectors.basePackage("com.tujia.com.aopandannotation.controller.test"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)), typeResolver.resolve(WildcardType.class)))
// .enableUrlTemplating(true)
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
// .host("")
.apiInfo(apiInfo("test_api","文档中可以查询及测试接口调用参数和结果","4.4"));
// .securitySchemes(Lists.newArrayList(apiKey()))
// .securityContexts(Lists.newArrayList(securityContext()));
}
@Bean
public Docket h5_api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("h5-api")
.select()
.apis(RequestHandlerSelectors.basePackage("com.tujia.com.aopandannotation.controller.h5"))
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)), typeResolver.resolve(WildcardType.class)))
// .enableUrlTemplating(true)
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
.host("127.0.0.3")
.apiInfo(apiInfo("h5_api","文档中可以查询及测试接口调用参数和结果","4.4"));
// .securitySchemes(Lists.newArrayList(apiKey()))
// .securityContexts(Lists.newArrayList(securityContext()));
}
private ApiInfo apiInfo(String title,String description,String version){
return new ApiInfoBuilder()
.title(title)
.description(description)
.version(version)
.build();
}
}
| 3,845 | 0.689078 | 0.681903 | 90 | 40.811111 | 33.855541 | 194 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.455556 | false | false |
0
|
3634c027c794c1a3052c229eab3b895828a29c65
| 39,350,490,399,467 |
88090faa28389d0c1e9af655600dce37f588677b
|
/src/main/java/by/epam/fitness/filter/TimeOutFilter.java
|
e6b2eb2b70e8ee3a54e898840ea190c416121a66
|
[] |
no_license
|
demis131194/fitness
|
https://github.com/demis131194/fitness
|
94beddd4e877914eed5d636c3911088265fcb83a
|
b898c27e433f89ecac99cffd1becce623da32639
|
refs/heads/master
| 2022-06-24T04:19:06.429000 | 2020-06-11T13:19:54 | 2020-06-11T13:19:54 | 217,480,578 | 1 | 3 | null | false | 2022-06-21T02:06:56 | 2019-10-25T07:49:24 | 2020-06-11T13:19:57 | 2022-06-21T02:06:55 | 7,593 | 0 | 2 | 4 |
Java
| false | false |
package by.epam.fitness.filter;
import by.epam.fitness.command.PagePath;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* The type Time out filter.
*/
@WebFilter(urlPatterns = {"/*"})
public class TimeOutFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession();
if(session.isNew()) {
request.getRequestDispatcher(PagePath.MAIN_PATH).forward(request, response);
} else {
chain.doFilter(request, response);
}
}
}
|
UTF-8
|
Java
| 849 |
java
|
TimeOutFilter.java
|
Java
|
[] | null |
[] |
package by.epam.fitness.filter;
import by.epam.fitness.command.PagePath;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* The type Time out filter.
*/
@WebFilter(urlPatterns = {"/*"})
public class TimeOutFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession();
if(session.isNew()) {
request.getRequestDispatcher(PagePath.MAIN_PATH).forward(request, response);
} else {
chain.doFilter(request, response);
}
}
}
| 849 | 0.723204 | 0.723204 | 27 | 30.444445 | 30.154335 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false |
0
|
39de171df4fc0c19e9a4c4d424b94d52b576a332
| 26,199,300,566,639 |
390afe55cee792cf6e9b7b7e4cef6ecb22e43316
|
/padroes/Workspace/BridgeExample1/src/model/JanelaDialogo.java
|
9c4d4d0b875ac31bbc9166a9693e315ee669577c
|
[] |
no_license
|
adrianonna/p5
|
https://github.com/adrianonna/p5
|
31dbd259bebed5de2eaa9b077589baca6131637e
|
b17b15c1b0776da0789b6275d2e28b8219b260ed
|
refs/heads/master
| 2023-01-13T11:52:07.423000 | 2020-05-13T15:45:31 | 2020-05-13T15:45:31 | 223,481,952 | 0 | 0 | null | false | 2023-01-09T12:02:11 | 2019-11-22T20:33:02 | 2020-05-13T15:45:35 | 2023-01-09T12:02:10 | 10,934 | 0 | 0 | 26 |
Java
| false | false |
package model;
public class JanelaDialogo extends Janela {
public JanelaDialogo(JanelaImplementada j) {
super(j);
}
public void desenhar() {
System.out.println(desenharJanela("Janela de Dialogo"));
System.out.println(desenharBotao("Botao Sim"));
System.out.println(desenharBotao("Botao Nao"));
System.out.println(desenharBotao("Botao Cancelar \n"));
}
}
|
UTF-8
|
Java
| 371 |
java
|
JanelaDialogo.java
|
Java
|
[] | null |
[] |
package model;
public class JanelaDialogo extends Janela {
public JanelaDialogo(JanelaImplementada j) {
super(j);
}
public void desenhar() {
System.out.println(desenharJanela("Janela de Dialogo"));
System.out.println(desenharBotao("Botao Sim"));
System.out.println(desenharBotao("Botao Nao"));
System.out.println(desenharBotao("Botao Cancelar \n"));
}
}
| 371 | 0.735849 | 0.735849 | 14 | 25.5 | 22.579226 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false |
0
|
50f694833e1e61c12153a166aaba1739b29311f1
| 34,909,494,228,889 |
c85969b8a71bbdad0bad0a39c4329e2a5786d9e5
|
/app/src/main/java/com/example/brunocoelho/navalbattle/Game/Models/Position.java
|
2ae016ab04688c0dc46c045f5a5c32524f773065
|
[] |
no_license
|
brunocoelho1997/NavalBattleGame
|
https://github.com/brunocoelho1997/NavalBattleGame
|
fd9c96aec5fae7c9ffa3a2bb3fdc52e6663f6666
|
6e0d63ed8ce21a80fec1c86e29284182226bc244
|
refs/heads/master
| 2020-03-24T18:54:30.696000 | 2019-06-04T10:38:31 | 2019-06-04T10:38:31 | 142,333,221 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.brunocoelho.navalbattle.Game.Models;
import com.example.brunocoelho.navalbattle.Game.Constants;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Position implements Serializable{
private int number, letter;
private int color;
private String objectType;
public Position() {
number = -1;
letter = -1;
}
public Position(int number, int letter) {
this.number = number;
this.letter = letter;
this.color = Constants.FULL_SQUARE;
this.objectType = Constants.CLASS_POSITION; //className
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getLetter() {
return letter;
}
public void setLetter(int letter) {
this.letter = letter;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if(this.letter == ((Position)obj).getLetter())
{
if(this.number == ((Position)obj).getNumber())
return true;
}
return false;
}
@Override
public String toString() {
/*
Tem de ser lido como: linha x coluna.
*/
return "[" + (number) + ";" + (char)(letter+96) + "] - " + number + ";" +letter;
}
public boolean isAdjacent(Position onUpPosition) {
List<Position> adjacentPositions = new ArrayList<>();
adjacentPositions.add(new Position(this.getNumber()-1, this.getLetter()));
adjacentPositions.add(new Position(this.getNumber()-1, this.getLetter()+1));
adjacentPositions.add(new Position(this.getNumber()-1, this.getLetter()-1));
adjacentPositions.add(new Position(this.getNumber(), this.getLetter()+1));
adjacentPositions.add(new Position(this.getNumber(), this.getLetter()-1));
adjacentPositions.add(new Position(this.getNumber()+1, this.getLetter()+1));
adjacentPositions.add(new Position(this.getNumber()+1, this.getLetter()));
adjacentPositions.add(new Position(this.getNumber()+1, this.getLetter()-1));
if(adjacentPositions.contains(onUpPosition))
return true;
return false;
}
}
|
UTF-8
|
Java
| 2,392 |
java
|
Position.java
|
Java
|
[
{
"context": "ho.navalbattle.Game.Models;\n\nimport com.example.brunocoelho.navalbattle.Game.Constants;\n\nimport java.io",
"end": 82,
"score": 0.5425195693969727,
"start": 79,
"tag": "USERNAME",
"value": "uno"
}
] | null |
[] |
package com.example.brunocoelho.navalbattle.Game.Models;
import com.example.brunocoelho.navalbattle.Game.Constants;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Position implements Serializable{
private int number, letter;
private int color;
private String objectType;
public Position() {
number = -1;
letter = -1;
}
public Position(int number, int letter) {
this.number = number;
this.letter = letter;
this.color = Constants.FULL_SQUARE;
this.objectType = Constants.CLASS_POSITION; //className
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getLetter() {
return letter;
}
public void setLetter(int letter) {
this.letter = letter;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
@Override
public boolean equals(Object obj) {
if(this.letter == ((Position)obj).getLetter())
{
if(this.number == ((Position)obj).getNumber())
return true;
}
return false;
}
@Override
public String toString() {
/*
Tem de ser lido como: linha x coluna.
*/
return "[" + (number) + ";" + (char)(letter+96) + "] - " + number + ";" +letter;
}
public boolean isAdjacent(Position onUpPosition) {
List<Position> adjacentPositions = new ArrayList<>();
adjacentPositions.add(new Position(this.getNumber()-1, this.getLetter()));
adjacentPositions.add(new Position(this.getNumber()-1, this.getLetter()+1));
adjacentPositions.add(new Position(this.getNumber()-1, this.getLetter()-1));
adjacentPositions.add(new Position(this.getNumber(), this.getLetter()+1));
adjacentPositions.add(new Position(this.getNumber(), this.getLetter()-1));
adjacentPositions.add(new Position(this.getNumber()+1, this.getLetter()+1));
adjacentPositions.add(new Position(this.getNumber()+1, this.getLetter()));
adjacentPositions.add(new Position(this.getNumber()+1, this.getLetter()-1));
if(adjacentPositions.contains(onUpPosition))
return true;
return false;
}
}
| 2,392 | 0.615385 | 0.608696 | 90 | 25.577778 | 26.243719 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511111 | false | false |
0
|
3339fbb23b1643217b65bf49d3c5e823afa7264a
| 19,576,460,992,908 |
073b726fc5f3df52646bb767efc68753274f1f4f
|
/src/main/java/com/rg/DAO/AdminRepository.java
|
b859a035f1e45fa70b8a5b6d3effa01326516fba
|
[] |
no_license
|
rishabhguptagwl/transactionManagement
|
https://github.com/rishabhguptagwl/transactionManagement
|
16fb1f7ddfd594d8d17a65add1f323e5537e77c9
|
ab1d6d012686ea8a1099786a13b1d7f08f4427fe
|
refs/heads/master
| 2023-01-11T07:22:07.081000 | 2021-06-05T19:24:40 | 2021-06-05T19:24:40 | 205,731,633 | 0 | 0 | null | false | 2023-01-08T00:35:04 | 2019-09-01T20:58:48 | 2021-06-05T19:24:45 | 2023-01-08T00:35:02 | 130,117 | 0 | 0 | 22 |
TypeScript
| false | false |
package com.rg.DAO;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.rg.model.Admin;
public interface AdminRepository extends CrudRepository<Admin, Integer> {
@Query(value="select * from admin where username=? and password=?" , nativeQuery=true)
public Admin LoginAdmin(String username , String password);
@Modifying
@Query(value="update admin set lastlogin=? where id=?" ,nativeQuery=true)
public void updateLastLogin(String time,int id);
@Query(value="select invalidlogin from admin where username=?", nativeQuery=true)
public String getLoginCount(String userId);
@Modifying
@Query(value="update admin set invalidlogin=(invalidlogin+1) where username=?", nativeQuery=true)
public void incrementLoginCount(String id);
@Modifying
@Query(value="update admin set invalidlogin=0 where id=?", nativeQuery=true)
public void resetLoginCount(int id);
}
|
UTF-8
|
Java
| 1,017 |
java
|
AdminRepository.java
|
Java
|
[] | null |
[] |
package com.rg.DAO;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.rg.model.Admin;
public interface AdminRepository extends CrudRepository<Admin, Integer> {
@Query(value="select * from admin where username=? and password=?" , nativeQuery=true)
public Admin LoginAdmin(String username , String password);
@Modifying
@Query(value="update admin set lastlogin=? where id=?" ,nativeQuery=true)
public void updateLastLogin(String time,int id);
@Query(value="select invalidlogin from admin where username=?", nativeQuery=true)
public String getLoginCount(String userId);
@Modifying
@Query(value="update admin set invalidlogin=(invalidlogin+1) where username=?", nativeQuery=true)
public void incrementLoginCount(String id);
@Modifying
@Query(value="update admin set invalidlogin=0 where id=?", nativeQuery=true)
public void resetLoginCount(int id);
}
| 1,017 | 0.773845 | 0.771878 | 35 | 28.057142 | 31.692219 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.171429 | false | false |
0
|
1c9c9cada8e8373fce71680d4fdff527a1cdf297
| 37,847,251,841,539 |
22e6668c9656fc7667481340c1da54d7d1b7d26f
|
/src/main/java/com/bitwig/extensions/controllers/arturia/keystep/KeyStepExtensionDefinition.java
|
b1eb79806c6e39b86df9861d8bd340f4a23014d8
|
[
"MIT"
] |
permissive
|
bitwig/bitwig-extensions
|
https://github.com/bitwig/bitwig-extensions
|
e4216e690a56c6cbe42f3f3af41ff9ac899ecfcd
|
3142e700d7f6844e609ee5cc08efc0102026f5c6
|
refs/heads/api-18
| 2023-08-09T13:29:50.268000 | 2023-08-09T08:34:35 | 2023-08-09T08:34:35 | 203,979,004 | 150 | 37 |
MIT
| false | 2023-09-06T08:50:32 | 2019-08-23T10:39:19 | 2023-09-04T20:25:06 | 2023-09-06T08:50:31 | 22,854 | 140 | 31 | 9 |
Java
| false | false |
package com.bitwig.extensions.controllers.arturia.keystep;
import com.bitwig.extension.api.PlatformType;
import com.bitwig.extension.controller.AutoDetectionMidiPortNamesList;
import com.bitwig.extension.controller.ControllerExtensionDefinition;
import com.bitwig.extension.controller.api.ControllerHost;
import java.util.UUID;
public class KeyStepExtensionDefinition extends ControllerExtensionDefinition {
private static final UUID DRIVER_ID = UUID.fromString("6102eb09-7f47-42c1-8462-239de519dcc9");
public KeyStepExtensionDefinition() {
}
@Override
public String getName() {
return "Keystep";
}
@Override
public String getAuthor() {
return "Bitwig";
}
@Override
public String getVersion() {
return "1.0";
}
@Override
public UUID getId() {
return DRIVER_ID;
}
@Override
public String getHardwareVendor() {
return "Arturia";
}
@Override
public String getHardwareModel() {
return "Keystep";
}
@Override
public int getRequiredAPIVersion() {
return 16;
}
@Override
public int getNumMidiInPorts() {
return 1;
}
@Override
public int getNumMidiOutPorts() {
return 1;
}
@Override
public void listAutoDetectionMidiPortNames(final AutoDetectionMidiPortNamesList list,
final PlatformType platformType) {
if (platformType == PlatformType.WINDOWS) {
list.add(new String[]{"Arturia KeyStep 32"}, new String[]{"Arturia KeyStep 32"});
} else if (platformType == PlatformType.MAC) {
list.add(new String[]{"Arturia KeyStep 32"}, new String[]{"Arturia KeyStep 32"});
} else if (platformType == PlatformType.LINUX) {
list.add(new String[]{"Arturia KeyStep 32"}, new String[]{"Arturia KeyStep 32"});
}
}
@Override
public KeyStepProExtension createInstance(final ControllerHost host) {
return new KeyStepProExtension(this, host);
}
}
|
UTF-8
|
Java
| 2,069 |
java
|
KeyStepExtensionDefinition.java
|
Java
|
[] | null |
[] |
package com.bitwig.extensions.controllers.arturia.keystep;
import com.bitwig.extension.api.PlatformType;
import com.bitwig.extension.controller.AutoDetectionMidiPortNamesList;
import com.bitwig.extension.controller.ControllerExtensionDefinition;
import com.bitwig.extension.controller.api.ControllerHost;
import java.util.UUID;
public class KeyStepExtensionDefinition extends ControllerExtensionDefinition {
private static final UUID DRIVER_ID = UUID.fromString("6102eb09-7f47-42c1-8462-239de519dcc9");
public KeyStepExtensionDefinition() {
}
@Override
public String getName() {
return "Keystep";
}
@Override
public String getAuthor() {
return "Bitwig";
}
@Override
public String getVersion() {
return "1.0";
}
@Override
public UUID getId() {
return DRIVER_ID;
}
@Override
public String getHardwareVendor() {
return "Arturia";
}
@Override
public String getHardwareModel() {
return "Keystep";
}
@Override
public int getRequiredAPIVersion() {
return 16;
}
@Override
public int getNumMidiInPorts() {
return 1;
}
@Override
public int getNumMidiOutPorts() {
return 1;
}
@Override
public void listAutoDetectionMidiPortNames(final AutoDetectionMidiPortNamesList list,
final PlatformType platformType) {
if (platformType == PlatformType.WINDOWS) {
list.add(new String[]{"Arturia KeyStep 32"}, new String[]{"Arturia KeyStep 32"});
} else if (platformType == PlatformType.MAC) {
list.add(new String[]{"Arturia KeyStep 32"}, new String[]{"Arturia KeyStep 32"});
} else if (platformType == PlatformType.LINUX) {
list.add(new String[]{"Arturia KeyStep 32"}, new String[]{"Arturia KeyStep 32"});
}
}
@Override
public KeyStepProExtension createInstance(final ControllerHost host) {
return new KeyStepProExtension(this, host);
}
}
| 2,069 | 0.650073 | 0.630256 | 77 | 25.870131 | 27.772429 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.324675 | false | false |
0
|
45e17aa0124c7ef71e76ea30b7cb15a8f7428139
| 20,993,800,202,830 |
df2ab257306f727af1884579d542504a102a1724
|
/src/main/java/org/cesiumjs/cesium/data/DataSource.java
|
849d60d4df9f3854441baaea4380bd3af8aedd35
|
[
"Apache-2.0"
] |
permissive
|
markerikson/cesium-gwt
|
https://github.com/markerikson/cesium-gwt
|
eef80af29c424043e26e4ed2f6c7c6abe22c301d
|
dad5daa7606ed7028a1af6c6e7dc0adaf90c6aaf
|
refs/heads/master
| 2021-01-18T06:51:54.194000 | 2014-09-03T14:58:51 | 2014-09-03T14:58:51 | 23,319,416 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.cesiumjs.cesium.data;
import com.google.gwt.core.client.JavaScriptObject;
public class DataSource extends JavaScriptObject
{
protected DataSource() {}
}
|
UTF-8
|
Java
| 170 |
java
|
DataSource.java
|
Java
|
[] | null |
[] |
package org.cesiumjs.cesium.data;
import com.google.gwt.core.client.JavaScriptObject;
public class DataSource extends JavaScriptObject
{
protected DataSource() {}
}
| 170 | 0.794118 | 0.794118 | 9 | 17.888889 | 20.528811 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
0
|
0dd8606f013a654cec6d14560b79b48b2b3a5ec6
| 39,256,001,111,053 |
02844a1bc2446f0deb1bee7db0f94d24556062b6
|
/social-im-common/src/main/java/com/enuos/live/manager/UserKey.java
|
497804cdaa02bc8a522b344db5fdcaf27ab3cabb
|
[] |
no_license
|
xubinxmcog/xbObj20201120
|
https://github.com/xubinxmcog/xbObj20201120
|
7b48f73f910fc79854b59edec38c67a17ea35168
|
f4e9dc95ba69395eefb50c3c6f7ef4ba1a99943e
|
refs/heads/master
| 2023-01-23T02:51:45.427000 | 2020-11-30T02:59:32 | 2020-11-30T02:59:32 | 314,460,677 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.enuos.live.manager;
/**
* @author WangCaiWen
* Created on 2020/3/19 13:10
*/
public enum UserKey {
/** 用户信息*/
USER("USER",100),
/** 验证码*/
CODE("CODE",200);
private String name;
private Integer code;
UserKey(String name, Integer code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
|
UTF-8
|
Java
| 619 |
java
|
UserKey.java
|
Java
|
[
{
"context": "package com.enuos.live.manager;\n\n/**\n * @author WangCaiWen\n * Created on 2020/3/19 13:10\n */\npublic enum Use",
"end": 58,
"score": 0.9829400777816772,
"start": 48,
"tag": "NAME",
"value": "WangCaiWen"
}
] | null |
[] |
package com.enuos.live.manager;
/**
* @author WangCaiWen
* Created on 2020/3/19 13:10
*/
public enum UserKey {
/** 用户信息*/
USER("USER",100),
/** 验证码*/
CODE("CODE",200);
private String name;
private Integer code;
UserKey(String name, Integer code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
| 619 | 0.550413 | 0.522314 | 37 | 15.351352 | 12.905512 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.378378 | false | false |
0
|
b3a6cac1a877f1a7e52f2fcde752a1169fa52b05
| 34,076,270,583,575 |
32197545c804daccd40eea4a2e1f49cd5e845740
|
/lierl_outerside_tomcat/src/test/java/lierl/outer/tomcat/Test.java
|
aed7077ab8a1fb6a944400701a2d330929e4484b
|
[] |
no_license
|
dream7319/personal_study
|
https://github.com/dream7319/personal_study
|
4235a159650dcbc7713a43d8be017d204ef3ecda
|
19b49b00c9f682f9ef23d40e6e60b73772f8aad4
|
refs/heads/master
| 2020-03-18T17:25:04.225000 | 2018-07-08T11:54:41 | 2018-07-08T11:54:44 | 135,027,431 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lierl.outer.tomcat;
import java.io.File;
import java.io.FilenameFilter;
/**
* @Author: lierl
* @Description:
* @Date: 2018/6/6 7:16
*/
public class Test {
public static void main(String[] args) {
File file = new File("F:\\");
File[] files = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".zip");
}
});
for (File file1 : files) {
System.out.println(file1.getName());
}
}
}
|
UTF-8
|
Java
| 594 |
java
|
Test.java
|
Java
|
[
{
"context": "import java.io.FilenameFilter;\r\n\r\n/**\r\n * @Author: lierl\r\n * @Description:\r\n * @Date: 2018/6/6 7:16\r\n */\r\n",
"end": 109,
"score": 0.9996285438537598,
"start": 104,
"tag": "USERNAME",
"value": "lierl"
}
] | null |
[] |
package lierl.outer.tomcat;
import java.io.File;
import java.io.FilenameFilter;
/**
* @Author: lierl
* @Description:
* @Date: 2018/6/6 7:16
*/
public class Test {
public static void main(String[] args) {
File file = new File("F:\\");
File[] files = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".zip");
}
});
for (File file1 : files) {
System.out.println(file1.getName());
}
}
}
| 594 | 0.521886 | 0.503367 | 25 | 21.76 | 18.151098 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false |
0
|
3d16fe12a20519f656017c7e1f661a97a0716691
| 39,350,490,389,176 |
49cbb3f591441f8dbab9a1d7759f75dbe24354e7
|
/src/main/java/ch/sebastianhaeni/prophector/dto/auth/JwtAuthenticationResponse.java
|
55de0740cd3e3c187e29bb38e70a810db77cc2e9
|
[] |
no_license
|
Prophector/backend
|
https://github.com/Prophector/backend
|
bf1a193825cc78df4140ea2f2953727985842255
|
921c93d4d964d6588f82e0f5f363654f49bd89de
|
refs/heads/main
| 2023-02-24T11:51:12.095000 | 2021-01-31T21:29:10 | 2021-01-31T21:41:38 | 334,646,367 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ch.sebastianhaeni.prophector.dto.auth;
import lombok.Value;
@Value
public class JwtAuthenticationResponse {
String accessToken;
UserInfo user;
}
|
UTF-8
|
Java
| 163 |
java
|
JwtAuthenticationResponse.java
|
Java
|
[
{
"context": "package ch.sebastianhaeni.prophector.dto.auth;\n\nimport lombok.Value;\n\n@V",
"end": 22,
"score": 0.5147421360015869,
"start": 13,
"tag": "USERNAME",
"value": "bastianha"
}
] | null |
[] |
package ch.sebastianhaeni.prophector.dto.auth;
import lombok.Value;
@Value
public class JwtAuthenticationResponse {
String accessToken;
UserInfo user;
}
| 163 | 0.779141 | 0.779141 | 9 | 17.111111 | 16.230591 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
0
|
c1411f63549e5790924c0d4321cb2013f2da020c
| 36,996,848,317,565 |
82d8e3494724dcb2884ed2fb3cfad22d265d2629
|
/dbcalcutest/src/main/java/uyun/bat/research/dbcalcutest/ManageThread.java
|
a7a5beb9c446afb4a9eca2a355bb460d8c3c6e65
|
[] |
no_license
|
zhaoyn2016/research
|
https://github.com/zhaoyn2016/research
|
339c3fb8829315f1078e68d7494a9c47fd25f30a
|
d0b935d4afe9f24381bbdcb4ec255c8a855b9e7a
|
refs/heads/master
| 2016-06-03T02:50:06.893000 | 2016-03-26T11:27:27 | 2016-03-26T11:27:27 | 53,011,353 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package uyun.bat.research.dbcalcutest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import uyun.bat.research.dbcalcutest.entity.CollectData;
import uyun.bat.research.dbcalcutest.entity.SourceData;
import uyun.bat.research.dbcalcutest.service.BufferService;
import uyun.bat.research.dbcalcutest.service.impl.CacheServiceImpl;
import uyun.bat.research.dbcalcutest.service.impl.JsonParserService;
import uyun.bat.research.dbcalcutest.service.impl.KafkaBufferService;
import uyun.bat.research.dbcalcutest.service.impl.PersistenceServiceImpl;
import uyun.bat.research.dbcalcutest.service.impl.RedisBufferService;
import uyun.bat.research.dbcalcutest.util.SimpleProperties;
import uyun.bat.research.dbcalcutest.util.SystemProperties;
public class ManageThread {
private static ManageThread instance;
private static final int BATCHSIZE = 1000;
private BufferService bufferService;
public ManageThread() {
checkSystemProperties();
init();
}
public int getBatchSize() {
return BATCHSIZE;
}
private BufferService getBuffersService() {
if (bufferService == null) {
synchronized (this) {
if (bufferService == null) {
String workDir = System.getProperty("user.dir");
SimpleProperties prop = new SimpleProperties(workDir + "/conf/config.properties");
String bufferType = prop.get("calcutest.bufferservice.type");
if ("kafka".equals(bufferType)) {
bufferService = new KafkaBufferService(new JsonParserService());
} else if ("redis".equals(bufferType)) {
bufferService = new RedisBufferService(new JsonParserService());
}
}
}
}
return bufferService;
}
public static ManageThread getDefault() {
if (instance == null) {
synchronized (ManageThread.class) {
if (instance == null) {
instance = new ManageThread();
}
}
}
return instance;
}
public static void checkSystemProperties() {
String workdir = System.getProperty("user.dir");
SystemProperties.setIfNotExists("dbtest.logs.dir", workdir + "/logs");
SystemProperties.setIfNotExists("logback.configurationFile", workdir + "/conf/logback.xml");
SystemProperties.setIfNotExists("net.sf.ehcache.skipUpdateCheck", "true");
}
public List<CollectData> startBufferService(int batchCount) {
List<SourceData> datas = new ArrayList<SourceData>();
for (int i = 0; i < batchCount; i++) {
String str = "{" + "\"time\": " + System.currentTimeMillis() +
"," + "\"tags\" : { " + "\"host\" : \"myPC" + i
+ "\"," + "\"inst\" : \"/dev/hda" + i + "\"" + "},"
+ "\"values\" : {" + "\"disk.reads\" : 29872.21,"
+ "\"disk.readBytes\" : 239872.21," +
"\"disk.writes\" : 29222.21," +
"\"disk.writeBytes\" : 230289.21,"
+ "\"disk.size\" : 723987.21" + "}}";
datas.add(new SourceData(i, str));
}
getBuffersService().push(datas);
List<CollectData> result = getBuffersService().pull(batchCount);
getBuffersService().pullCommit(result);
return result;
}
public void init() {
getBuffersService().init();
PersistenceServiceImpl.getDefault().init();
CacheServiceImpl.getDefault().init();
}
public void dispose() {
getBuffersService().dispose();
PersistenceServiceImpl.getDefault().dispose();
CacheServiceImpl.getDefault().dispose();
}
public void test(int numCount, int batchNum) {
long startTime = System.currentTimeMillis();
System.out.println("开始时间:" + new Date());
for (int i = 0; i < (numCount / batchNum); i++) {
List<CollectData> list = startBufferService(batchNum);
CacheServiceImpl.getDefault().updateDatas(list, "24h");
}
System.out.println(("结束时间:" + new Date()));
long endTime = System.currentTimeMillis();
long countTime = endTime - startTime;
System.out.println("持续时间:" + countTime);
double speed = numCount * 1000 / countTime;
System.out.println(speed);
BigDecimal decimal = new BigDecimal(speed);
speed = decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println("吞吐量:" + speed + "个/S");
}
public static void main(String[] args) {
//总数、批处理个数
ManageThread.getDefault().test(50000, 1000);
}
}
|
UTF-8
|
Java
| 4,306 |
java
|
ManageThread.java
|
Java
|
[] | null |
[] |
package uyun.bat.research.dbcalcutest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import uyun.bat.research.dbcalcutest.entity.CollectData;
import uyun.bat.research.dbcalcutest.entity.SourceData;
import uyun.bat.research.dbcalcutest.service.BufferService;
import uyun.bat.research.dbcalcutest.service.impl.CacheServiceImpl;
import uyun.bat.research.dbcalcutest.service.impl.JsonParserService;
import uyun.bat.research.dbcalcutest.service.impl.KafkaBufferService;
import uyun.bat.research.dbcalcutest.service.impl.PersistenceServiceImpl;
import uyun.bat.research.dbcalcutest.service.impl.RedisBufferService;
import uyun.bat.research.dbcalcutest.util.SimpleProperties;
import uyun.bat.research.dbcalcutest.util.SystemProperties;
public class ManageThread {
private static ManageThread instance;
private static final int BATCHSIZE = 1000;
private BufferService bufferService;
public ManageThread() {
checkSystemProperties();
init();
}
public int getBatchSize() {
return BATCHSIZE;
}
private BufferService getBuffersService() {
if (bufferService == null) {
synchronized (this) {
if (bufferService == null) {
String workDir = System.getProperty("user.dir");
SimpleProperties prop = new SimpleProperties(workDir + "/conf/config.properties");
String bufferType = prop.get("calcutest.bufferservice.type");
if ("kafka".equals(bufferType)) {
bufferService = new KafkaBufferService(new JsonParserService());
} else if ("redis".equals(bufferType)) {
bufferService = new RedisBufferService(new JsonParserService());
}
}
}
}
return bufferService;
}
public static ManageThread getDefault() {
if (instance == null) {
synchronized (ManageThread.class) {
if (instance == null) {
instance = new ManageThread();
}
}
}
return instance;
}
public static void checkSystemProperties() {
String workdir = System.getProperty("user.dir");
SystemProperties.setIfNotExists("dbtest.logs.dir", workdir + "/logs");
SystemProperties.setIfNotExists("logback.configurationFile", workdir + "/conf/logback.xml");
SystemProperties.setIfNotExists("net.sf.ehcache.skipUpdateCheck", "true");
}
public List<CollectData> startBufferService(int batchCount) {
List<SourceData> datas = new ArrayList<SourceData>();
for (int i = 0; i < batchCount; i++) {
String str = "{" + "\"time\": " + System.currentTimeMillis() +
"," + "\"tags\" : { " + "\"host\" : \"myPC" + i
+ "\"," + "\"inst\" : \"/dev/hda" + i + "\"" + "},"
+ "\"values\" : {" + "\"disk.reads\" : 29872.21,"
+ "\"disk.readBytes\" : 239872.21," +
"\"disk.writes\" : 29222.21," +
"\"disk.writeBytes\" : 230289.21,"
+ "\"disk.size\" : 723987.21" + "}}";
datas.add(new SourceData(i, str));
}
getBuffersService().push(datas);
List<CollectData> result = getBuffersService().pull(batchCount);
getBuffersService().pullCommit(result);
return result;
}
public void init() {
getBuffersService().init();
PersistenceServiceImpl.getDefault().init();
CacheServiceImpl.getDefault().init();
}
public void dispose() {
getBuffersService().dispose();
PersistenceServiceImpl.getDefault().dispose();
CacheServiceImpl.getDefault().dispose();
}
public void test(int numCount, int batchNum) {
long startTime = System.currentTimeMillis();
System.out.println("开始时间:" + new Date());
for (int i = 0; i < (numCount / batchNum); i++) {
List<CollectData> list = startBufferService(batchNum);
CacheServiceImpl.getDefault().updateDatas(list, "24h");
}
System.out.println(("结束时间:" + new Date()));
long endTime = System.currentTimeMillis();
long countTime = endTime - startTime;
System.out.println("持续时间:" + countTime);
double speed = numCount * 1000 / countTime;
System.out.println(speed);
BigDecimal decimal = new BigDecimal(speed);
speed = decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println("吞吐量:" + speed + "个/S");
}
public static void main(String[] args) {
//总数、批处理个数
ManageThread.getDefault().test(50000, 1000);
}
}
| 4,306 | 0.680941 | 0.666824 | 123 | 32.552845 | 24.035612 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.487805 | false | false |
0
|
aed863d2b0834f874a7a5893868a38dfc77d0d09
| 36,996,848,317,216 |
779b7f32cc4624c23f0cc92a908e2579e638efe9
|
/structs/src/main/java/com/ericliu/practice/toy/structs/recall/Package01.java
|
372aaaae9a9d27f629c2f3fd6b00f0fe927f72c3
|
[] |
no_license
|
liuhao163/leetcode-practice
|
https://github.com/liuhao163/leetcode-practice
|
17de6cb94b34115934c5f473243bd5d8ebc89064
|
551458bf3435b3466e048b38da7da3343c4ac59c
|
refs/heads/master
| 2021-07-16T13:32:37.670000 | 2020-06-28T11:38:57 | 2020-06-28T11:38:57 | 175,349,212 | 0 | 0 | null | false | 2019-11-29T18:04:07 | 2019-03-13T04:58:10 | 2019-11-11T03:44:41 | 2019-11-29T18:04:04 | 188 | 0 | 0 | 1 |
Java
| false | false |
package com.ericliu.practice.toy.structs.recall;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: liuhaoeric
* Create time: 2019/07/26
* Description:
*/
public class Package01 {
int[] items;
private int maxWeight;
private int maxCount;
private int weight = 0;
private int count = 0;
private int maxPrice = 0;
private int price = 0;
private List<Integer> list = new ArrayList<>();
public Package01(int[] items, int maxWeight, int maxCount) {
this.items = items;
this.maxWeight = maxWeight;
this.maxCount = maxCount;
}
public void input(int count, int weight, int price) {
if (weight == maxWeight || count == maxCount) {
maxPrice = Math.max(maxPrice, price);
System.out.println("all weight is " + weight + " count is " + count + " price: " + price + " maxPrice: " + maxPrice);
return;
}
input(count + 1, weight, price);
if (weight + items[count] <= maxWeight) {
price+=getPrice(items[count]);
System.out.print("items["+count+"]="+items[count]+" ");
input(count + 1, weight + items[count],price);
}
}
public static void main(String[] args) {
Package01 pkg = new Package01(new int[]{2, 2, 4, 6, 3}, 10, 4);
pkg.input(0, 0, 0);
System.out.println();
}
private int getPrice(int weight) {
int i = 0;
switch (weight) {
case 2:
i = weight * 1;
break;
case 3:
i = weight * 1;
break;
case 4:
i = weight * 1;
break;
case 6:
i = weight * 1;
break;
default:
throw new IllegalArgumentException(" not weight");
}
return i;
}
}
|
UTF-8
|
Java
| 1,910 |
java
|
Package01.java
|
Java
|
[
{
"context": "package com.ericliu.practice.toy.structs.recall;\n\nimport java.util.Ar",
"end": 19,
"score": 0.5129742622375488,
"start": 18,
"tag": "USERNAME",
"value": "u"
},
{
"context": "ArrayList;\nimport java.util.List;\n\n/**\n * @Author: liuhaoeric\n * Create time: 2019/07/26\n * Description:\n */\npu",
"end": 128,
"score": 0.9994543790817261,
"start": 118,
"tag": "USERNAME",
"value": "liuhaoeric"
}
] | null |
[] |
package com.ericliu.practice.toy.structs.recall;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: liuhaoeric
* Create time: 2019/07/26
* Description:
*/
public class Package01 {
int[] items;
private int maxWeight;
private int maxCount;
private int weight = 0;
private int count = 0;
private int maxPrice = 0;
private int price = 0;
private List<Integer> list = new ArrayList<>();
public Package01(int[] items, int maxWeight, int maxCount) {
this.items = items;
this.maxWeight = maxWeight;
this.maxCount = maxCount;
}
public void input(int count, int weight, int price) {
if (weight == maxWeight || count == maxCount) {
maxPrice = Math.max(maxPrice, price);
System.out.println("all weight is " + weight + " count is " + count + " price: " + price + " maxPrice: " + maxPrice);
return;
}
input(count + 1, weight, price);
if (weight + items[count] <= maxWeight) {
price+=getPrice(items[count]);
System.out.print("items["+count+"]="+items[count]+" ");
input(count + 1, weight + items[count],price);
}
}
public static void main(String[] args) {
Package01 pkg = new Package01(new int[]{2, 2, 4, 6, 3}, 10, 4);
pkg.input(0, 0, 0);
System.out.println();
}
private int getPrice(int weight) {
int i = 0;
switch (weight) {
case 2:
i = weight * 1;
break;
case 3:
i = weight * 1;
break;
case 4:
i = weight * 1;
break;
case 6:
i = weight * 1;
break;
default:
throw new IllegalArgumentException(" not weight");
}
return i;
}
}
| 1,910 | 0.510471 | 0.488482 | 78 | 23.47436 | 22.526751 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false |
0
|
e0f355e28ea27ef519a8687d2371540f87928c75
| 36,996,848,318,148 |
6a0ccf66420d983f0bec78e01c22960cc5d474e4
|
/app/src/main/java/com/example/ronald/sfparking/MapsActivity.java
|
32687d1e343c58812a70e1788fe08332d308234c
|
[] |
no_license
|
ronbarrera/SFParking-Project
|
https://github.com/ronbarrera/SFParking-Project
|
7853f2fc819c4ea398d977936ba6603db4116bbb
|
32a699e8fd990480cb35d2da52005c0a73d5ff29
|
refs/heads/master
| 2020-12-30T16:48:20.647000 | 2015-05-20T20:31:23 | 2015-05-20T20:31:23 | 91,036,775 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.ronald.sfparking;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.example.ronald.sfparking.R.id;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%% MAPS ACTIVITY %%%%%%%%%%%%%%%%%%%%%%
/**
* The initial activity of the app.
* displays a google map with information about the current location.
*/
public class MapsActivity extends FragmentActivity implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%% DATA FIELDS %%%%%%%%%%%%%%%%%%%%%%
// map handlers
private static GoogleMap theMap;
private static ParkedDbAccessor parkedDbAccessor;
private static SavedDbAccessor savedDbAccessor;
/**
* Stores the current instantiation of the location client in this object
*/
private GoogleApiClient mGoogleApiClient; //
private boolean mUpdatesRequested = false;
/**
* the LatLng object that keeps the latitude and longitude of the view center.
*/
private LatLng latLngAtCameraCenter;
private List<Address> addressesFromGeocoder;
private ParkLocation parkLoc;
private String sfparkQueryUrl;
private final String radius = "0.010"; // approx. 53ft for accuracy (0.010 miles)
private String streetName = "";
private String onOffSt = "";
private String rates = "";
private String address = "";
private String phone = "";
private boolean isParked;
private boolean isDataAtCenter;
//Timer layout and reference variables
private static LinearLayout timer_layout;
private static TimerPicker timerPicker;
private Intent countDownTimerIntent;
// UI element reference variables
private static CustomMapFragment customMapFragment;
private static SlidingUpPanelLayout sliding_layout_container;
private static ScrollView sliding_up_layout_scrollview;
private static LinearLayout park_save_history_button_bar_layout;
private static TextView park_data_text_view;
private static TextView addressAtCenterPin;
// private static LinearLayout hover_layout; //not needed unless we want to hide it sometimes
private static ToggleButton parkButton;
private static Button saveButton;
private static Button historyButton;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%% ONCREATE %%%%%%%%%%%%%%%%%%%%%%
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
customMapFragment = (CustomMapFragment) getSupportFragmentManager().findFragmentById(id.map);
sliding_layout_container = (SlidingUpPanelLayout) findViewById(id.sliding_layout_container);
sliding_up_layout_scrollview = (ScrollView) findViewById(id.sliding_up_layout_scrollview);
park_save_history_button_bar_layout = (LinearLayout) findViewById(id.ParkSaveHist_Layout);
park_data_text_view = (TextView) findViewById(id.park_data_text_view);
parkButton = (ToggleButton) findViewById(id.park_button);
saveButton = (Button) findViewById(id.save_button);
historyButton = (Button) findViewById(id.history_button);
// hover_layout = (LinearLayout) findViewById(id.hoverPin); // not needed unless we want to hide it sometimes
//create timePicker
timer_layout = (LinearLayout) findViewById(id.timer_layout);
timerPicker = new TimerPicker(this);
parkedDbAccessor = new ParkedDbAccessor(this);
parkedDbAccessor.write();
parkedDbAccessor.read();
savedDbAccessor = new SavedDbAccessor(this);
savedDbAccessor.write();
savedDbAccessor.read();
addressAtCenterPin = (TextView) findViewById(id.addressText);
// markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
/*
A request to connect to Location Services
*/
LocationRequest mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(10000);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(60000);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
buildGoogleApiClient();
mGoogleApiClient.connect();
}
}
protected void onStart() {
super.onStart();
}
/**
* Builds the google API client to add the API to the app build.
*/
private synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
/**
* Creates the google map to be used as the initial view.
*/
private void setupMap() {
try {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
LatLng latLong;
theMap = customMapFragment.getMap();
theMap.setIndoorEnabled(false);
// Enabling MyLocation in Google Map
theMap.setMyLocationEnabled(true);
if (mLastLocation != null) {
latLong = new LatLng(mLastLocation
.getLatitude(), mLastLocation
.getLongitude());
} else {
latLong = new LatLng(37.751864, -122.445840);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(15).build();
theMap.setMyLocationEnabled(true);
theMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
// mGoogleMap.clear();
// latLngAtCameraCenter = theMap.getCameraPosition().target;
customMapFragment.setOnDragListener(new MapWrapperLayout.OnDragListener() {
@Override
public void onDrag(MotionEvent motionEvent) {
//Log.d("ON_DRAG", String.format("ME: %s", motionEvent));
// On ACTION_DOWN, switch to default sliding_layout_container
// On ACTION_UP, proceed to request and display SFPark data
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN: //ACTION_DOWN
// setUpPanelDefault();
// park_data_text_view.setVisibility(View.GONE);
// addressAtCenterPin.setText(" Getting location ");
break;
case MotionEvent.ACTION_UP: //ACTION_UP
latLngAtCameraCenter = theMap.getCameraPosition().target;
queryAndDisplayGoogleData();
queryAndDisplaySfparkData();
sliding_up_layout_scrollview.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
/*theMap.setOnCameraChangeListener(new OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
latLngAtCameraCenter = theMap.getCameraPosition().target;
// markerLayout.setVisibility(View.VISIBLE);
//setupPanelWithoutData();
// request and parse sfpark api
// display appropriate results to user
}
});*/
/* markerLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
LatLng latLng1 = new LatLng(latLngAtCameraCenter.latitude,
latLngAtCameraCenter.longitude);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
}); */
latLngAtCameraCenter = latLong;
queryAndDisplayGoogleData();
queryAndDisplaySfparkData();
sliding_up_layout_scrollview.setVisibility(View.VISIBLE);
parkedMarkerLoader();
if (savedDbAccessor.isEmpty()) {
historyButton.setEnabled(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets up sliding_layout_container for a location that has no data form SFPark
*/
private void setupPanelWithData() {
parkButton.setEnabled(true);
saveButton.setEnabled(true);
int height1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 145, getResources().getDisplayMetrics());
int height2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 195, getResources().getDisplayMetrics());
sliding_up_layout_scrollview.getLayoutParams().height = height1;
sliding_layout_container.setPanelHeight(height2);
sliding_layout_container.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
sliding_layout_container.setTouchEnabled(false);
}
/**
* Sets up sliding_layout_container for a location that contains data from SFPark
*/
private void setupPanelWithoutData() {
parkButton.setEnabled(true);
saveButton.setEnabled(false);
int height1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
int height2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
sliding_up_layout_scrollview.getLayoutParams().height = height1;
sliding_layout_container.setPanelHeight(height2);
sliding_layout_container.setTouchEnabled(false);
sliding_layout_container.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
/**
* Sets up the timer layout in a window with default values
*/
private void setupPanelWithTimerPickerLayout() {
int height1;
if (isDataAtCenter) {
height1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 395, getResources().getDisplayMetrics());
} else {
height1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());
}
int height2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, getResources().getDisplayMetrics());
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int displayHeight = size.y;
int displayWidth = size.x;
System.out.println("h " + displayHeight + " w " + displayWidth);
System.out.println("h2 " + height2);
//sliding_layout_container.setAnchorPoint(0.7f);
//sliding_layout_container.setPanelHeight(height1);
sliding_up_layout_scrollview.getLayoutParams().height = displayHeight - height2 - 50;
park_save_history_button_bar_layout.setVisibility(LinearLayout.GONE);
timer_layout.setVisibility(LinearLayout.VISIBLE);
sliding_layout_container.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
sliding_layout_container.setTouchEnabled(false);
timerPicker.defaultValues();
}
/**
* retrieves data about the center location asynchronously
*/
private void queryAndDisplayGoogleData() {
try {
new GetLocationAsync(latLngAtCameraCenter.latitude,
latLngAtCameraCenter.longitude)
.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets up the information panel by sending a query to the
* SFPark server.
*/
private void queryAndDisplaySfparkData() {
try {
makeURLString(Double.toString(latLngAtCameraCenter.latitude),
Double.toString(latLngAtCameraCenter.longitude),
radius);
parkLoc = new HttpRequest(getApplicationContext()).execute(sfparkQueryUrl).get();
streetName = parkLoc.getName();
if (streetName.equals("No Data")) {
park_data_text_view.setText("\tNo Data");
// Set up panel with No data
setupPanelWithoutData();
isDataAtCenter = false;
} else {
onOffSt = parkLoc.getOnOffStreet();
rates = parkLoc.getRates();
if (onOffSt.equals("Meter")) {
park_data_text_view.setText("\tStreet Name: "
+ streetName + "\n\tType: "
+ onOffSt
+ "\n\tRates:\n"
+ rates);
} else {
address = parkLoc.getAddress();
phone = parkLoc.getPhone();
park_data_text_view.setText("\tName: " + streetName +
"\n\tType: " + onOffSt +
"\n\tAddress: " + address +
"\n\tPhone: " + phone +
"\n\tRates:\n" + rates);
}
// Set up panel when info is available
setupPanelWithData();
isDataAtCenter = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets up sliding_layout_container for a default view
*/
/*public void setUpPanelDefault() {
parkButton.setEnabled(false);
saveButton.setEnabled(false);
sliding_up_layout_scrollview.setVisibility(View.GONE);
sliding_layout_container.setPanelHeight(100);
sliding_layout_container.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
sliding_layout_container.setTouchEnabled(false);
}*/
/**
* If the user parked in the app and then closed it, this puts their parked location back on the
* map when they re-open the app.
*/
private void parkedMarkerLoader() {
theMap.clear();
isParked = !parkedDbAccessor.isEmpty();
if (isParked) {
LatLng parkedLatLng = new LatLng(parkedDbAccessor.getParkedLocation().getLatitude(),
parkedDbAccessor.getParkedLocation().getLongitude());
theMap.addMarker(new MarkerOptions()
.position(parkedLatLng)
.title("I parked here")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
);
parkButton.setText("Unpark");
parkButton.setChecked(true);
} else {
isParked = false;
}
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%% BUTTON HANDLERS %%%%%%%%%%%%%%%%%%%%%%
/**
* Park Button. creates a location object with the given latLngAtCameraCenter and stores it
* into an SQLite database on the device. Also adds a new marker on theMap after clearing any
* other markers placed.
*/
public void parkButton(View view) {
theMap.clear();
if (!isParked) {
if (latLngAtCameraCenter != null) {
setupPanelWithTimerPickerLayout();
Calendar calendar = Calendar.getInstance();
Date d = calendar.getTime();
String str = d.toString();
ParkLocationInfo parkLocationInfo = new ParkLocationInfo();
parkLocationInfo.setLatitude(latLngAtCameraCenter.latitude);
parkLocationInfo.setLongitude(latLngAtCameraCenter.longitude);
parkLocationInfo.setOnOffStreet("On");
parkLocationInfo.setStreetName(parkLoc.getName());
parkLocationInfo.setTime(str);
parkLocationInfo.setRates("");
parkedDbAccessor.createLocationInfo(parkLocationInfo);
theMap.addMarker(new MarkerOptions()
.position(latLngAtCameraCenter)
.title("I parked here")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
);
isParked = true;
parkButton.setText("Unpark");
parkButton.setChecked(true);
} else {
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Current Location Not Available!!!", Toast.LENGTH_SHORT);
toast.show();
}
} else {
theMap.clear();
parkedDbAccessor.clear();
isParked = false;
parkButton.setText("Park");
parkButton.setChecked(false);
if (countDownTimerIntent != null) {
Context context = getApplicationContext();
stopService(countDownTimerIntent);
countDownTimerIntent = null;
Toast toast = Toast.makeText(context, "Timer Cancelled", Toast.LENGTH_SHORT);
toast.show();
}
}
}
/**
* Hides the timer if the option to set it was cancelled
*
* @param view the current view.
*/
public void cancelTimer(View view) {
if (isDataAtCenter)
setupPanelWithData();
else
setupPanelWithoutData();
park_save_history_button_bar_layout.setVisibility(LinearLayout.VISIBLE);
timer_layout.setVisibility(LinearLayout.GONE);
}
/**
* Sets the timer to start in the background and removes the display of it from the view.
*
* @param view the view the timer is in.
*/
public void setTimer(View view) {
countDownTimerIntent = new Intent(this, ParkingTimer.class);
countDownTimerIntent.putExtra("millis", timerPicker.getMilliseconds());
startService(countDownTimerIntent);
cancelTimer(view);
}
/**
* Save Button
* saves a location's data to the SQLite database on the device.
*/
public void saveButton(View view) {
//Location c = m; // m is a data field in the MapsActivity class
if (latLngAtCameraCenter != null) {
Calendar calendar = Calendar.getInstance();
Date d = calendar.getTime();
String time = d.toString();
ParkLocationInfo parkLocationInfo = new ParkLocationInfo();
parkLocationInfo.setLatitude(latLngAtCameraCenter.latitude);
parkLocationInfo.setLongitude(latLngAtCameraCenter.longitude);
parkLocationInfo.setOnOffStreet(parkLoc.getOnOffStreet());
parkLocationInfo.setStreetName(parkLoc.getName());
parkLocationInfo.setTime(time);
parkLocationInfo.setRates(parkLoc.getRates());
savedDbAccessor.createLocationInfo(parkLocationInfo);
Context context = getApplicationContext();
CharSequence message = "Location Saved \uD83D\uDC4D";
Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
//toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
historyButton.setEnabled(true);
} else {
Context context = getApplicationContext();
CharSequence text = "Location Not Available";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
/**
* History Button
* starts the history table activity .SavedLocationsActivity
*/
public void historyButton(View view) {
startActivity(new Intent(".SavedLocationsActivity"));
}
/**
* Allows the user to quickly zoom in or out for a more precise view an overview.
*
* @param view
*/
public void zoomButton(View view) {
float zoom = theMap.getCameraPosition().zoom;
if (zoom == 18.0f) {
theMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
} else
theMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
/**
* gives sfparkQueryUrl a query string from URLMaker using the given params
*
* @param latitude the latitude to include in the string
* @param longitude the longitude to include in the string
* @param radius the radius to include in the string.
*/
private void makeURLString(String latitude, String longitude, String radius) {
URLMaker temp = URLMaker.getInstance();
sfparkQueryUrl = temp.makeURL(latitude, longitude, radius);
}
//empty inherited methods
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onConnected(Bundle connectionHint) {
setupMap();
}
@Override
public void onConnectionSuspended(int i) {
}
//@Override
/*public void onDisconnected() {
}*/
//end empty inherited methods
/**
* Uses a Geocoder object to get latitude and longitude of the current location asynchronously.
*/
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
//constructor
public GetLocationAsync(double latitude, double longitude) {
x = latitude;
y = longitude;
}
/**
* invoked on the UI thread before the task is executed. This step is normally used to setup
* the task, for instance by showing a progress bar in the user interface.
*/
@Override
protected void onPreExecute() {
addressAtCenterPin.setText(" Getting location ");
}
/**
* invoked on the background thread immediately after onPreExecute() finishes executing.
* This step is used to perform background computation that can take a long time. The
* parameters of the asynchronous task are passed to this step. The result of the
* computation must be returned by this step and will be passed back to the last step. This
* step can also use publishProgress(Progress...) to publish one or more units of progress.
* These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
* In this case, it is retrieving addresses from a Geocoder object and getting more detailed
* information about the location and returning it as a string..
*
* @param params the parameters of the asynchronous task.
* @return null for now.
*/
@Override
protected String doInBackground(String... params) {
try {
Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.ENGLISH);
addressesFromGeocoder = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addressesFromGeocoder.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipCode = returnAddress.getPostalCode();
str.append(localityString).append("");
str.append(city).append("").append(region_code).append("");
str.append(zipCode).append("");
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
/**
* invoked on the UI thread after the background computation finishes. The result of the
* background computation is passed to this step as a parameter.
*
* @param result The result of the background computation.
*/
@Override
protected void onPostExecute(String result) {
try {
addressAtCenterPin.setText(addressesFromGeocoder.get(0).getAddressLine(0)
+ "\n" + addressesFromGeocoder.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* invoked on the UI thread after a call to publishProgress(Progress...). The timing of the
* execution is undefined. This method is used to display any form of progress in the user
* interface while the background computation is still executing. For instance, it can be
* used to animate a progress bar or show logs in a text field.
*
* @param values default
*/
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
|
UTF-8
|
Java
| 28,416 |
java
|
MapsActivity.java
|
Java
|
[] | null |
[] |
package com.example.ronald.sfparking;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.example.ronald.sfparking.R.id;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%% MAPS ACTIVITY %%%%%%%%%%%%%%%%%%%%%%
/**
* The initial activity of the app.
* displays a google map with information about the current location.
*/
public class MapsActivity extends FragmentActivity implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%% DATA FIELDS %%%%%%%%%%%%%%%%%%%%%%
// map handlers
private static GoogleMap theMap;
private static ParkedDbAccessor parkedDbAccessor;
private static SavedDbAccessor savedDbAccessor;
/**
* Stores the current instantiation of the location client in this object
*/
private GoogleApiClient mGoogleApiClient; //
private boolean mUpdatesRequested = false;
/**
* the LatLng object that keeps the latitude and longitude of the view center.
*/
private LatLng latLngAtCameraCenter;
private List<Address> addressesFromGeocoder;
private ParkLocation parkLoc;
private String sfparkQueryUrl;
private final String radius = "0.010"; // approx. 53ft for accuracy (0.010 miles)
private String streetName = "";
private String onOffSt = "";
private String rates = "";
private String address = "";
private String phone = "";
private boolean isParked;
private boolean isDataAtCenter;
//Timer layout and reference variables
private static LinearLayout timer_layout;
private static TimerPicker timerPicker;
private Intent countDownTimerIntent;
// UI element reference variables
private static CustomMapFragment customMapFragment;
private static SlidingUpPanelLayout sliding_layout_container;
private static ScrollView sliding_up_layout_scrollview;
private static LinearLayout park_save_history_button_bar_layout;
private static TextView park_data_text_view;
private static TextView addressAtCenterPin;
// private static LinearLayout hover_layout; //not needed unless we want to hide it sometimes
private static ToggleButton parkButton;
private static Button saveButton;
private static Button historyButton;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%% ONCREATE %%%%%%%%%%%%%%%%%%%%%%
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
customMapFragment = (CustomMapFragment) getSupportFragmentManager().findFragmentById(id.map);
sliding_layout_container = (SlidingUpPanelLayout) findViewById(id.sliding_layout_container);
sliding_up_layout_scrollview = (ScrollView) findViewById(id.sliding_up_layout_scrollview);
park_save_history_button_bar_layout = (LinearLayout) findViewById(id.ParkSaveHist_Layout);
park_data_text_view = (TextView) findViewById(id.park_data_text_view);
parkButton = (ToggleButton) findViewById(id.park_button);
saveButton = (Button) findViewById(id.save_button);
historyButton = (Button) findViewById(id.history_button);
// hover_layout = (LinearLayout) findViewById(id.hoverPin); // not needed unless we want to hide it sometimes
//create timePicker
timer_layout = (LinearLayout) findViewById(id.timer_layout);
timerPicker = new TimerPicker(this);
parkedDbAccessor = new ParkedDbAccessor(this);
parkedDbAccessor.write();
parkedDbAccessor.read();
savedDbAccessor = new SavedDbAccessor(this);
savedDbAccessor.write();
savedDbAccessor.read();
addressAtCenterPin = (TextView) findViewById(id.addressText);
// markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
// Getting Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
/*
A request to connect to Location Services
*/
LocationRequest mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(10000);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(60000);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
buildGoogleApiClient();
mGoogleApiClient.connect();
}
}
protected void onStart() {
super.onStart();
}
/**
* Builds the google API client to add the API to the app build.
*/
private synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
/**
* Creates the google map to be used as the initial view.
*/
private void setupMap() {
try {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
LatLng latLong;
theMap = customMapFragment.getMap();
theMap.setIndoorEnabled(false);
// Enabling MyLocation in Google Map
theMap.setMyLocationEnabled(true);
if (mLastLocation != null) {
latLong = new LatLng(mLastLocation
.getLatitude(), mLastLocation
.getLongitude());
} else {
latLong = new LatLng(37.751864, -122.445840);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(15).build();
theMap.setMyLocationEnabled(true);
theMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
// mGoogleMap.clear();
// latLngAtCameraCenter = theMap.getCameraPosition().target;
customMapFragment.setOnDragListener(new MapWrapperLayout.OnDragListener() {
@Override
public void onDrag(MotionEvent motionEvent) {
//Log.d("ON_DRAG", String.format("ME: %s", motionEvent));
// On ACTION_DOWN, switch to default sliding_layout_container
// On ACTION_UP, proceed to request and display SFPark data
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN: //ACTION_DOWN
// setUpPanelDefault();
// park_data_text_view.setVisibility(View.GONE);
// addressAtCenterPin.setText(" Getting location ");
break;
case MotionEvent.ACTION_UP: //ACTION_UP
latLngAtCameraCenter = theMap.getCameraPosition().target;
queryAndDisplayGoogleData();
queryAndDisplaySfparkData();
sliding_up_layout_scrollview.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
/*theMap.setOnCameraChangeListener(new OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
latLngAtCameraCenter = theMap.getCameraPosition().target;
// markerLayout.setVisibility(View.VISIBLE);
//setupPanelWithoutData();
// request and parse sfpark api
// display appropriate results to user
}
});*/
/* markerLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
LatLng latLng1 = new LatLng(latLngAtCameraCenter.latitude,
latLngAtCameraCenter.longitude);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
}); */
latLngAtCameraCenter = latLong;
queryAndDisplayGoogleData();
queryAndDisplaySfparkData();
sliding_up_layout_scrollview.setVisibility(View.VISIBLE);
parkedMarkerLoader();
if (savedDbAccessor.isEmpty()) {
historyButton.setEnabled(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets up sliding_layout_container for a location that has no data form SFPark
*/
private void setupPanelWithData() {
parkButton.setEnabled(true);
saveButton.setEnabled(true);
int height1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 145, getResources().getDisplayMetrics());
int height2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 195, getResources().getDisplayMetrics());
sliding_up_layout_scrollview.getLayoutParams().height = height1;
sliding_layout_container.setPanelHeight(height2);
sliding_layout_container.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
sliding_layout_container.setTouchEnabled(false);
}
/**
* Sets up sliding_layout_container for a location that contains data from SFPark
*/
private void setupPanelWithoutData() {
parkButton.setEnabled(true);
saveButton.setEnabled(false);
int height1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());
int height2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
sliding_up_layout_scrollview.getLayoutParams().height = height1;
sliding_layout_container.setPanelHeight(height2);
sliding_layout_container.setTouchEnabled(false);
sliding_layout_container.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
/**
* Sets up the timer layout in a window with default values
*/
private void setupPanelWithTimerPickerLayout() {
int height1;
if (isDataAtCenter) {
height1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 395, getResources().getDisplayMetrics());
} else {
height1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());
}
int height2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, getResources().getDisplayMetrics());
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int displayHeight = size.y;
int displayWidth = size.x;
System.out.println("h " + displayHeight + " w " + displayWidth);
System.out.println("h2 " + height2);
//sliding_layout_container.setAnchorPoint(0.7f);
//sliding_layout_container.setPanelHeight(height1);
sliding_up_layout_scrollview.getLayoutParams().height = displayHeight - height2 - 50;
park_save_history_button_bar_layout.setVisibility(LinearLayout.GONE);
timer_layout.setVisibility(LinearLayout.VISIBLE);
sliding_layout_container.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
sliding_layout_container.setTouchEnabled(false);
timerPicker.defaultValues();
}
/**
* retrieves data about the center location asynchronously
*/
private void queryAndDisplayGoogleData() {
try {
new GetLocationAsync(latLngAtCameraCenter.latitude,
latLngAtCameraCenter.longitude)
.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets up the information panel by sending a query to the
* SFPark server.
*/
private void queryAndDisplaySfparkData() {
try {
makeURLString(Double.toString(latLngAtCameraCenter.latitude),
Double.toString(latLngAtCameraCenter.longitude),
radius);
parkLoc = new HttpRequest(getApplicationContext()).execute(sfparkQueryUrl).get();
streetName = parkLoc.getName();
if (streetName.equals("No Data")) {
park_data_text_view.setText("\tNo Data");
// Set up panel with No data
setupPanelWithoutData();
isDataAtCenter = false;
} else {
onOffSt = parkLoc.getOnOffStreet();
rates = parkLoc.getRates();
if (onOffSt.equals("Meter")) {
park_data_text_view.setText("\tStreet Name: "
+ streetName + "\n\tType: "
+ onOffSt
+ "\n\tRates:\n"
+ rates);
} else {
address = parkLoc.getAddress();
phone = parkLoc.getPhone();
park_data_text_view.setText("\tName: " + streetName +
"\n\tType: " + onOffSt +
"\n\tAddress: " + address +
"\n\tPhone: " + phone +
"\n\tRates:\n" + rates);
}
// Set up panel when info is available
setupPanelWithData();
isDataAtCenter = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets up sliding_layout_container for a default view
*/
/*public void setUpPanelDefault() {
parkButton.setEnabled(false);
saveButton.setEnabled(false);
sliding_up_layout_scrollview.setVisibility(View.GONE);
sliding_layout_container.setPanelHeight(100);
sliding_layout_container.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
sliding_layout_container.setTouchEnabled(false);
}*/
/**
* If the user parked in the app and then closed it, this puts their parked location back on the
* map when they re-open the app.
*/
private void parkedMarkerLoader() {
theMap.clear();
isParked = !parkedDbAccessor.isEmpty();
if (isParked) {
LatLng parkedLatLng = new LatLng(parkedDbAccessor.getParkedLocation().getLatitude(),
parkedDbAccessor.getParkedLocation().getLongitude());
theMap.addMarker(new MarkerOptions()
.position(parkedLatLng)
.title("I parked here")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
);
parkButton.setText("Unpark");
parkButton.setChecked(true);
} else {
isParked = false;
}
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%% BUTTON HANDLERS %%%%%%%%%%%%%%%%%%%%%%
/**
* Park Button. creates a location object with the given latLngAtCameraCenter and stores it
* into an SQLite database on the device. Also adds a new marker on theMap after clearing any
* other markers placed.
*/
public void parkButton(View view) {
theMap.clear();
if (!isParked) {
if (latLngAtCameraCenter != null) {
setupPanelWithTimerPickerLayout();
Calendar calendar = Calendar.getInstance();
Date d = calendar.getTime();
String str = d.toString();
ParkLocationInfo parkLocationInfo = new ParkLocationInfo();
parkLocationInfo.setLatitude(latLngAtCameraCenter.latitude);
parkLocationInfo.setLongitude(latLngAtCameraCenter.longitude);
parkLocationInfo.setOnOffStreet("On");
parkLocationInfo.setStreetName(parkLoc.getName());
parkLocationInfo.setTime(str);
parkLocationInfo.setRates("");
parkedDbAccessor.createLocationInfo(parkLocationInfo);
theMap.addMarker(new MarkerOptions()
.position(latLngAtCameraCenter)
.title("I parked here")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
);
isParked = true;
parkButton.setText("Unpark");
parkButton.setChecked(true);
} else {
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Current Location Not Available!!!", Toast.LENGTH_SHORT);
toast.show();
}
} else {
theMap.clear();
parkedDbAccessor.clear();
isParked = false;
parkButton.setText("Park");
parkButton.setChecked(false);
if (countDownTimerIntent != null) {
Context context = getApplicationContext();
stopService(countDownTimerIntent);
countDownTimerIntent = null;
Toast toast = Toast.makeText(context, "Timer Cancelled", Toast.LENGTH_SHORT);
toast.show();
}
}
}
/**
* Hides the timer if the option to set it was cancelled
*
* @param view the current view.
*/
public void cancelTimer(View view) {
if (isDataAtCenter)
setupPanelWithData();
else
setupPanelWithoutData();
park_save_history_button_bar_layout.setVisibility(LinearLayout.VISIBLE);
timer_layout.setVisibility(LinearLayout.GONE);
}
/**
* Sets the timer to start in the background and removes the display of it from the view.
*
* @param view the view the timer is in.
*/
public void setTimer(View view) {
countDownTimerIntent = new Intent(this, ParkingTimer.class);
countDownTimerIntent.putExtra("millis", timerPicker.getMilliseconds());
startService(countDownTimerIntent);
cancelTimer(view);
}
/**
* Save Button
* saves a location's data to the SQLite database on the device.
*/
public void saveButton(View view) {
//Location c = m; // m is a data field in the MapsActivity class
if (latLngAtCameraCenter != null) {
Calendar calendar = Calendar.getInstance();
Date d = calendar.getTime();
String time = d.toString();
ParkLocationInfo parkLocationInfo = new ParkLocationInfo();
parkLocationInfo.setLatitude(latLngAtCameraCenter.latitude);
parkLocationInfo.setLongitude(latLngAtCameraCenter.longitude);
parkLocationInfo.setOnOffStreet(parkLoc.getOnOffStreet());
parkLocationInfo.setStreetName(parkLoc.getName());
parkLocationInfo.setTime(time);
parkLocationInfo.setRates(parkLoc.getRates());
savedDbAccessor.createLocationInfo(parkLocationInfo);
Context context = getApplicationContext();
CharSequence message = "Location Saved \uD83D\uDC4D";
Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
//toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
historyButton.setEnabled(true);
} else {
Context context = getApplicationContext();
CharSequence text = "Location Not Available";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
/**
* History Button
* starts the history table activity .SavedLocationsActivity
*/
public void historyButton(View view) {
startActivity(new Intent(".SavedLocationsActivity"));
}
/**
* Allows the user to quickly zoom in or out for a more precise view an overview.
*
* @param view
*/
public void zoomButton(View view) {
float zoom = theMap.getCameraPosition().zoom;
if (zoom == 18.0f) {
theMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
} else
theMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
/**
* gives sfparkQueryUrl a query string from URLMaker using the given params
*
* @param latitude the latitude to include in the string
* @param longitude the longitude to include in the string
* @param radius the radius to include in the string.
*/
private void makeURLString(String latitude, String longitude, String radius) {
URLMaker temp = URLMaker.getInstance();
sfparkQueryUrl = temp.makeURL(latitude, longitude, radius);
}
//empty inherited methods
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onConnected(Bundle connectionHint) {
setupMap();
}
@Override
public void onConnectionSuspended(int i) {
}
//@Override
/*public void onDisconnected() {
}*/
//end empty inherited methods
/**
* Uses a Geocoder object to get latitude and longitude of the current location asynchronously.
*/
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
//constructor
public GetLocationAsync(double latitude, double longitude) {
x = latitude;
y = longitude;
}
/**
* invoked on the UI thread before the task is executed. This step is normally used to setup
* the task, for instance by showing a progress bar in the user interface.
*/
@Override
protected void onPreExecute() {
addressAtCenterPin.setText(" Getting location ");
}
/**
* invoked on the background thread immediately after onPreExecute() finishes executing.
* This step is used to perform background computation that can take a long time. The
* parameters of the asynchronous task are passed to this step. The result of the
* computation must be returned by this step and will be passed back to the last step. This
* step can also use publishProgress(Progress...) to publish one or more units of progress.
* These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
* In this case, it is retrieving addresses from a Geocoder object and getting more detailed
* information about the location and returning it as a string..
*
* @param params the parameters of the asynchronous task.
* @return null for now.
*/
@Override
protected String doInBackground(String... params) {
try {
Geocoder geocoder = new Geocoder(MapsActivity.this, Locale.ENGLISH);
addressesFromGeocoder = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addressesFromGeocoder.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipCode = returnAddress.getPostalCode();
str.append(localityString).append("");
str.append(city).append("").append(region_code).append("");
str.append(zipCode).append("");
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
/**
* invoked on the UI thread after the background computation finishes. The result of the
* background computation is passed to this step as a parameter.
*
* @param result The result of the background computation.
*/
@Override
protected void onPostExecute(String result) {
try {
addressAtCenterPin.setText(addressesFromGeocoder.get(0).getAddressLine(0)
+ "\n" + addressesFromGeocoder.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* invoked on the UI thread after a call to publishProgress(Progress...). The timing of the
* execution is undefined. This method is used to display any form of progress in the user
* interface while the background computation is still executing. For instance, it can be
* used to animate a progress bar or show logs in a text field.
*
* @param values default
*/
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
| 28,416 | 0.602055 | 0.598255 | 762 | 36.290028 | 29.622181 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.471129 | false | false |
0
|
2a3b8da600e39e51d68d7f9790deca57c8b09c5f
| 20,246,475,895,674 |
f8180da69edcba8ad04955260b6b7a08edefd199
|
/internetTV_v2/src/main/java/com/imm/ceflix/model/Comment.java
|
c6d5bbd1fb7d7ecd066efe0a4711fc67192f65c9
|
[] |
no_license
|
mobilekbs/CeflixStudy
|
https://github.com/mobilekbs/CeflixStudy
|
83e8721b58d7fde025e785cbc4d46f1cd98b9856
|
8f36a24dd2743e495d8a43343c66e3ccc5a95bf6
|
refs/heads/master
| 2020-12-24T05:52:45.013000 | 2016-11-16T08:06:24 | 2016-11-16T08:06:24 | 73,445,296 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
*
*/
package com.imm.ceflix.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author Donaldson Chickeme
* @company Internet Multimedia, Christ Emabassy.
* @date Jul 14, 2014 @time 5:48:08 PM
*
*/
public class Comment implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5192107707444723012L;
private String username;
private String photoUrl;
private String comment;
private String replies_count;
private String commentID;
private List<Reply> replyList = new ArrayList<Reply>();
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setRepliesCount(String count){
replies_count = count;
}
public String getRepliesCount(){
return replies_count;
}
public void setCommentID(String id){
commentID = id;
}
public String getCommentID(){
return commentID;
}
public String toString(){
return getComment();
}
public List<Reply> getReplies(){
return replyList;
}
public void setReplyList(List<Reply> replies){
replyList = replies;
}
public static class Reply{
public String username;
public String reply;
public String profilePic;
}
}
|
UTF-8
|
Java
| 1,623 |
java
|
Comment.java
|
Java
|
[
{
"context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author Donaldson Chickeme\n * @company Internet Multimedia, Christ Emabassy.",
"end": 157,
"score": 0.9998513460159302,
"start": 139,
"tag": "NAME",
"value": "Donaldson Chickeme"
},
{
"context": "onaldson Chickeme\n * @company Internet Multimedia, Christ Emabassy.\n * @date Jul 14, 2014 @time 5:48:08 PM\n *\n */\npu",
"end": 206,
"score": 0.7625877261161804,
"start": 191,
"tag": "NAME",
"value": "Christ Emabassy"
}
] | null |
[] |
/**
*
*/
package com.imm.ceflix.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author <NAME>
* @company Internet Multimedia, <NAME>.
* @date Jul 14, 2014 @time 5:48:08 PM
*
*/
public class Comment implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5192107707444723012L;
private String username;
private String photoUrl;
private String comment;
private String replies_count;
private String commentID;
private List<Reply> replyList = new ArrayList<Reply>();
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setRepliesCount(String count){
replies_count = count;
}
public String getRepliesCount(){
return replies_count;
}
public void setCommentID(String id){
commentID = id;
}
public String getCommentID(){
return commentID;
}
public String toString(){
return getComment();
}
public List<Reply> getReplies(){
return replyList;
}
public void setReplyList(List<Reply> replies){
replyList = replies;
}
public static class Reply{
public String username;
public String reply;
public String profilePic;
}
}
| 1,602 | 0.667283 | 0.648799 | 82 | 18.780487 | 16.851593 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.768293 | false | false |
0
|
0b05bc415a139a467be509200985f092baa869fa
| 8,830,452,818,630 |
48e835e6f176a8ac9ae3ca718e8922891f1e5a18
|
/benchmark/training/com/alibaba/json/bvt/TimeZoneFieldTest.java
|
f24f2ba2596b5b3c2af2c2000cbbf32c04ecce00
|
[] |
no_license
|
STAMP-project/dspot-experiments
|
https://github.com/STAMP-project/dspot-experiments
|
f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5
|
121487e65cdce6988081b67f21bbc6731354a47f
|
refs/heads/master
| 2023-02-07T14:40:12.919000 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | false | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | 2022-02-18T17:43:31 | 2023-01-26T23:57:40 | 651,434 | 12 | 14 | 5 | null | false | false |
package com.alibaba.json.bvt;
import SerializerFeature.WriteMapNullValue;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import java.util.TimeZone;
import junit.framework.TestCase;
import org.junit.Assert;
public class TimeZoneFieldTest extends TestCase {
public void test_codec() throws Exception {
TimeZoneFieldTest.User user = new TimeZoneFieldTest.User();
user.setValue(TimeZone.getDefault());
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(user, mapping, WriteMapNullValue);
TimeZoneFieldTest.User user1 = JSON.parseObject(text, TimeZoneFieldTest.User.class);
Assert.assertEquals(user1.getValue(), user.getValue());
}
public void test_codec_null() throws Exception {
TimeZoneFieldTest.User user = new TimeZoneFieldTest.User();
user.setValue(null);
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(user, mapping, WriteMapNullValue);
TimeZoneFieldTest.User user1 = JSON.parseObject(text, TimeZoneFieldTest.User.class);
Assert.assertEquals(user1.getValue(), user.getValue());
}
public static class User {
private TimeZone value;
public TimeZone getValue() {
return value;
}
public void setValue(TimeZone value) {
this.value = value;
}
}
}
|
UTF-8
|
Java
| 1,517 |
java
|
TimeZoneFieldTest.java
|
Java
|
[] | null |
[] |
package com.alibaba.json.bvt;
import SerializerFeature.WriteMapNullValue;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import java.util.TimeZone;
import junit.framework.TestCase;
import org.junit.Assert;
public class TimeZoneFieldTest extends TestCase {
public void test_codec() throws Exception {
TimeZoneFieldTest.User user = new TimeZoneFieldTest.User();
user.setValue(TimeZone.getDefault());
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(user, mapping, WriteMapNullValue);
TimeZoneFieldTest.User user1 = JSON.parseObject(text, TimeZoneFieldTest.User.class);
Assert.assertEquals(user1.getValue(), user.getValue());
}
public void test_codec_null() throws Exception {
TimeZoneFieldTest.User user = new TimeZoneFieldTest.User();
user.setValue(null);
SerializeConfig mapping = new SerializeConfig();
mapping.setAsmEnable(false);
String text = JSON.toJSONString(user, mapping, WriteMapNullValue);
TimeZoneFieldTest.User user1 = JSON.parseObject(text, TimeZoneFieldTest.User.class);
Assert.assertEquals(user1.getValue(), user.getValue());
}
public static class User {
private TimeZone value;
public TimeZone getValue() {
return value;
}
public void setValue(TimeZone value) {
this.value = value;
}
}
}
| 1,517 | 0.694133 | 0.691496 | 44 | 33.454544 | 26.42094 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false |
0
|
cd828667dc1c1e61990396d8b8cf9380e6731bcf
| 21,620,865,377,239 |
018d0962cf20fc1b9f16ffcb0a95351a8cdba33e
|
/homework-g595-murzin/src/main/java/ru/mipt/java2016/homework/g595/murzin/task3slow/LSMStorage.java
|
d1ff6f84639b069423696c9d40259804d6ee1438
|
[] |
no_license
|
dima74/mipt-java-2016
|
https://github.com/dima74/mipt-java-2016
|
b9c2a3f75308b1cc1a9328beaacb9aa3e79bfbc9
|
860c9203347e92b5405dc180c93a17367d43f8a3
|
refs/heads/master
| 2018-01-06T06:52:10.953000 | 2017-01-06T20:50:26 | 2017-01-06T20:50:26 | 70,473,520 | 0 | 0 | null | true | 2016-10-10T09:34:55 | 2016-10-10T09:34:55 | 2016-10-08T15:45:19 | 2016-10-10T06:19:27 | 81 | 0 | 0 | 0 | null | null | null |
package ru.mipt.java2016.homework.g595.murzin.task3slow;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import ru.mipt.java2016.homework.base.task2.KeyValueStorage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Created by dima on 05.11.16.
*/
public class LSMStorage<Key, Value> implements KeyValueStorage<Key, Value> {
private static final String KEYS_FILE_NAME = "keys.dat";
private static final String INFO_FILE_NAME = "info.dat";
private static final int MAX_VALUE_SIZE = 10 * 1024;
private static final int MAX_RAM_SIZE = 64 * 1024 * 1024;
private static final double NEW_ENTRIES_PERCENTAGE = 0.3052 / 2;
private static final double CACHE_PERCENTAGE = NEW_ENTRIES_PERCENTAGE;
private static final int MAX_NEW_ENTRIES_SIZE = (int) (MAX_RAM_SIZE * NEW_ENTRIES_PERCENTAGE / MAX_VALUE_SIZE);
private static final int MAX_CACHE_SIZE = (int) (MAX_RAM_SIZE * CACHE_PERCENTAGE / MAX_VALUE_SIZE);
private final SerializationStrategy<Key> keySerializationStrategy;
private final SerializationStrategy<Value> valueSerializationStrategy;
private final Comparator<Key> comparator;
private final FileLock lock;
private final File storageDirectory;
private final Map<Key, KeyWrapper<Key, Value>> keys = new HashMap<>();
private final List<SstableInfo<Key, Value>> sstableInfos = new ArrayList<>();
private final Set<Integer> sstablesFilesIndexes = new HashSet<>();
private final List<Key> newEntries = new ArrayList<>(MAX_NEW_ENTRIES_SIZE);
private final Cache<Key, Value> cache = CacheBuilder
.newBuilder()
.maximumSize(MAX_CACHE_SIZE)
.build();
private volatile boolean isClosed;
public LSMStorage(String path,
SerializationStrategy<Key> keySerializationStrategy,
SerializationStrategy<Value> valueSerializationStrategy,
Comparator<Key> comparator) {
this.keySerializationStrategy = keySerializationStrategy;
this.valueSerializationStrategy = valueSerializationStrategy;
this.comparator = comparator;
storageDirectory = new File(path);
if (!storageDirectory.isDirectory() || !storageDirectory.exists()) {
throw new MyException("Path " + path + " is not a valid directory name");
}
synchronized (LSMStorage.class) {
try {
// It is between processes lock!!!
lock = new RandomAccessFile(new File(path, ".lock"), "rw").getChannel().lock();
} catch (IOException e) {
throw new MyException("Can't create lock file", e);
}
}
readAllKeys();
readSstablesInfo();
}
private int getNextSstableFileIndex() {
int i = 0;
while (sstablesFilesIndexes.contains(i)) {
++i;
}
sstablesFilesIndexes.add(i);
return i;
}
private String getTableFileName(int index) {
return "table" + index + ".dat";
}
private File getSstableFile(int index) {
return new File(storageDirectory, getTableFileName(index));
}
private void readAllKeys() {
File keysFile = new File(storageDirectory, KEYS_FILE_NAME);
if (!keysFile.exists()) {
return;
}
try (DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(keysFile)))) {
int n = input.readInt();
for (int i = 0; i < n; i++) {
Key key = keySerializationStrategy.deserializeFromStream(input);
KeyWrapper<Key, Value> wrapper = new KeyWrapper<>(key, input.readInt(), input.readLong());
keys.put(key, wrapper);
}
} catch (IOException e) {
throw new MyException("Can't read from keys file " + keysFile.getAbsolutePath(), e);
}
}
private void writeAllKeys() throws IOException {
File keysFile = new File(storageDirectory, KEYS_FILE_NAME);
if (keys.isEmpty()) {
Files.deleteIfExists(keysFile.toPath());
return;
}
try (DataOutputStream output =
new DataOutputStream(new BufferedOutputStream(new FileOutputStream(keysFile)))) {
output.writeInt(keys.size());
for (Map.Entry<Key, KeyWrapper<Key, Value>> entry : keys.entrySet()) {
keySerializationStrategy.serializeToStream(entry.getKey(), output);
KeyWrapper<Key, Value> wrapper = entry.getValue();
output.writeInt(wrapper.getTableIndex());
output.writeLong(wrapper.getOffsetInFile());
}
}
}
private void readSstablesInfo() {
File infoFile = new File(storageDirectory, INFO_FILE_NAME);
boolean exists = infoFile.exists();
if (exists == keys.isEmpty()) {
throw new MyException("TODO");
}
if (!exists) {
return;
}
Map<Integer, List<KeyWrapper<Key, Value>>> collect =
keys.values().stream().collect(Collectors.groupingBy(KeyWrapper::getTableIndex));
try (DataInputStream input = new DataInputStream(new FileInputStream(infoFile))) {
int n = input.readInt();
if (!IntStream.range(0, n).boxed().collect(Collectors.toSet()).equals(collect.keySet())) {
throw new MyException("TODO");
}
for (int i = 0; i < n; i++) {
int fileIndex = input.readInt();
List<KeyWrapper<Key, Value>> wrappersList = collect.get(i);
KeyWrapper<Key, Value>[] wrappers = wrappersList.toArray(new KeyWrapper[wrappersList.size()]);
Arrays.sort(wrappers, (wrapper1, wrapper2) -> comparator.compare(wrapper1.key, wrapper2.key));
sstableInfos.add(new SstableInfo<>(fileIndex, getSstableFile(fileIndex), wrappers));
sstablesFilesIndexes.add(fileIndex);
}
} catch (IOException e) {
throw new MyException("TODO", e);
}
}
private void writeSstablesInfo() throws IOException {
File infoFile = new File(storageDirectory, INFO_FILE_NAME);
if (sstableInfos.isEmpty()) {
return;
}
try (DataOutputStream output =
new DataOutputStream(new BufferedOutputStream(new FileOutputStream(infoFile)))) {
output.writeInt(sstableInfos.size());
for (SstableInfo<Key, Value> info : sstableInfos) {
output.writeInt(info.fileIndex);
}
}
}
private void checkForNewEntriesSize() throws IOException {
if (newEntries.size() < MAX_NEW_ENTRIES_SIZE) {
return;
}
pushNewEntriesToDisk();
checkForMergeTablesOnDisk();
}
private void pushNewEntriesToDisk() {
if (newEntries.isEmpty()) {
return;
}
int newTableFileIndex = getNextSstableFileIndex();
File newTableFile = getSstableFile(newTableFileIndex);
try {
Files.createFile(newTableFile.toPath());
} catch (IOException e) {
throw new MyException("Can't create one of table files " + newTableFile.getAbsolutePath(), e);
}
KeyWrapper<Key, Value>[] wrappers = new KeyWrapper[newEntries.size()];
newEntries.sort(comparator);
try (FileOutputStream fileOutput = new FileOutputStream(newTableFile);
FileChannel fileChannel = fileOutput.getChannel();
DataOutputStream output = new DataOutputStream(fileOutput)) {
output.writeInt(newEntries.size());
for (int i = 0; i < newEntries.size(); i++) {
Key key = newEntries.get(i);
KeyWrapper<Key, Value> wrapper = keys.get(key);
wrappers[i] = wrapper;
wrapper.setTableIndex(sstableInfos.size());
wrapper.setOffsetInFile(fileChannel.position());
valueSerializationStrategy.serializeToStream(wrapper.getValue(), output);
wrapper.setValue(null);
}
} catch (IOException e) {
throw new MyException("Can't write to one of table files " + newTableFile.getAbsolutePath(), e);
}
sstableInfos.add(new SstableInfo<>(newTableFileIndex, newTableFile, wrappers));
newEntries.clear();
}
private void checkForMergeTablesOnDisk() throws IOException {
// https://habrahabr.ru/post/251751/
while (sstableInfos.size() > 1) {
int n = sstableInfos.size() - 2;
int[] tablesLength = sstableInfos.stream().mapToInt(table -> table.size).toArray();
if (n > 0 && tablesLength[n - 1] <= tablesLength[n] + tablesLength[n + 1]
|| n - 1 > 0 && tablesLength[n - 2] <= tablesLength[n] + tablesLength[n - 1]) {
if (tablesLength[n - 1] < tablesLength[n + 1]) {
n--;
}
} else if (n < 0 || tablesLength[n] > tablesLength[n + 1]) {
break; // инвариант установлен
}
System.out.printf("%50s ", Arrays.toString(tablesLength));
mergeTwoTableFiles(n);
System.out.println(Arrays.toString(sstableInfos.stream().mapToInt(table -> table.size).toArray()));
}
}
private class MergeInfo {
private final int length;
private final SstableInfo<Key, Value> sstableInfo;
private final InputStream input;
private final long fileLength;
MergeInfo(int i) throws IOException {
sstableInfo = sstableInfos.get(i);
length = sstableInfo.size;
input = new BufferedInputStream(new FileInputStream(sstableInfo.file), MAX_NEW_ENTRIES_SIZE / 3);
int lengthRecordedInFile = new DataInputStream(input).readInt();
if (lengthRecordedInFile != sstableInfo.size) {
throw new MyException("TODO");
}
fileLength = sstableInfos.get(i).getBufferedRandomAccessFile().fileLength();
}
public Key keyAt(int i) {
return sstableInfo.keys[i];
}
public int getValueSize(int i) {
long end = i == length - 1 ? fileLength : sstableInfo.valuesOffsets[i + 1];
long start = sstableInfo.valuesOffsets[i];
return (int) (end - start);
}
public int getMaxValueSize() {
int maxSize = 0;
for (int i = 0; i < length; i++) {
maxSize = Math.max(maxSize, getValueSize(i));
}
return maxSize;
}
@Override
public String toString() {
return "MergeInfo{" +
"length=" + length +
", sstableInfo=" + sstableInfo +
'}';
}
}
// Сливает таблицы i и i + 1
// Полученной таблице присваивается номер i
// Кроме того индексы всех таблиц с номерами j > i + 1 уменьшаются на один
private void mergeTwoTableFiles(int iTable) throws IOException {
MergeInfo info1 = new MergeInfo(iTable);
MergeInfo info2 = new MergeInfo(iTable + 1);
int maxValueSize = Math.max(info1.getMaxValueSize(), info2.getMaxValueSize());
byte[] buffer = new byte[maxValueSize];
ArrayList<KeyWrapper<Key, Value>> wrappersMerged = new ArrayList<>(info1.length + info2.length);
int newFileIndex = getNextSstableFileIndex();
File newFile = getSstableFile(newFileIndex);
try (OutputStream output = new BufferedOutputStream(new FileOutputStream(newFile), MAX_NEW_ENTRIES_SIZE / 2)) {
new DataOutputStream(output).writeInt(info1.length + info2.length); // Это число перезапишется позже
int i1 = 0;
int i2 = 0;
long position = 4;
while (i1 < info1.length || i2 < info2.length) {
Key key1 = i1 == info1.length ? null : info1.keyAt(i1);
Key key2 = i2 == info2.length ? null : info2.keyAt(i2);
int compare = key1 == null ? 1 : key2 == null ? -1 : comparator.compare(key1, key2);
int i = compare < 0 ? i1++ : i2++;
Key key = compare < 0 ? key1 : key2;
MergeInfo info = compare < 0 ? info1 : info2;
KeyWrapper<Key, Value> wrapper = keys.get(key);
if (wrapper != null) {
int readSize = info.getValueSize(i);
int realReadSize = info.input.read(buffer, 0, readSize);
if (realReadSize != readSize) {
throw new MyException("TODO");
}
output.write(buffer, 0, readSize);
wrapper.setTableIndex(iTable);
wrapper.setOffsetInFile(position);
wrappersMerged.add(wrapper);
position += readSize;
} else {
int readSize = info.getValueSize(i);
long realReadSize = info.input.skip(readSize);
if (realReadSize != readSize) {
throw new MyException("TODO");
}
}
if (compare == 0) {
int numberBytesToSkip = info1.getValueSize(i1);
long numberBytesSkipped = info1.input.skip(numberBytesToSkip);
if (numberBytesSkipped != numberBytesToSkip) {
throw new MyException("TODO");
}
++i1;
}
}
}
try (RandomAccessFile randomAccessFile = new RandomAccessFile(newFile, "rw")) {
randomAccessFile.writeInt(wrappersMerged.size());
}
Files.delete(info1.sstableInfo.file.toPath());
Files.delete(info2.sstableInfo.file.toPath());
sstableInfos.remove(info1.sstableInfo);
sstableInfos.remove(info2.sstableInfo);
sstableInfos.add(iTable, new SstableInfo<>(
newFileIndex, newFile, wrappersMerged.toArray(new KeyWrapper[wrappersMerged.size()])));
for (int i = iTable + 1; i < sstableInfos.size(); i++) {
for (Key key : sstableInfos.get(i).keys) {
KeyWrapper<Key, Value> wrapper = keys.get(key);
wrapper.setTableIndex(wrapper.getTableIndex() - 1);
}
}
}
private void checkForClosed() {
if (isClosed) {
throw new RuntimeException("Access to closed storage");
}
}
@Override
public Value read(Key key) {
checkForClosed();
KeyWrapper<Key, Value> wrapper = keys.get(key);
if (wrapper == null) {
return null;
}
if (wrapper.getValue() != null) {
return wrapper.getValue();
}
Value cacheValue = cache.getIfPresent(key);
if (cacheValue != null) {
return cacheValue;
}
try {
assert wrapper.getTableIndex() != -1;
BufferedRandomAccessFile bufferedRandomAccessFile =
sstableInfos.get(wrapper.getTableIndex()).getBufferedRandomAccessFile();
Value value;
bufferedRandomAccessFile.seek(wrapper.getOffsetInFile());
value = valueSerializationStrategy.deserializeFromStream(bufferedRandomAccessFile.getDataInputStream());
cache.put(key, value);
return value;
} catch (IOException e) {
throw new MyException("Can't read from one of table files", e);
}
}
@Override
public boolean exists(Key key) {
checkForClosed();
return keys.containsKey(key);
}
@Override
public void write(Key key, Value value) {
checkForClosed();
KeyWrapper<Key, Value> wrapper = keys.get(key);
if (wrapper == null) {
keys.put(key, new KeyWrapper<>(key, value, newEntries.size()));
newEntries.add(key);
} else {
wrapper.setTableIndex(-1);
wrapper.setOffsetInFile(-1);
wrapper.setIndexInNewEntries(newEntries.size());
if (wrapper.getValue() == null) { // то есть если key не содержится в newEntries
newEntries.add(key);
}
wrapper.setValue(value);
}
cache.put(key, value);
try {
checkForNewEntriesSize();
} catch (IOException e) {
throw new MyException("Произошла IOException. " +
"В идеале она должна быть проброшена дальше как checked, но ...", e);
}
}
@Override
public void delete(Key key) {
checkForClosed();
KeyWrapper<Key, Value> wrapper = keys.remove(key);
if (wrapper.getValue() != null) {
wrapper.setValue(null);
// wrapper.fileIndex = -1;
// wrapper.offsetInFile = -1;
// wrapper.indexInNewEntries = -1;
Key lastNewEntryKey = newEntries.remove(newEntries.size() - 1);
if (lastNewEntryKey != key) {
newEntries.set(wrapper.getIndexInNewEntries(), lastNewEntryKey);
keys.get(lastNewEntryKey).setIndexInNewEntries(wrapper.getIndexInNewEntries());
}
}
cache.invalidate(key);
}
@Override
public Iterator<Key> readKeys() {
checkForClosed();
return keys.keySet().iterator();
}
@Override
public int size() {
checkForClosed();
return keys.size();
}
@Override
public void close() throws IOException {
checkForClosed();
pushNewEntriesToDisk();
writeAllKeys();
writeSstablesInfo();
for (SstableInfo<Key, Value> info : sstableInfos) {
info.getBufferedRandomAccessFile().close();
}
lock.release();
isClosed = true;
}
}
|
UTF-8
|
Java
| 18,942 |
java
|
LSMStorage.java
|
Java
|
[
{
"context": "ort java.util.stream.IntStream;\n\n/**\n * Created by dima on 05.11.16.\n */\npublic class LSMStorage<Key, Val",
"end": 968,
"score": 0.9890191555023193,
"start": 964,
"tag": "USERNAME",
"value": "dima"
}
] | null |
[] |
package ru.mipt.java2016.homework.g595.murzin.task3slow;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import ru.mipt.java2016.homework.base.task2.KeyValueStorage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Created by dima on 05.11.16.
*/
public class LSMStorage<Key, Value> implements KeyValueStorage<Key, Value> {
private static final String KEYS_FILE_NAME = "keys.dat";
private static final String INFO_FILE_NAME = "info.dat";
private static final int MAX_VALUE_SIZE = 10 * 1024;
private static final int MAX_RAM_SIZE = 64 * 1024 * 1024;
private static final double NEW_ENTRIES_PERCENTAGE = 0.3052 / 2;
private static final double CACHE_PERCENTAGE = NEW_ENTRIES_PERCENTAGE;
private static final int MAX_NEW_ENTRIES_SIZE = (int) (MAX_RAM_SIZE * NEW_ENTRIES_PERCENTAGE / MAX_VALUE_SIZE);
private static final int MAX_CACHE_SIZE = (int) (MAX_RAM_SIZE * CACHE_PERCENTAGE / MAX_VALUE_SIZE);
private final SerializationStrategy<Key> keySerializationStrategy;
private final SerializationStrategy<Value> valueSerializationStrategy;
private final Comparator<Key> comparator;
private final FileLock lock;
private final File storageDirectory;
private final Map<Key, KeyWrapper<Key, Value>> keys = new HashMap<>();
private final List<SstableInfo<Key, Value>> sstableInfos = new ArrayList<>();
private final Set<Integer> sstablesFilesIndexes = new HashSet<>();
private final List<Key> newEntries = new ArrayList<>(MAX_NEW_ENTRIES_SIZE);
private final Cache<Key, Value> cache = CacheBuilder
.newBuilder()
.maximumSize(MAX_CACHE_SIZE)
.build();
private volatile boolean isClosed;
public LSMStorage(String path,
SerializationStrategy<Key> keySerializationStrategy,
SerializationStrategy<Value> valueSerializationStrategy,
Comparator<Key> comparator) {
this.keySerializationStrategy = keySerializationStrategy;
this.valueSerializationStrategy = valueSerializationStrategy;
this.comparator = comparator;
storageDirectory = new File(path);
if (!storageDirectory.isDirectory() || !storageDirectory.exists()) {
throw new MyException("Path " + path + " is not a valid directory name");
}
synchronized (LSMStorage.class) {
try {
// It is between processes lock!!!
lock = new RandomAccessFile(new File(path, ".lock"), "rw").getChannel().lock();
} catch (IOException e) {
throw new MyException("Can't create lock file", e);
}
}
readAllKeys();
readSstablesInfo();
}
private int getNextSstableFileIndex() {
int i = 0;
while (sstablesFilesIndexes.contains(i)) {
++i;
}
sstablesFilesIndexes.add(i);
return i;
}
private String getTableFileName(int index) {
return "table" + index + ".dat";
}
private File getSstableFile(int index) {
return new File(storageDirectory, getTableFileName(index));
}
private void readAllKeys() {
File keysFile = new File(storageDirectory, KEYS_FILE_NAME);
if (!keysFile.exists()) {
return;
}
try (DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(keysFile)))) {
int n = input.readInt();
for (int i = 0; i < n; i++) {
Key key = keySerializationStrategy.deserializeFromStream(input);
KeyWrapper<Key, Value> wrapper = new KeyWrapper<>(key, input.readInt(), input.readLong());
keys.put(key, wrapper);
}
} catch (IOException e) {
throw new MyException("Can't read from keys file " + keysFile.getAbsolutePath(), e);
}
}
private void writeAllKeys() throws IOException {
File keysFile = new File(storageDirectory, KEYS_FILE_NAME);
if (keys.isEmpty()) {
Files.deleteIfExists(keysFile.toPath());
return;
}
try (DataOutputStream output =
new DataOutputStream(new BufferedOutputStream(new FileOutputStream(keysFile)))) {
output.writeInt(keys.size());
for (Map.Entry<Key, KeyWrapper<Key, Value>> entry : keys.entrySet()) {
keySerializationStrategy.serializeToStream(entry.getKey(), output);
KeyWrapper<Key, Value> wrapper = entry.getValue();
output.writeInt(wrapper.getTableIndex());
output.writeLong(wrapper.getOffsetInFile());
}
}
}
private void readSstablesInfo() {
File infoFile = new File(storageDirectory, INFO_FILE_NAME);
boolean exists = infoFile.exists();
if (exists == keys.isEmpty()) {
throw new MyException("TODO");
}
if (!exists) {
return;
}
Map<Integer, List<KeyWrapper<Key, Value>>> collect =
keys.values().stream().collect(Collectors.groupingBy(KeyWrapper::getTableIndex));
try (DataInputStream input = new DataInputStream(new FileInputStream(infoFile))) {
int n = input.readInt();
if (!IntStream.range(0, n).boxed().collect(Collectors.toSet()).equals(collect.keySet())) {
throw new MyException("TODO");
}
for (int i = 0; i < n; i++) {
int fileIndex = input.readInt();
List<KeyWrapper<Key, Value>> wrappersList = collect.get(i);
KeyWrapper<Key, Value>[] wrappers = wrappersList.toArray(new KeyWrapper[wrappersList.size()]);
Arrays.sort(wrappers, (wrapper1, wrapper2) -> comparator.compare(wrapper1.key, wrapper2.key));
sstableInfos.add(new SstableInfo<>(fileIndex, getSstableFile(fileIndex), wrappers));
sstablesFilesIndexes.add(fileIndex);
}
} catch (IOException e) {
throw new MyException("TODO", e);
}
}
private void writeSstablesInfo() throws IOException {
File infoFile = new File(storageDirectory, INFO_FILE_NAME);
if (sstableInfos.isEmpty()) {
return;
}
try (DataOutputStream output =
new DataOutputStream(new BufferedOutputStream(new FileOutputStream(infoFile)))) {
output.writeInt(sstableInfos.size());
for (SstableInfo<Key, Value> info : sstableInfos) {
output.writeInt(info.fileIndex);
}
}
}
private void checkForNewEntriesSize() throws IOException {
if (newEntries.size() < MAX_NEW_ENTRIES_SIZE) {
return;
}
pushNewEntriesToDisk();
checkForMergeTablesOnDisk();
}
private void pushNewEntriesToDisk() {
if (newEntries.isEmpty()) {
return;
}
int newTableFileIndex = getNextSstableFileIndex();
File newTableFile = getSstableFile(newTableFileIndex);
try {
Files.createFile(newTableFile.toPath());
} catch (IOException e) {
throw new MyException("Can't create one of table files " + newTableFile.getAbsolutePath(), e);
}
KeyWrapper<Key, Value>[] wrappers = new KeyWrapper[newEntries.size()];
newEntries.sort(comparator);
try (FileOutputStream fileOutput = new FileOutputStream(newTableFile);
FileChannel fileChannel = fileOutput.getChannel();
DataOutputStream output = new DataOutputStream(fileOutput)) {
output.writeInt(newEntries.size());
for (int i = 0; i < newEntries.size(); i++) {
Key key = newEntries.get(i);
KeyWrapper<Key, Value> wrapper = keys.get(key);
wrappers[i] = wrapper;
wrapper.setTableIndex(sstableInfos.size());
wrapper.setOffsetInFile(fileChannel.position());
valueSerializationStrategy.serializeToStream(wrapper.getValue(), output);
wrapper.setValue(null);
}
} catch (IOException e) {
throw new MyException("Can't write to one of table files " + newTableFile.getAbsolutePath(), e);
}
sstableInfos.add(new SstableInfo<>(newTableFileIndex, newTableFile, wrappers));
newEntries.clear();
}
private void checkForMergeTablesOnDisk() throws IOException {
// https://habrahabr.ru/post/251751/
while (sstableInfos.size() > 1) {
int n = sstableInfos.size() - 2;
int[] tablesLength = sstableInfos.stream().mapToInt(table -> table.size).toArray();
if (n > 0 && tablesLength[n - 1] <= tablesLength[n] + tablesLength[n + 1]
|| n - 1 > 0 && tablesLength[n - 2] <= tablesLength[n] + tablesLength[n - 1]) {
if (tablesLength[n - 1] < tablesLength[n + 1]) {
n--;
}
} else if (n < 0 || tablesLength[n] > tablesLength[n + 1]) {
break; // инвариант установлен
}
System.out.printf("%50s ", Arrays.toString(tablesLength));
mergeTwoTableFiles(n);
System.out.println(Arrays.toString(sstableInfos.stream().mapToInt(table -> table.size).toArray()));
}
}
private class MergeInfo {
private final int length;
private final SstableInfo<Key, Value> sstableInfo;
private final InputStream input;
private final long fileLength;
MergeInfo(int i) throws IOException {
sstableInfo = sstableInfos.get(i);
length = sstableInfo.size;
input = new BufferedInputStream(new FileInputStream(sstableInfo.file), MAX_NEW_ENTRIES_SIZE / 3);
int lengthRecordedInFile = new DataInputStream(input).readInt();
if (lengthRecordedInFile != sstableInfo.size) {
throw new MyException("TODO");
}
fileLength = sstableInfos.get(i).getBufferedRandomAccessFile().fileLength();
}
public Key keyAt(int i) {
return sstableInfo.keys[i];
}
public int getValueSize(int i) {
long end = i == length - 1 ? fileLength : sstableInfo.valuesOffsets[i + 1];
long start = sstableInfo.valuesOffsets[i];
return (int) (end - start);
}
public int getMaxValueSize() {
int maxSize = 0;
for (int i = 0; i < length; i++) {
maxSize = Math.max(maxSize, getValueSize(i));
}
return maxSize;
}
@Override
public String toString() {
return "MergeInfo{" +
"length=" + length +
", sstableInfo=" + sstableInfo +
'}';
}
}
// Сливает таблицы i и i + 1
// Полученной таблице присваивается номер i
// Кроме того индексы всех таблиц с номерами j > i + 1 уменьшаются на один
private void mergeTwoTableFiles(int iTable) throws IOException {
MergeInfo info1 = new MergeInfo(iTable);
MergeInfo info2 = new MergeInfo(iTable + 1);
int maxValueSize = Math.max(info1.getMaxValueSize(), info2.getMaxValueSize());
byte[] buffer = new byte[maxValueSize];
ArrayList<KeyWrapper<Key, Value>> wrappersMerged = new ArrayList<>(info1.length + info2.length);
int newFileIndex = getNextSstableFileIndex();
File newFile = getSstableFile(newFileIndex);
try (OutputStream output = new BufferedOutputStream(new FileOutputStream(newFile), MAX_NEW_ENTRIES_SIZE / 2)) {
new DataOutputStream(output).writeInt(info1.length + info2.length); // Это число перезапишется позже
int i1 = 0;
int i2 = 0;
long position = 4;
while (i1 < info1.length || i2 < info2.length) {
Key key1 = i1 == info1.length ? null : info1.keyAt(i1);
Key key2 = i2 == info2.length ? null : info2.keyAt(i2);
int compare = key1 == null ? 1 : key2 == null ? -1 : comparator.compare(key1, key2);
int i = compare < 0 ? i1++ : i2++;
Key key = compare < 0 ? key1 : key2;
MergeInfo info = compare < 0 ? info1 : info2;
KeyWrapper<Key, Value> wrapper = keys.get(key);
if (wrapper != null) {
int readSize = info.getValueSize(i);
int realReadSize = info.input.read(buffer, 0, readSize);
if (realReadSize != readSize) {
throw new MyException("TODO");
}
output.write(buffer, 0, readSize);
wrapper.setTableIndex(iTable);
wrapper.setOffsetInFile(position);
wrappersMerged.add(wrapper);
position += readSize;
} else {
int readSize = info.getValueSize(i);
long realReadSize = info.input.skip(readSize);
if (realReadSize != readSize) {
throw new MyException("TODO");
}
}
if (compare == 0) {
int numberBytesToSkip = info1.getValueSize(i1);
long numberBytesSkipped = info1.input.skip(numberBytesToSkip);
if (numberBytesSkipped != numberBytesToSkip) {
throw new MyException("TODO");
}
++i1;
}
}
}
try (RandomAccessFile randomAccessFile = new RandomAccessFile(newFile, "rw")) {
randomAccessFile.writeInt(wrappersMerged.size());
}
Files.delete(info1.sstableInfo.file.toPath());
Files.delete(info2.sstableInfo.file.toPath());
sstableInfos.remove(info1.sstableInfo);
sstableInfos.remove(info2.sstableInfo);
sstableInfos.add(iTable, new SstableInfo<>(
newFileIndex, newFile, wrappersMerged.toArray(new KeyWrapper[wrappersMerged.size()])));
for (int i = iTable + 1; i < sstableInfos.size(); i++) {
for (Key key : sstableInfos.get(i).keys) {
KeyWrapper<Key, Value> wrapper = keys.get(key);
wrapper.setTableIndex(wrapper.getTableIndex() - 1);
}
}
}
private void checkForClosed() {
if (isClosed) {
throw new RuntimeException("Access to closed storage");
}
}
@Override
public Value read(Key key) {
checkForClosed();
KeyWrapper<Key, Value> wrapper = keys.get(key);
if (wrapper == null) {
return null;
}
if (wrapper.getValue() != null) {
return wrapper.getValue();
}
Value cacheValue = cache.getIfPresent(key);
if (cacheValue != null) {
return cacheValue;
}
try {
assert wrapper.getTableIndex() != -1;
BufferedRandomAccessFile bufferedRandomAccessFile =
sstableInfos.get(wrapper.getTableIndex()).getBufferedRandomAccessFile();
Value value;
bufferedRandomAccessFile.seek(wrapper.getOffsetInFile());
value = valueSerializationStrategy.deserializeFromStream(bufferedRandomAccessFile.getDataInputStream());
cache.put(key, value);
return value;
} catch (IOException e) {
throw new MyException("Can't read from one of table files", e);
}
}
@Override
public boolean exists(Key key) {
checkForClosed();
return keys.containsKey(key);
}
@Override
public void write(Key key, Value value) {
checkForClosed();
KeyWrapper<Key, Value> wrapper = keys.get(key);
if (wrapper == null) {
keys.put(key, new KeyWrapper<>(key, value, newEntries.size()));
newEntries.add(key);
} else {
wrapper.setTableIndex(-1);
wrapper.setOffsetInFile(-1);
wrapper.setIndexInNewEntries(newEntries.size());
if (wrapper.getValue() == null) { // то есть если key не содержится в newEntries
newEntries.add(key);
}
wrapper.setValue(value);
}
cache.put(key, value);
try {
checkForNewEntriesSize();
} catch (IOException e) {
throw new MyException("Произошла IOException. " +
"В идеале она должна быть проброшена дальше как checked, но ...", e);
}
}
@Override
public void delete(Key key) {
checkForClosed();
KeyWrapper<Key, Value> wrapper = keys.remove(key);
if (wrapper.getValue() != null) {
wrapper.setValue(null);
// wrapper.fileIndex = -1;
// wrapper.offsetInFile = -1;
// wrapper.indexInNewEntries = -1;
Key lastNewEntryKey = newEntries.remove(newEntries.size() - 1);
if (lastNewEntryKey != key) {
newEntries.set(wrapper.getIndexInNewEntries(), lastNewEntryKey);
keys.get(lastNewEntryKey).setIndexInNewEntries(wrapper.getIndexInNewEntries());
}
}
cache.invalidate(key);
}
@Override
public Iterator<Key> readKeys() {
checkForClosed();
return keys.keySet().iterator();
}
@Override
public int size() {
checkForClosed();
return keys.size();
}
@Override
public void close() throws IOException {
checkForClosed();
pushNewEntriesToDisk();
writeAllKeys();
writeSstablesInfo();
for (SstableInfo<Key, Value> info : sstableInfos) {
info.getBufferedRandomAccessFile().close();
}
lock.release();
isClosed = true;
}
}
| 18,942 | 0.586796 | 0.579212 | 471 | 38.74947 | 28.457531 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.70276 | false | false |
0
|
7b56aea49c671a017e50f72f47388404d6c09186
| 11,364,483,506,001 |
b5ae73f70fde841b2d8dd5ee4dd667a1eac21785
|
/permissionlib/src/main/java/com/linxz/permissionlib/listener/PermissionListener.java
|
aa8b9f43fa0fb92963b30c7234a9a8c697e96b8a
|
[] |
no_license
|
paomian2/Permission
|
https://github.com/paomian2/Permission
|
631d266baa36dec28615d697e372009896daf3e4
|
2002083132700d914617961f9a22c515dd018ae0
|
refs/heads/master
| 2021-08-27T18:24:45.254000 | 2021-08-06T08:05:09 | 2021-08-06T08:05:09 | 149,689,554 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.linxz.permissionlib.listener;
import android.support.annotation.NonNull;
public interface PermissionListener {
/**
* 申请权限全部成功时回调
*
* @param requestCode 请求码
* @param grantPermissions 请求的权限
*/
void onSucceed(int requestCode, @NonNull String[] grantPermissions);
/**
* 申请权限失败回调
*
* @param requestCode 请求码
* @param deniedPermissions 请求失败的权限
*/
void onFailed(int requestCode, @NonNull String[] deniedPermissions);
}
|
UTF-8
|
Java
| 579 |
java
|
PermissionListener.java
|
Java
|
[] | null |
[] |
package com.linxz.permissionlib.listener;
import android.support.annotation.NonNull;
public interface PermissionListener {
/**
* 申请权限全部成功时回调
*
* @param requestCode 请求码
* @param grantPermissions 请求的权限
*/
void onSucceed(int requestCode, @NonNull String[] grantPermissions);
/**
* 申请权限失败回调
*
* @param requestCode 请求码
* @param deniedPermissions 请求失败的权限
*/
void onFailed(int requestCode, @NonNull String[] deniedPermissions);
}
| 579 | 0.653465 | 0.653465 | 24 | 20.083334 | 21.906841 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
0
|
4fdb95f520a905866f57c56294c883412f0cc31f
| 24,129,126,306,901 |
65772e5b8e06f631054bed5a6f7a4e3ff573a9f2
|
/booking/src/main/java/org/jboss/seam/examples/booking/exceptioncontrol/GeneralExceptionHandler.java
|
4e0038fb91ff38bb3f603de7261856867a0b4556
|
[] |
no_license
|
cnpcvideo/VideoSystem
|
https://github.com/cnpcvideo/VideoSystem
|
4ef8d71cfd4e39068fedc03503b377f97a8550da
|
914340408211937b5cd735fc459388cea83153d9
|
refs/heads/master
| 2016-09-06T00:39:56.645000 | 2012-01-12T09:47:43 | 2012-01-12T09:47:43 | 2,913,628 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.seam.examples.booking.exceptioncontrol;
import org.jboss.solder.logging.Logger;
import org.jboss.solder.exception.control.CaughtException;
import org.jboss.solder.exception.control.Handles;
import org.jboss.solder.exception.control.HandlesExceptions;
/**
* Logs all exceptions and allows the to propagate
*
* @author <a href="http://community.jboss.org/people/spinner">Jose Freitas</a>
*/
@HandlesExceptions
public class GeneralExceptionHandler {
public void printExceptionMessage(@Handles CaughtException<Throwable> event, Logger log) {
log.info("Exception logged by seam-catch catcher: " + event.getException().getMessage());
event.rethrow();
}
}
|
UTF-8
|
Java
| 1,519 |
java
|
GeneralExceptionHandler.java
|
Java
|
[
{
"context": " href=\"http://community.jboss.org/people/spinner\">Jose Freitas</a>\r\n */\r\n@HandlesExceptions\r\npublic class Genera",
"end": 1215,
"score": 0.999366283416748,
"start": 1203,
"tag": "NAME",
"value": "Jose Freitas"
}
] | null |
[] |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.seam.examples.booking.exceptioncontrol;
import org.jboss.solder.logging.Logger;
import org.jboss.solder.exception.control.CaughtException;
import org.jboss.solder.exception.control.Handles;
import org.jboss.solder.exception.control.HandlesExceptions;
/**
* Logs all exceptions and allows the to propagate
*
* @author <a href="http://community.jboss.org/people/spinner"><NAME></a>
*/
@HandlesExceptions
public class GeneralExceptionHandler {
public void printExceptionMessage(@Handles CaughtException<Throwable> event, Logger log) {
log.info("Exception logged by seam-catch catcher: " + event.getException().getMessage());
event.rethrow();
}
}
| 1,513 | 0.742594 | 0.737327 | 36 | 40.194443 | 30.18169 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
0
|
29be03f1bfea67eb78f4713952cbfd43c5834a87
| 24,739,011,662,579 |
056386baab8a1ff68d2b318c0fad3e3f115a971d
|
/src/main/java/com/everis/livecode/accesmodifiers/Sample.java
|
6077d1e2160f1512fe6d062f3e65d9d34bf0a2b3
|
[] |
no_license
|
javaPassionate/everisJavaTrainingLiveCode
|
https://github.com/javaPassionate/everisJavaTrainingLiveCode
|
453fa1afb9b23ac25e31a4e51e73568a532dbdfa
|
3b08c2f40a1ea0dc0145a61fe25259ae1623ebbd
|
refs/heads/master
| 2020-05-07T14:21:00.081000 | 2019-04-11T11:44:45 | 2019-04-11T11:44:45 | 180,589,949 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.everis.livecode.accesmodifiers;
public class Sample {
private String privateMember;
String member;
protected String protectedMember;
public String publiceMember;
}
|
UTF-8
|
Java
| 182 |
java
|
Sample.java
|
Java
|
[] | null |
[] |
package com.everis.livecode.accesmodifiers;
public class Sample {
private String privateMember;
String member;
protected String protectedMember;
public String publiceMember;
}
| 182 | 0.813187 | 0.813187 | 9 | 19.222221 | 15.229925 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
0
|
b665659f2b3bf85b326b5589aa34fe24563b0ae3
| 10,548,439,743,261 |
95e944448000c08dd3d6915abb468767c9f29d3c
|
/sources/com/p280ss/android/ugc/aweme/legoImp/task/C32397b.java
|
f5df6df79a4a65acddacbb29cdb5af3c8cf44dc1
|
[] |
no_license
|
xrealm/tiktok-src
|
https://github.com/xrealm/tiktok-src
|
261b1faaf7b39d64bb7cb4106dc1a35963bd6868
|
90f305b5f981d39cfb313d75ab231326c9fca597
|
refs/heads/master
| 2022-11-12T06:43:07.401000 | 2020-07-04T20:21:12 | 2020-07-04T20:21:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.p280ss.android.ugc.aweme.legoImp.task;
import com.p280ss.android.anrmonitor.ANRError;
import com.p280ss.android.anrmonitor.C19214a.C19218a;
/* renamed from: com.ss.android.ugc.aweme.legoImp.task.b */
final /* synthetic */ class C32397b implements C19218a {
/* renamed from: a */
private final AnrTask f84516a;
C32397b(AnrTask anrTask) {
this.f84516a = anrTask;
}
/* renamed from: a */
public final void mo50918a(ANRError aNRError, int i) {
this.f84516a.lambda$run$0$AnrTask(aNRError, i);
}
}
|
UTF-8
|
Java
| 553 |
java
|
C32397b.java
|
Java
|
[] | null |
[] |
package com.p280ss.android.ugc.aweme.legoImp.task;
import com.p280ss.android.anrmonitor.ANRError;
import com.p280ss.android.anrmonitor.C19214a.C19218a;
/* renamed from: com.ss.android.ugc.aweme.legoImp.task.b */
final /* synthetic */ class C32397b implements C19218a {
/* renamed from: a */
private final AnrTask f84516a;
C32397b(AnrTask anrTask) {
this.f84516a = anrTask;
}
/* renamed from: a */
public final void mo50918a(ANRError aNRError, int i) {
this.f84516a.lambda$run$0$AnrTask(aNRError, i);
}
}
| 553 | 0.692586 | 0.593128 | 20 | 26.65 | 22.961435 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
0
|
f1bef3c59228f5d016977d969a5b6006a4630985
| 22,548,578,364,857 |
13b9ce118bf15756d2f5543c46a14a084d3a760b
|
/quora-service/src/main/java/com/upgrad/quora/service/business/AdminBusinessService.java
|
6e172ebd47a50bbf36f256e4429f97382440b85a
|
[] |
no_license
|
komal1204/Course-5-Group-Project
|
https://github.com/komal1204/Course-5-Group-Project
|
9cccfc7fa69e4288c06fe194d45abad0d728e56e
|
5dc2b1a4a99adfcb13b616f96dafb6ae8acfb80a
|
refs/heads/master
| 2020-04-03T06:01:49.013000 | 2018-10-28T13:34:08 | 2018-10-28T13:34:08 | 154,483,598 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.upgrad.quora.service.business;
import com.upgrad.quora.service.dao.UserDao;
import com.upgrad.quora.service.entity.UserEntity;
import com.upgrad.quora.service.exception.AuthorizationFailedException;
import com.upgrad.quora.service.exception.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.ZonedDateTime;
@Service
public class AdminBusinessService {
@Autowired
private UserDao userDao;
@Autowired
private UserBusinessService userBusinessService;
//This method first checks whether the token entered is correc, if not exception is thrown. If it is correct, it then checks whether the user is admin or not
/**
* This retuen the uuid if the user is valid after deleting that user
* @param userUuid
* @param authorization
* @return UUID Of User
* @throws AuthorizationFailedException
* @throws UserNotFoundException
*/
@Transactional(propagation=Propagation.REQUIRED)
public String getUserAuth(final String userUuid,final String authorization) throws AuthorizationFailedException, UserNotFoundException {
UserEntity getUserEntity=userBusinessService.getUser(userUuid,authorization);
if(getUserEntity.getRole().equals("nonadmin")){
throw new AuthorizationFailedException("ATHR-003","Unauthorized Access, Entered user is not an admin");
}
String uuidUser=userDao.deleteUser(getUserEntity);
return uuidUser;
}
}
|
UTF-8
|
Java
| 1,680 |
java
|
AdminBusinessService.java
|
Java
|
[] | null |
[] |
package com.upgrad.quora.service.business;
import com.upgrad.quora.service.dao.UserDao;
import com.upgrad.quora.service.entity.UserEntity;
import com.upgrad.quora.service.exception.AuthorizationFailedException;
import com.upgrad.quora.service.exception.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.ZonedDateTime;
@Service
public class AdminBusinessService {
@Autowired
private UserDao userDao;
@Autowired
private UserBusinessService userBusinessService;
//This method first checks whether the token entered is correc, if not exception is thrown. If it is correct, it then checks whether the user is admin or not
/**
* This retuen the uuid if the user is valid after deleting that user
* @param userUuid
* @param authorization
* @return UUID Of User
* @throws AuthorizationFailedException
* @throws UserNotFoundException
*/
@Transactional(propagation=Propagation.REQUIRED)
public String getUserAuth(final String userUuid,final String authorization) throws AuthorizationFailedException, UserNotFoundException {
UserEntity getUserEntity=userBusinessService.getUser(userUuid,authorization);
if(getUserEntity.getRole().equals("nonadmin")){
throw new AuthorizationFailedException("ATHR-003","Unauthorized Access, Entered user is not an admin");
}
String uuidUser=userDao.deleteUser(getUserEntity);
return uuidUser;
}
}
| 1,680 | 0.770238 | 0.768452 | 50 | 32.599998 | 36.665516 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46 | false | false |
0
|
d576059794cff5e72f358c2b92a8cfae14afbb8e
| 29,738,353,619,692 |
43f3c2bd96c93b8a8505995ec912820518677628
|
/src/main/java/com/revature/repository/DatabaseBridge.java
|
a5a38123052c23b8d48cbdbf54d9fd78a45e3219
|
[] |
no_license
|
190819-reston-java/project-0-Chris-Michael-Allen
|
https://github.com/190819-reston-java/project-0-Chris-Michael-Allen
|
b1e549f3197891c1947d7721bb7237986846cf45
|
43c092355eefc821a43fa127fd5637edee2ef4e4
|
refs/heads/master
| 2022-09-25T12:30:49.780000 | 2019-09-16T15:50:28 | 2019-09-16T15:50:28 | 206,370,613 | 0 | 0 | null | false | 2022-09-08T01:02:17 | 2019-09-04T17:04:30 | 2019-09-16T15:50:36 | 2022-09-08T01:02:17 | 51 | 0 | 0 | 3 |
HTML
| false | false |
package com.revature.repository;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import com.revature.service.RetrievalLayer;
public class DatabaseBridge {
static final Logger logger = Logger.getLogger(DatabaseBridge.class);
private List<List<String>> transaction_history_data = new ArrayList<List<String>>();
public void sendToUserDatabase(HashMap<String, List<String>> data_to_send) {
Statement statement = null;
ResultSet results = null;
Connection conn = null;
logger.info("Now iterating through update data passed from service layer");
for (List<String> user_data : data_to_send.values()) {
String query_string;
// Check if there is already an entry in the database for the username
query_string = "SELECT * FROM users WHERE users.user_name = 'entry_username';";
query_string = query_string.replaceAll("entry_username", user_data.get(0));
logger.info("Attempting to determine if user is currently in the table");
logger.info("Query to be sent to the database: " + query_string);
try {
conn = ConnectionUtil.getConnection();
statement = conn.createStatement();
results = statement.executeQuery(query_string);
if (results.next()) {
logger.info("Selected user is currently in the table - will update entry");
query_string = this.updateTableEntry(user_data);
logger.info("Query to perform: " + query_string);
} else {
logger.info("Selected user is not currently in the table - will insert entry");
query_string = this.insertTableEntry(user_data);
logger.info("Query to perform: " + query_string);
}
statement.executeUpdate(query_string);
logger.info("Query has been handled");
} catch (SQLException e) {
logger.debug("There was an SQL exception when attempting to save to the database");
e.printStackTrace();
} finally {
try {
results.close();
statement.close();
conn.close();
} catch (SQLException e) {
logger.debug("There was an SQL exception when attempting to close the connection while saving to the database");
e.printStackTrace();
}
}
}
logger.info("After updating user table, now updating transaction history table");
insertToTransactionHistoryTable();
logger.info("Successfully updated transaction history table from function sendToDatabase");
}
public List<List<String>> retrieveFromTransactionHistory(String user_key) {
logger.info("Inserting known values into the transaction history table before retrieving information");
this.insertToTransactionHistoryTable();
List<List<String>> transaction_history_for_a_user = new ArrayList<List<String>>();
Statement statement = null;
ResultSet results = null;
Connection conn = null;
String retrieval_query = "SELECT prior_amount, transfer_amount, new_amount, transaction_time "
+ "FROM transaction_history "
+ "WHERE reference_user = 'user_key' "
+ "ORDER BY transaction_time DESC;";
retrieval_query = retrieval_query.replaceAll("user_key", user_key);
logger.info("Constructed query to retrieve transaction history for user");
logger.info("Constructed query: " + retrieval_query);
try {
conn = ConnectionUtil.getConnection();
statement = conn.createStatement();
results = statement.executeQuery(retrieval_query);
String prior_amount;
String transfer_amount;
String new_amount;
String transaction_time;
List<String> data_array;
while(results.next()) {
prior_amount = results.getString("prior_amount");
transfer_amount = results.getString("transfer_amount");
new_amount = results.getString("new_amount");
transaction_time = results.getString("transaction_time");
logger.info("Extracted and formatted relevant user data from transaction history table");
data_array = Arrays.asList(prior_amount, transfer_amount, new_amount, transaction_time);
transaction_history_for_a_user.add(data_array);
logger.info("Added the value to the array of user transaction history to be returned to service layer (note: implicitly ordered by query)");
}
}
catch (SQLException e) {
logger.debug("There was an SQL exception when attempting to retrieve transaction history from the database");
e.printStackTrace();
}
finally {
try {
results.close();
statement.close();
conn.close();
} catch (SQLException e) {
logger.debug("There was an SQL exception when attempting to close connection after retrieving transaction history from the database");
e.printStackTrace();
}
}
logger.info("Returning array of user's transaction history for user by the service layer");
return transaction_history_for_a_user;
}
public HashMap<String, List<String>> retrieveFromDatabase() {
HashMap<String, List<String>> data_to_retrieve = new HashMap<String, List<String>>();
Statement statement = null;
ResultSet results = null;
Connection conn = null;
String retrieval_query = "SELECT * FROM users";
logger.info("Constructed query to return all information in the user database");
try {
conn = ConnectionUtil.getConnection();
statement = conn.createStatement();
results = statement.executeQuery(retrieval_query);
logger.info("Retrieved all user data from database and stored in results");
String this_username;
String this_name;
String this_funds;
String this_password;
List<String> data_array;
while (results.next()) {
this_username = results.getString("user_name");
this_name = results.getString("name");
this_funds = results.getString("funds");
this_password = results.getString("user_password");
data_array = Arrays.asList(this_username, this_name, this_funds, this_password);
data_to_retrieve.put(this_username, data_array);
logger.info("Retrieved all relevant information and inserted into HashMap for service layer to user for user: " + this_username);
}
} catch (SQLException e) {
logger.debug("Received an SQL exception when attempting to retrieve user information from the database");
e.printStackTrace();
} finally {
try {
results.close();
statement.close();
conn.close();
} catch (SQLException e) {
logger.debug("Received an SQL exception when attempting to close connection after retrieving user information from the database");
e.printStackTrace();
}
}
logger.info("Returning Hashmap of user data from database for service layer to use");
return data_to_retrieve;
}
private String insertTableEntry(List<String> entry_data) {
String query_string;
// For a user that does not exist in the database
query_string = "INSERT INTO users " + "(user_name, name, funds, user_password) " + "VALUES "
+ "('entry_username', 'entry_name', 'entry_funds', 'entry_password');";
query_string = query_string.replaceAll("entry_username", entry_data.get(0));
query_string = query_string.replaceAll("entry_name", entry_data.get(1));
query_string = query_string.replaceAll("entry_funds", entry_data.get(2));
query_string = query_string.replaceAll("entry_password", entry_data.get(3));
logger.info("Insertion query for new user generated");
logger.info("Constructed query: " + query_string);
return query_string;
}
private String updateTableEntry(List<String> entry_data) {
String query_string;
// For a user that already is in the database
query_string = "UPDATE users " + "SET user_name = 'entry_username', " + "name = 'entry_name', "
+ "funds = 'entry_funds', " + "user_password = 'entry_password' "
+ "WHERE user_name = 'entry_username';";
query_string = query_string.replaceAll("entry_username", entry_data.get(0));
query_string = query_string.replaceAll("entry_name", entry_data.get(1));
query_string = query_string.replaceAll("entry_funds", entry_data.get(2));
query_string = query_string.replaceAll("entry_password", entry_data.get(3));
logger.info("Update query for existing user generated");
logger.info("Constructed query: " + query_string);
return query_string;
}
public void addToTransactionHistory(List<String> transaction_history_data_entry) {
this.transaction_history_data.add(transaction_history_data_entry);
logger.info("Added new entry to repository layer's transaction history that was passed from the service layer");
}
private void insertToTransactionHistoryTable() {
String entry_query;
Statement statement = null;
Connection conn = null;
logger.info("Now iterating through all stored transaction history data to be entered into transaction history table");
for (List<String> update_item : this.transaction_history_data) {
entry_query = "INSERT INTO transaction_history (reference_user, prior_amount, transfer_amount, new_amount, transaction_time) "
+ "VALUES ('entry_user_name', 'entry_prior_amount', 'entry_transfer_amount', 'entry_new_amount', 'entry_timestamp');";
entry_query = entry_query.replaceAll("entry_user_name", update_item.get(0));
entry_query = entry_query.replaceAll("entry_prior_amount", update_item.get(1));
entry_query = entry_query.replaceAll("entry_transfer_amount", update_item.get(2));
entry_query = entry_query.replaceAll("entry_new_amount", update_item.get(3));
entry_query = entry_query.replaceAll("entry_timestamp", update_item.get(4));
logger.info("Constructed insertion query for new data entry for transaction history");
logger.info("Constructed query: " + entry_query);
try {
conn = ConnectionUtil.getConnection();
statement = conn.createStatement();
statement.executeUpdate(entry_query);
logger.info("Successfully executed query");
} catch (SQLException e) {
logger.debug("SQL Exception occured when attempting to insert transaction history entry to the database");
e.printStackTrace();
} finally {
try {
statement.close();
conn.close();
} catch (SQLException e) {
logger.debug("SQL Exception occured when attempting to close connection after inserting transaction history entry to the database");
e.printStackTrace();
}
}
}
this.transaction_history_data.clear();
logger.info("Clearing transaction history array after adding all entries (avoids duplicate entries)");
}
}
|
UTF-8
|
Java
| 10,493 |
java
|
DatabaseBridge.java
|
Java
|
[
{
"context": "unds, user_password) \" + \"VALUES \"\n\t\t\t\t+ \"('entry_username', 'entry_name', 'entry_funds', 'entry_password');",
"end": 7011,
"score": 0.6280390024185181,
"start": 7003,
"tag": "USERNAME",
"value": "username"
},
{
"context": "string = \"UPDATE users \" + \"SET user_name = 'entry_username', \" + \"name = 'entry_name', \"\n\t\t\t\t+ \"funds = 'ent",
"end": 7712,
"score": 0.8384428024291992,
"start": 7704,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\t\t+ \"funds = 'entry_funds', \" + \"user_password = 'entry_password' \"\n\t\t\t\t+ \"WHERE user_name = 'entry_username';\";\n\t",
"end": 7809,
"score": 0.9990592002868652,
"start": 7795,
"tag": "PASSWORD",
"value": "entry_password"
},
{
"context": "entry_password' \"\n\t\t\t\t+ \"WHERE user_name = 'entry_username';\";\n\t\tquery_string = query_string.replaceAll(\"ent",
"end": 7853,
"score": 0.5756760239601135,
"start": 7845,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package com.revature.repository;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import com.revature.service.RetrievalLayer;
public class DatabaseBridge {
static final Logger logger = Logger.getLogger(DatabaseBridge.class);
private List<List<String>> transaction_history_data = new ArrayList<List<String>>();
public void sendToUserDatabase(HashMap<String, List<String>> data_to_send) {
Statement statement = null;
ResultSet results = null;
Connection conn = null;
logger.info("Now iterating through update data passed from service layer");
for (List<String> user_data : data_to_send.values()) {
String query_string;
// Check if there is already an entry in the database for the username
query_string = "SELECT * FROM users WHERE users.user_name = 'entry_username';";
query_string = query_string.replaceAll("entry_username", user_data.get(0));
logger.info("Attempting to determine if user is currently in the table");
logger.info("Query to be sent to the database: " + query_string);
try {
conn = ConnectionUtil.getConnection();
statement = conn.createStatement();
results = statement.executeQuery(query_string);
if (results.next()) {
logger.info("Selected user is currently in the table - will update entry");
query_string = this.updateTableEntry(user_data);
logger.info("Query to perform: " + query_string);
} else {
logger.info("Selected user is not currently in the table - will insert entry");
query_string = this.insertTableEntry(user_data);
logger.info("Query to perform: " + query_string);
}
statement.executeUpdate(query_string);
logger.info("Query has been handled");
} catch (SQLException e) {
logger.debug("There was an SQL exception when attempting to save to the database");
e.printStackTrace();
} finally {
try {
results.close();
statement.close();
conn.close();
} catch (SQLException e) {
logger.debug("There was an SQL exception when attempting to close the connection while saving to the database");
e.printStackTrace();
}
}
}
logger.info("After updating user table, now updating transaction history table");
insertToTransactionHistoryTable();
logger.info("Successfully updated transaction history table from function sendToDatabase");
}
public List<List<String>> retrieveFromTransactionHistory(String user_key) {
logger.info("Inserting known values into the transaction history table before retrieving information");
this.insertToTransactionHistoryTable();
List<List<String>> transaction_history_for_a_user = new ArrayList<List<String>>();
Statement statement = null;
ResultSet results = null;
Connection conn = null;
String retrieval_query = "SELECT prior_amount, transfer_amount, new_amount, transaction_time "
+ "FROM transaction_history "
+ "WHERE reference_user = 'user_key' "
+ "ORDER BY transaction_time DESC;";
retrieval_query = retrieval_query.replaceAll("user_key", user_key);
logger.info("Constructed query to retrieve transaction history for user");
logger.info("Constructed query: " + retrieval_query);
try {
conn = ConnectionUtil.getConnection();
statement = conn.createStatement();
results = statement.executeQuery(retrieval_query);
String prior_amount;
String transfer_amount;
String new_amount;
String transaction_time;
List<String> data_array;
while(results.next()) {
prior_amount = results.getString("prior_amount");
transfer_amount = results.getString("transfer_amount");
new_amount = results.getString("new_amount");
transaction_time = results.getString("transaction_time");
logger.info("Extracted and formatted relevant user data from transaction history table");
data_array = Arrays.asList(prior_amount, transfer_amount, new_amount, transaction_time);
transaction_history_for_a_user.add(data_array);
logger.info("Added the value to the array of user transaction history to be returned to service layer (note: implicitly ordered by query)");
}
}
catch (SQLException e) {
logger.debug("There was an SQL exception when attempting to retrieve transaction history from the database");
e.printStackTrace();
}
finally {
try {
results.close();
statement.close();
conn.close();
} catch (SQLException e) {
logger.debug("There was an SQL exception when attempting to close connection after retrieving transaction history from the database");
e.printStackTrace();
}
}
logger.info("Returning array of user's transaction history for user by the service layer");
return transaction_history_for_a_user;
}
public HashMap<String, List<String>> retrieveFromDatabase() {
HashMap<String, List<String>> data_to_retrieve = new HashMap<String, List<String>>();
Statement statement = null;
ResultSet results = null;
Connection conn = null;
String retrieval_query = "SELECT * FROM users";
logger.info("Constructed query to return all information in the user database");
try {
conn = ConnectionUtil.getConnection();
statement = conn.createStatement();
results = statement.executeQuery(retrieval_query);
logger.info("Retrieved all user data from database and stored in results");
String this_username;
String this_name;
String this_funds;
String this_password;
List<String> data_array;
while (results.next()) {
this_username = results.getString("user_name");
this_name = results.getString("name");
this_funds = results.getString("funds");
this_password = results.getString("user_password");
data_array = Arrays.asList(this_username, this_name, this_funds, this_password);
data_to_retrieve.put(this_username, data_array);
logger.info("Retrieved all relevant information and inserted into HashMap for service layer to user for user: " + this_username);
}
} catch (SQLException e) {
logger.debug("Received an SQL exception when attempting to retrieve user information from the database");
e.printStackTrace();
} finally {
try {
results.close();
statement.close();
conn.close();
} catch (SQLException e) {
logger.debug("Received an SQL exception when attempting to close connection after retrieving user information from the database");
e.printStackTrace();
}
}
logger.info("Returning Hashmap of user data from database for service layer to use");
return data_to_retrieve;
}
private String insertTableEntry(List<String> entry_data) {
String query_string;
// For a user that does not exist in the database
query_string = "INSERT INTO users " + "(user_name, name, funds, user_password) " + "VALUES "
+ "('entry_username', 'entry_name', 'entry_funds', 'entry_password');";
query_string = query_string.replaceAll("entry_username", entry_data.get(0));
query_string = query_string.replaceAll("entry_name", entry_data.get(1));
query_string = query_string.replaceAll("entry_funds", entry_data.get(2));
query_string = query_string.replaceAll("entry_password", entry_data.get(3));
logger.info("Insertion query for new user generated");
logger.info("Constructed query: " + query_string);
return query_string;
}
private String updateTableEntry(List<String> entry_data) {
String query_string;
// For a user that already is in the database
query_string = "UPDATE users " + "SET user_name = 'entry_username', " + "name = 'entry_name', "
+ "funds = 'entry_funds', " + "user_password = '<PASSWORD>' "
+ "WHERE user_name = 'entry_username';";
query_string = query_string.replaceAll("entry_username", entry_data.get(0));
query_string = query_string.replaceAll("entry_name", entry_data.get(1));
query_string = query_string.replaceAll("entry_funds", entry_data.get(2));
query_string = query_string.replaceAll("entry_password", entry_data.get(3));
logger.info("Update query for existing user generated");
logger.info("Constructed query: " + query_string);
return query_string;
}
public void addToTransactionHistory(List<String> transaction_history_data_entry) {
this.transaction_history_data.add(transaction_history_data_entry);
logger.info("Added new entry to repository layer's transaction history that was passed from the service layer");
}
private void insertToTransactionHistoryTable() {
String entry_query;
Statement statement = null;
Connection conn = null;
logger.info("Now iterating through all stored transaction history data to be entered into transaction history table");
for (List<String> update_item : this.transaction_history_data) {
entry_query = "INSERT INTO transaction_history (reference_user, prior_amount, transfer_amount, new_amount, transaction_time) "
+ "VALUES ('entry_user_name', 'entry_prior_amount', 'entry_transfer_amount', 'entry_new_amount', 'entry_timestamp');";
entry_query = entry_query.replaceAll("entry_user_name", update_item.get(0));
entry_query = entry_query.replaceAll("entry_prior_amount", update_item.get(1));
entry_query = entry_query.replaceAll("entry_transfer_amount", update_item.get(2));
entry_query = entry_query.replaceAll("entry_new_amount", update_item.get(3));
entry_query = entry_query.replaceAll("entry_timestamp", update_item.get(4));
logger.info("Constructed insertion query for new data entry for transaction history");
logger.info("Constructed query: " + entry_query);
try {
conn = ConnectionUtil.getConnection();
statement = conn.createStatement();
statement.executeUpdate(entry_query);
logger.info("Successfully executed query");
} catch (SQLException e) {
logger.debug("SQL Exception occured when attempting to insert transaction history entry to the database");
e.printStackTrace();
} finally {
try {
statement.close();
conn.close();
} catch (SQLException e) {
logger.debug("SQL Exception occured when attempting to close connection after inserting transaction history entry to the database");
e.printStackTrace();
}
}
}
this.transaction_history_data.clear();
logger.info("Clearing transaction history array after adding all entries (avoids duplicate entries)");
}
}
| 10,489 | 0.709902 | 0.708472 | 270 | 37.862965 | 34.758743 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.444444 | false | false |
0
|
66f802606d536db7d18ee10b8178d1684bb6c3c7
| 10,445,360,517,663 |
192edd63bdca9162f9491118f3d1d8a86266be54
|
/src/main/java/org/jtrfp/mtmx/internal/VboUtil.java
|
033f3c2526eafb50b7bf77d18e28959869e6ef2a
|
[] |
no_license
|
jtrfp/mtmx-java
|
https://github.com/jtrfp/mtmx-java
|
d983d728629f1d1d4a9e190d4557738651988203
|
64462871f232379f91d8f0cb04e7c491a29e339d
|
refs/heads/master
| 2021-12-31T14:19:18.188000 | 2014-03-05T09:01:49 | 2014-03-05T09:01:49 | 10,239,433 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* This file is part of mtmX.
*
* mtmX 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 3 of the License, or
* (at your option) any later version.
*
* mtmX 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 mtmX. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jtrfp.mtmx.internal;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.jtrfp.jtrfp.clr.IClrData;
import org.jtrfp.mtmx.EngineUtil;
import org.jtrfp.mtmx.draw.IDrawer;
import org.jtrfp.mtmx.terrain.ITerrainMap;
import org.lwjgl.util.vector.Vector3f;
public final class VboUtil {
private final ITerrainMap map;
private final IClrData clrData;
private int[] sizes;
public VboUtil(ITerrainMap map, IClrData clrData) {
this.map = map;
this.clrData = clrData;
}
public static int indexBufferSize(ITerrainMap map) {
final int w = map.getWidth();
final int h = map.getHeight();
return (w - 1) * (h - 1) * 2 * 3;
}
public IntBuffer createIndexBuffer() {
final int w = map.getWidth();
final int h = map.getHeight();
int[] indexBuffer = new int[indexBufferSize(map)];
int texCount = clrData.getColorCount();
sizes = new int[texCount];
int z = 0;
for (int c = 0; c < texCount; c++) {
int size = 0;
for (int i = 0; i < w - 1; i++) {
for (int j = 0; j < h - 1; j++) {
int texNum = clrData.getColorAt(i, j);
if (texNum == c) {
final int jw = j * w;
final int j1w = (j + 1) * w;
// triangle 1
indexBuffer[z] = (jw + (i + 1));
z++;
indexBuffer[z] = (jw + i);
z++;
indexBuffer[z] = (j1w + i);
z++;
// triangle 2
indexBuffer[z] = (j1w + (i + 1));
z++;
indexBuffer[z] = (jw + (i + 1));
z++;
indexBuffer[z] = (j1w + i);
z++;
size++;
}
}
}
sizes[c] = size * 6;
}
int maxIndex = 0;
for (int i = 0; i < indexBufferSize(map); i++) {
if (indexBuffer[i] > maxIndex) {
maxIndex = indexBuffer[i];
}
}
System.out.println(
"Created index buffer with " + z + " indexes "
+ " (" + (z / 3) + " triangles) using " + (maxIndex + 1) + " vertexes.");
return EngineUtil.createIntBuffer(indexBuffer);
}
public FloatBuffer createVertexBuffer() {
final int w = map.getWidth();
final int h = map.getHeight();
float[] vertexBuffer = new float[w * h * 3];
int z = 0;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
int e = map.getElevationAt(j, i);
vertexBuffer[z] = j * IDrawer.WORLD_SCALE_XZ;
z++;
vertexBuffer[z] = e * IDrawer.WORLD_SCALE_Y;
z++;
vertexBuffer[z] = i * IDrawer.WORLD_SCALE_XZ;
z++;
}
}
System.out.println(
"Created vertex buffer with " + z + " coords and " + (z / 3) + " vertexes.");
return EngineUtil.createFloatBuffer(vertexBuffer);
}
public FloatBuffer createNormalBuffer() {
final int w = map.getWidth();
final int h = map.getHeight();
float[] vertexBuffer = new float[w * h * 3];
int q = 0;
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
Vector3f sum = new Vector3f(0.0f, 0.0f, 0.0f);
Vector3f out = new Vector3f(0.0f, 0.0f, 0.0f);
if (y > 0) {
int eOut = map.getElevationAt(x, y - 1) - map.getElevationAt(x, y);
out = new Vector3f(1.0f, eOut, 0.0f);
}
Vector3f in = new Vector3f(0.0f, 0.0f, 0.0f);
if (y < h - 1) {
int eIn = map.getElevationAt(x, y + 1) - map.getElevationAt(x, y);
in = new Vector3f(-1.0f, eIn, 0.0f);
}
Vector3f left = new Vector3f(0.0f, 0.0f, 0.0f);
if (x > 0) {
int eLeft = map.getElevationAt(x - 1, y) - map.getElevationAt(x, y);
left = new Vector3f(0.0f, eLeft, -1.0f);
}
Vector3f right = new Vector3f(0.0f, 0.0f, 0.0f);
if (x < w - 1) {
int eRight = map.getElevationAt(x + 1, y) - map.getElevationAt(x, y);
right = new Vector3f(0.0f, eRight, 1.0f);
}
Vector3f res = new Vector3f();
if (x > 0 && y > 0) {
Vector3f.cross(out, left, res);
Vector3f.add(sum, res, sum);
// sum += out.cross(left).normalise();
}
if (x > 0 && y < h - 1) {
Vector3f.cross(left, in, res);
Vector3f.add(sum, res, sum);
// sum += left.cross(in).normalise();
}
if (x < w - 1 && y < h - 1) {
Vector3f.cross(in, right, res);
Vector3f.add(sum, res, sum);
// sum += in.cross(right).normalise();
}
if (x < w - 1 && y > 0) {
Vector3f.cross(right, out, res);
Vector3f.add(sum, res, sum);
// sum += right.cross(out).normalise();
}
sum.normalise(sum);
//sum.negate(sum);
vertexBuffer[q] = sum.x;
q++;
vertexBuffer[q] = sum.y;
q++;
vertexBuffer[q] = sum.z;
q++;
}
}
return EngineUtil.createFloatBuffer(vertexBuffer);
}
public FloatBuffer createTexCoordBuffer() {
final int w = map.getWidth();
final int h = map.getHeight();
float[] texBuffer = new float[w * h * 2];
int z = 0;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
texBuffer[z] = i * 1.0f;
z++;
texBuffer[z] = -j * 1.0f;
z++;
}
}
return EngineUtil.createFloatBuffer(texBuffer);
}
public int[] getSizes() {
return sizes;
}
}
|
UTF-8
|
Java
| 5,569 |
java
|
VboUtil.java
|
Java
|
[] | null |
[] |
/*
* This file is part of mtmX.
*
* mtmX 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 3 of the License, or
* (at your option) any later version.
*
* mtmX 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 mtmX. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jtrfp.mtmx.internal;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.jtrfp.jtrfp.clr.IClrData;
import org.jtrfp.mtmx.EngineUtil;
import org.jtrfp.mtmx.draw.IDrawer;
import org.jtrfp.mtmx.terrain.ITerrainMap;
import org.lwjgl.util.vector.Vector3f;
public final class VboUtil {
private final ITerrainMap map;
private final IClrData clrData;
private int[] sizes;
public VboUtil(ITerrainMap map, IClrData clrData) {
this.map = map;
this.clrData = clrData;
}
public static int indexBufferSize(ITerrainMap map) {
final int w = map.getWidth();
final int h = map.getHeight();
return (w - 1) * (h - 1) * 2 * 3;
}
public IntBuffer createIndexBuffer() {
final int w = map.getWidth();
final int h = map.getHeight();
int[] indexBuffer = new int[indexBufferSize(map)];
int texCount = clrData.getColorCount();
sizes = new int[texCount];
int z = 0;
for (int c = 0; c < texCount; c++) {
int size = 0;
for (int i = 0; i < w - 1; i++) {
for (int j = 0; j < h - 1; j++) {
int texNum = clrData.getColorAt(i, j);
if (texNum == c) {
final int jw = j * w;
final int j1w = (j + 1) * w;
// triangle 1
indexBuffer[z] = (jw + (i + 1));
z++;
indexBuffer[z] = (jw + i);
z++;
indexBuffer[z] = (j1w + i);
z++;
// triangle 2
indexBuffer[z] = (j1w + (i + 1));
z++;
indexBuffer[z] = (jw + (i + 1));
z++;
indexBuffer[z] = (j1w + i);
z++;
size++;
}
}
}
sizes[c] = size * 6;
}
int maxIndex = 0;
for (int i = 0; i < indexBufferSize(map); i++) {
if (indexBuffer[i] > maxIndex) {
maxIndex = indexBuffer[i];
}
}
System.out.println(
"Created index buffer with " + z + " indexes "
+ " (" + (z / 3) + " triangles) using " + (maxIndex + 1) + " vertexes.");
return EngineUtil.createIntBuffer(indexBuffer);
}
public FloatBuffer createVertexBuffer() {
final int w = map.getWidth();
final int h = map.getHeight();
float[] vertexBuffer = new float[w * h * 3];
int z = 0;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
int e = map.getElevationAt(j, i);
vertexBuffer[z] = j * IDrawer.WORLD_SCALE_XZ;
z++;
vertexBuffer[z] = e * IDrawer.WORLD_SCALE_Y;
z++;
vertexBuffer[z] = i * IDrawer.WORLD_SCALE_XZ;
z++;
}
}
System.out.println(
"Created vertex buffer with " + z + " coords and " + (z / 3) + " vertexes.");
return EngineUtil.createFloatBuffer(vertexBuffer);
}
public FloatBuffer createNormalBuffer() {
final int w = map.getWidth();
final int h = map.getHeight();
float[] vertexBuffer = new float[w * h * 3];
int q = 0;
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
Vector3f sum = new Vector3f(0.0f, 0.0f, 0.0f);
Vector3f out = new Vector3f(0.0f, 0.0f, 0.0f);
if (y > 0) {
int eOut = map.getElevationAt(x, y - 1) - map.getElevationAt(x, y);
out = new Vector3f(1.0f, eOut, 0.0f);
}
Vector3f in = new Vector3f(0.0f, 0.0f, 0.0f);
if (y < h - 1) {
int eIn = map.getElevationAt(x, y + 1) - map.getElevationAt(x, y);
in = new Vector3f(-1.0f, eIn, 0.0f);
}
Vector3f left = new Vector3f(0.0f, 0.0f, 0.0f);
if (x > 0) {
int eLeft = map.getElevationAt(x - 1, y) - map.getElevationAt(x, y);
left = new Vector3f(0.0f, eLeft, -1.0f);
}
Vector3f right = new Vector3f(0.0f, 0.0f, 0.0f);
if (x < w - 1) {
int eRight = map.getElevationAt(x + 1, y) - map.getElevationAt(x, y);
right = new Vector3f(0.0f, eRight, 1.0f);
}
Vector3f res = new Vector3f();
if (x > 0 && y > 0) {
Vector3f.cross(out, left, res);
Vector3f.add(sum, res, sum);
// sum += out.cross(left).normalise();
}
if (x > 0 && y < h - 1) {
Vector3f.cross(left, in, res);
Vector3f.add(sum, res, sum);
// sum += left.cross(in).normalise();
}
if (x < w - 1 && y < h - 1) {
Vector3f.cross(in, right, res);
Vector3f.add(sum, res, sum);
// sum += in.cross(right).normalise();
}
if (x < w - 1 && y > 0) {
Vector3f.cross(right, out, res);
Vector3f.add(sum, res, sum);
// sum += right.cross(out).normalise();
}
sum.normalise(sum);
//sum.negate(sum);
vertexBuffer[q] = sum.x;
q++;
vertexBuffer[q] = sum.y;
q++;
vertexBuffer[q] = sum.z;
q++;
}
}
return EngineUtil.createFloatBuffer(vertexBuffer);
}
public FloatBuffer createTexCoordBuffer() {
final int w = map.getWidth();
final int h = map.getHeight();
float[] texBuffer = new float[w * h * 2];
int z = 0;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
texBuffer[z] = i * 1.0f;
z++;
texBuffer[z] = -j * 1.0f;
z++;
}
}
return EngineUtil.createFloatBuffer(texBuffer);
}
public int[] getSizes() {
return sizes;
}
}
| 5,569 | 0.576944 | 0.553421 | 219 | 24.429224 | 20.613607 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.360731 | false | false |
0
|
07ccdb594aac9684c84a4d3611ceb9474f30d723
| 4,355,096,870,974 |
397c399b0ee8436a6b5bc0aa710853cd09273ccb
|
/src/main/java/com/example/MathController.java
|
433196153aeebbb794eeee18e6ee0ec16632f3a9
|
[] |
no_license
|
Geist732/Blog
|
https://github.com/Geist732/Blog
|
a5826891a448773ee7b5912dc038fc4128c572e8
|
f327bb99fa103dcd85f12079efcf63bbd2e93c1c
|
refs/heads/master
| 2021-04-29T03:49:49.729000 | 2017-01-13T20:30:33 | 2017-01-13T20:30:33 | 78,035,645 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MathController {
@GetMapping("/add/{number1}/and/{number2}")
@ResponseBody
public String add(@PathVariable int number1, @PathVariable int number2){
int sum = number1 + number2;
return number1 + " plus " + number2 + " equals: " + sum;
}
@GetMapping("/subtract/{number1}/from/{number2}")
@ResponseBody
public String subtract(@PathVariable int number1, @PathVariable int number2){
int remainder = number2 - number1;
return number1 + " from " + number2 + " equals: " + remainder;
}
@GetMapping("/multiply/{number1}/and/{number2}")
@ResponseBody
public String multiply(@PathVariable int number1, @PathVariable int number2){
int product = number1 * number2;
return number1 + " multiplied by " + number2 + " equals: " + product;
}
@GetMapping("/divide/{number1}/by/{number2}")
@ResponseBody
public String divide(@PathVariable int number1, @PathVariable int number2){
int remainder = number1 * number2;
return number1 + " divided by " + number2 + " equals: " + remainder;
}
}
|
UTF-8
|
Java
| 1,378 |
java
|
MathController.java
|
Java
|
[] | null |
[] |
package com.example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MathController {
@GetMapping("/add/{number1}/and/{number2}")
@ResponseBody
public String add(@PathVariable int number1, @PathVariable int number2){
int sum = number1 + number2;
return number1 + " plus " + number2 + " equals: " + sum;
}
@GetMapping("/subtract/{number1}/from/{number2}")
@ResponseBody
public String subtract(@PathVariable int number1, @PathVariable int number2){
int remainder = number2 - number1;
return number1 + " from " + number2 + " equals: " + remainder;
}
@GetMapping("/multiply/{number1}/and/{number2}")
@ResponseBody
public String multiply(@PathVariable int number1, @PathVariable int number2){
int product = number1 * number2;
return number1 + " multiplied by " + number2 + " equals: " + product;
}
@GetMapping("/divide/{number1}/by/{number2}")
@ResponseBody
public String divide(@PathVariable int number1, @PathVariable int number2){
int remainder = number1 * number2;
return number1 + " divided by " + number2 + " equals: " + remainder;
}
}
| 1,378 | 0.682148 | 0.658926 | 37 | 36.243244 | 28.173599 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459459 | false | false |
0
|
40762b0c5faf876a97e5ceba49f0ff2bd4c4abfd
| 38,001,870,647,150 |
69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e
|
/methods/Method_10598.java
|
6b7218b55ff224ca57bf15fc2b621f33e59789b8
|
[] |
no_license
|
P79N6A/icse_20_user_study
|
https://github.com/P79N6A/icse_20_user_study
|
5b9c42c6384502fdc9588430899f257761f1f506
|
8a3676bc96059ea2c4f6d209016f5088a5628f3c
|
refs/heads/master
| 2020-06-24T08:25:22.606000 | 2019-07-25T15:31:16 | 2019-07-25T15:31:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
@Override public byte[] getMatrix(){
return bitmapPixels;
}
|
UTF-8
|
Java
| 62 |
java
|
Method_10598.java
|
Java
|
[] | null |
[] |
@Override public byte[] getMatrix(){
return bitmapPixels;
}
| 62 | 0.725806 | 0.725806 | 3 | 19.666666 | 14.383633 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
0
|
141f49a4066cd9d2799c5e7551017aca77616d34
| 36,301,063,610,875 |
82ac963a83b7f7e67af891f1358536b201d577e7
|
/csvfile/src/main/java/wj/csv/controller/ExceptionController.java
|
5698a7751df7d41cba86ad9660fd64ac21e3ee73
|
[] |
no_license
|
womenr/homework
|
https://github.com/womenr/homework
|
01220dcb57bc35e2ccbce1075ada2d9b9b8a3719
|
33bef3f35d735b50dce7c1d399f080383e14007f
|
refs/heads/master
| 2020-03-19T17:49:02.477000 | 2018-10-21T10:29:19 | 2018-10-21T10:29:19 | 136,779,346 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package wj.csv.controller;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import wj.csv.Exception.CustomException;
@Controller
public class ExceptionController {
@RequestMapping(value = "/{type}", method = RequestMethod.GET)
public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{
if ("error".equals(type)) {
// 由handleCustomException处理
throw new CustomException("E888", "This is custom message");
} else if ("io-error".equals(type)) {
// 由handleAllException处理
throw new IOException();
} else {
return new ModelAndView("index").addObject("msg", type);
}
}
}
|
UTF-8
|
Java
| 1,033 |
java
|
ExceptionController.java
|
Java
|
[] | null |
[] |
package wj.csv.controller;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import wj.csv.Exception.CustomException;
@Controller
public class ExceptionController {
@RequestMapping(value = "/{type}", method = RequestMethod.GET)
public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{
if ("error".equals(type)) {
// 由handleCustomException处理
throw new CustomException("E888", "This is custom message");
} else if ("io-error".equals(type)) {
// 由handleAllException处理
throw new IOException();
} else {
return new ModelAndView("index").addObject("msg", type);
}
}
}
| 1,033 | 0.670911 | 0.667973 | 29 | 33.206898 | 26.539988 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.517241 | false | false |
0
|
acd18b119fc69a430e1a2c1a2749ff05511ba120
| 36,301,063,613,662 |
ec2eab135a767bbf81e89a7fdb016f55b8c1df17
|
/src/main/java/com/warn/service/impl/StatisticServiceImpl.java
|
26a9e4879a3577429d4a4cc681e3742aac9913ef
|
[] |
no_license
|
typeyuki/warn2.0
|
https://github.com/typeyuki/warn2.0
|
43254f5172c045622e3d98db58e23a7ee7de143e
|
5f4723d4fe0c746e4323362f03e4d08745b8955c
|
refs/heads/master
| 2022-12-22T00:37:24.139000 | 2019-10-16T01:29:42 | 2019-10-16T01:29:42 | 165,332,819 | 1 | 0 | null | false | 2022-12-16T07:51:46 | 2019-01-12T01:23:12 | 2020-07-30T13:02:01 | 2022-12-16T07:51:43 | 88,054 | 0 | 0 | 13 |
JavaScript
| false | false |
package com.warn.service.impl;
import com.warn.dao.DataDao;
import com.warn.dao.RoomDao;
import com.warn.dao.StatisticDao;
import com.warn.dao.ThresholdDao;
import com.warn.dto.DwrData;
import com.warn.dto.Warn_statistic;
import com.warn.dto.visual.AreaVisual;
import com.warn.dto.visual.AreaVisualList;
import com.warn.dto.visual.AreaVisualLists;
import com.warn.dwr.Remote;
import com.warn.entity.*;
import com.warn.mongodb.model.SensorCollection;
import com.warn.sensordata.dao.SensorMogoSecDao;
import com.warn.service.SensorService;
import com.warn.service.StatisticService;
import com.warn.service.WarnHistoryService;
import com.warn.util.DynamicDataSourceHolder;
import com.warn.util.Tool.Tool;
import org.omg.CORBA.MARSHAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Service
public class StatisticServiceImpl implements StatisticService {
@Autowired
SensorMogoSecDao sensorMogoSecDao;
@Autowired
DataDao dataDao;
@Autowired
RoomDao roomDao;
@Autowired
StatisticDao statisticDao;
@Autowired
ThresholdDao thresholdDao;
@Autowired
WarnHistoryService warnHistoryService;
// public static Map<OldMan,Boolean> doorS=new HashMap<OldMan,Boolean>();//存储老人是否出门了(门动的时间) 出门了就不在计数;
public static Map<Integer,Boolean> out = new HashMap<>();//initial false
public static Map<Integer,Boolean> judge = new HashMap<>();//initial false
public static Map<Integer,Boolean> key = new HashMap<>();//initial true
//public static Map<String,Integer> AreaNum = new HashMap<>();
@Override
public void getStatisticData(Integer gatewayId){
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String current = date.format(new Date());//现在的时间
String yesterday = date.format(new Date().getTime() - 86400000);
String start = yesterday.split(" ")[0] + " " + "20:00:00";
String end = current.split(" ")[0] + " " + "20:00:00";
String today = current.split(" ")[0];
OldMan oldMan = dataDao.getOldManByGatewayID(gatewayId);
List<Room> roomList = roomDao.getAllRoomByOldManId(oldMan.getOid());
Integer rSize = roomList.size();
List<AreaStatistic> areaStatistics = statisticDao.getStatisticByDate(today,oldMan.getOid());
Integer areas[][] = new Integer[11][11];
String statisticInfo[] = new String[11];
for(Room room:roomList) {//更新,先获取今天的数据,如果没有就从零开始
if (areaStatistics.size() == 0){
for (int j = 0; j <= 10; j++) {
areas[Integer.parseInt(room.getCollectId())][j] = 0;//collectId即每个采集点、就是房间
areas[0][10] = 0;
areas[0][0] = 0;
}
out.put(gatewayId,false);
judge.put(gatewayId,false);
key.put(gatewayId,true);
}
else{
for (AreaStatistic areaStatistic : areaStatistics) {
if(areaStatistic.getRoomId() == room.getRid()){
String tempArea[] = areaStatistic.getStatisticInfo().split("#");
areas[Integer.parseInt(room.getCollectId())][0] = 0;//把户外设为0?
for(int j = 0; j <= 10 ; j++)
areas[Integer.parseInt(room.getCollectId())][j] = Integer.parseInt(tempArea[j]);
}
}
start = areaStatistics.get(0).getTime();
}
}
List<Integer> sensorPointIds = new ArrayList<>();
for(Room room:roomList){
sensorPointIds.add(Integer.parseInt(room.getCollectId()));
}
// String now = date.format(new Date());//现在的时间
// String startOfDay = now.split(" ")[0] + " " + "00:00:00";//当天的开始
// String endOfDay = now.split(" ")[0] + " " + "23:59:59";//当天的结束
// Long fTime = date.parse(startOfDay).getTime();//转换成时间戳
// Long nTime = date.parse(now).getTime();
// Long eTime = date.parse(endOfDay).getTime();
//Integer limit = 3600 / 30 * roomList.size()+20;
// List<SensorCollection> sensorCollections = sensorMogoSecDao.findToStatistic(gatewayId, sensorPointIds,limit);
List<SensorCollection> sensorCollections = sensorMogoSecDao.findToStatisticBeta(gatewayId,sensorPointIds,start,end);
Set<String> zero = new HashSet<>();
// for(int i = limit - 1; i >=0 ; i--){
Integer tempY = 10;//用来标其他区域
Integer tempX = 0;//同上
for(int i=0;i<sensorCollections.size();i++){
SensorCollection sensorCollection = sensorCollections.get(i);
if(judge.get(gatewayId))//衔接上一个时间段的出门的判断
for(int j = i;j <= rSize * 2 * 2;j ++){
SensorCollection sensorCollection1 = sensorCollections.get(i+j);
if(sensorCollection1.getSensorID() == 1)
if(sensorCollection1.getSensorData() != 0){
out.put(gatewayId,false);//没出门
break;
}
if(j == rSize * 4)
out.put(gatewayId,true);//出门了
}
if(sensorCollection.getSensorID() == 1){//如果是行为数据
if(sensorCollection.getSensorData() == 0){
zero.add(sensorCollection.getSensorPointID());
if(zero.size() == rSize ){//出门了就户外,没出门就算其他区域
if(!out.get(gatewayId))
areas[tempX][tempY]++;
else
areas[0][0]++;
zero.clear();
}
}
else {
areas[Integer.parseInt(sensorCollection.getSensorPointID())][sensorCollection.getSensorData()]++;//在原来的数据上加
tempX = Integer.parseInt(sensorCollection.getSensorPointID());
tempY = sensorCollection.getSensorData();
zero.clear();
out.put(gatewayId,false);
}
}else{
if(sensorCollections.size() - i < rSize * 2 * 4)
judge.put(gatewayId,true);
else
for(int j = rSize * 2 * 2; j < rSize * 8 ; j++){ //出门判断(有门的霍尔数据的2-4分钟内,房间内 没有人的数据 的话,判断为出门)
SensorCollection sensorCollection1 = sensorCollections.get(i+j);
if(sensorCollection1.getSensorID() == 1)
if(sensorCollection1.getSensorData() != 0){
out.put(gatewayId,false);//没出门
break;
}
if(j == rSize * 8)
out.put(gatewayId,true);//出门了
}
}
// Long fiTime = date.parse(firstTime).getTime()
}
for(Room room:roomList){
Integer i = Integer.parseInt(room.getCollectId());
String temp = areas[0][0].toString() + "#";
for(Integer j = 1;j <= 9;j++){
temp = temp + areas[i][j].toString() + "#";
}
temp = temp + areas[0][10].toString();
statisticInfo[i] = temp;
}
List<AreaStatistic> areaStatisticr = statisticDao.getStatisticByDate(today,oldMan.getOid());
if(areaStatisticr.size() == 0){
for(Room room:roomList){
AreaStatistic areaStatistic = new AreaStatistic();
areaStatistic.setDate(today);
areaStatistic.setTime(current);
areaStatistic.setOid(oldMan.getOid());
areaStatistic.setRoomId(room.getRid());
areaStatistic.setStatisticInfo(statisticInfo[Integer.parseInt(room.getCollectId())]);
statisticDao.addAreaStatistic(areaStatistic);
}
}else{
for(AreaStatistic areaStatistic:areaStatistics){
for(Room room:roomList){
if(room.getRid() == areaStatistic.getRoomId())
areaStatistic.setStatisticInfo(statisticInfo[Integer.parseInt(room.getCollectId())]);
}
areaStatistic.setTime(current);
statisticDao.updateAreaStatistic(areaStatistic);
}
}
}
@Override
public List<AreaVisualList> getStatisticArea(Integer oid,Integer rid,String time){
//OldMan oldMan = dataDao.getOldManByOid(oid);
Map<String,Integer> areaNum = new HashMap<>();
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String current = date.format(new Date());//现在的时间
String today = current.split(" ")[0];
List<AreaVisualList> areaVisualLists = new ArrayList<>();
List<AreaStatistic> areaStatistics = new ArrayList<>();
List<AreaVisual> areaVisuals = new ArrayList<>();
Room room1 = new Room();
if(time == null)
areaStatistics = statisticDao.getStatisticInfo(today,oid);//就算取不到也不会报Null 的异常
else
areaStatistics = statisticDao.getStatisticInfo(time,oid);
if(areaStatistics.size() != 0)
for(AreaStatistic areaStatistic:areaStatistics){
room1 = roomDao.getRoomById(areaStatistic.getRoomId());
List<AreaStatistic> areaStatistics1 = new ArrayList<>();
areaStatistics1.clear();
areaStatistics1.add(areaStatistic);
mergeVsiuals(areaStatistics1,room1,areaNum);
}
for(Map.Entry<String,Integer> entry:areaNum.entrySet()){
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(entry.getKey());
if(entry.getKey().equals("户外"))
areaVisual.setSumTime(entry.getValue() / areaStatistics.size());
else
areaVisual.setSumTime(entry.getValue());
areaVisuals.add(areaVisual);
}
AreaVisualList areaVisualList = new AreaVisualList();
areaVisualList.setAreaVisuals(areaVisuals);
areaVisualList.setRoomName("区域时间统计");
areaVisualLists.add(areaVisualList);
areaVisualLists.add(getAreaAverage(oid));
return areaVisualLists;
}
private AreaVisualList getAreaAverage(Integer oid){
Map<String,Integer> areaNum = new HashMap<>();
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat week = new SimpleDateFormat("EEEE");
date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
week.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date current = new Date();//现在的时间
List<String> dates = new ArrayList<>();
List<Room> roomList = roomDao.getAllRoomByOldManId(oid);
List<AreaVisualLists> visualLists = new ArrayList<>();
List<AreaVisual> areaVisuals = new ArrayList<>();
for(int j = 0; j < 7; j++){
dates.add(date.format(current).split(" ")[0]);
current = new Date(current.getTime() - 86400000);
}
for(Room room:roomList){
List<AreaStatistic> areaStatistics = statisticDao.getStatisitcInfos(dates,oid,room.getRid());//就算取不到也不会报Null 的异常
for(AreaStatistic areaStatistic:areaStatistics){
List<AreaStatistic> areaStatistics1 = new ArrayList<>();
areaStatistics1.clear();
areaStatistics1.add(areaStatistic);
mergeVsiuals(areaStatistics1,room,areaNum);
}
}
for(Map.Entry<String,Integer> entry:areaNum.entrySet()){
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(entry.getKey());
if(entry.getKey().equals("户外"))
areaVisual.setSumTime(entry.getValue()/(7 * roomList.size()));
else
areaVisual.setSumTime(entry.getValue()/7);
areaVisuals.add(areaVisual);
}
AreaVisualList areaVisualList = new AreaVisualList();
areaVisualList.setAreaVisuals(areaVisuals);
areaVisualList.setRoomName("周平均值");
return areaVisualList;
}
@Override
public List<AreaVisualLists> getStatisticAreaList(Integer oid,Integer rid) {
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat week = new SimpleDateFormat("EEEE");
date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
week.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date current = new Date();//现在的时间
List<String> dates = new ArrayList<>();
List<Room> roomList = roomDao.getAllRoomByOldManId(oid);
List<AreaVisualLists> visualLists = new ArrayList<>();
for(int j = 0; j < 7; j++){
dates.add(date.format(current).split(" ")[0]);
current = new Date(current.getTime() - 86400000);
}
for(Room room:roomList){
AreaVisualLists visualList = new AreaVisualLists();
List<AreaStatistic> areaStatistics = statisticDao.getStatisitcInfos(dates,oid,room.getRid());//就算取不到也不会报Null 的异常
List<AreaVisualList> areaVisualLists = new ArrayList<>();
for(AreaStatistic areaStatistic:areaStatistics){
AreaVisualList areaVisualList = new AreaVisualList();
areaVisualList.setDate(areaStatistic.getDate()+"("+week.format(current)+")");
List<AreaStatistic> areaStatistics1 = new ArrayList<>();
areaStatistics1.clear();
areaStatistics1.add(areaStatistic);
List<AreaVisual> areaVisuals = setVisuals(areaStatistics1,room);
areaVisualList.setAreaVisuals(areaVisuals);
areaVisualLists.add(areaVisualList);
current = new Date(current.getTime() - 86400000);
}
Collections.reverse(areaVisualLists);
visualList.setAreaVisual(areaVisualLists);
visualList.setRoomName(room.getRoomName());
visualLists.add(visualList);
}
return visualLists;
}
@Override
public void transferData(List<SensorData> sensorDatas){
}
// @Override
// public void checkStatistic(Integer oid,Integer rid){
// try {
// Random r = new Random();
// TimeUnit.SECONDS.sleep(r.nextInt(20));
// }catch(Exception e){
// System.out.println("timeunit wrong");
// }
// if(key){
// key = false;
// }else
// return;
// SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
// Date current = new Date();//现在的时间
// List<AreaVisualList> areaVisualLists = new ArrayList<>();
// List<AreaVisual> areaVisuals = new ArrayList<>();
// current = new Date(current.getTime() - 86400000);
// String today = date.format(new Date()).split(" ")[0];
// List<AreaStatistic> areaStatistic1 = statisticDao.getStatisticInfo(today,oid);//就算取不到也不会报Null 的异常
// Room room = roomDao.getRoomById(rid);
// List<AreaVisual> areaVisuals1 = setVisuals(areaStatistic1,room);
// for (int j = 0; j < 7; j++) {
// AreaVisualList areaVisualList = new AreaVisualList();
// String time = date.format(current).split(" ")[0];
// areaVisualList.setDate(time);
// List<AreaStatistic> areaStatistic = statisticDao.getStatisticInfo(time, oid);//就算取不到也不会报Null 的异常
// if(areaStatistic.get(0).getNormal() == 0){
// areaVisuals = setVisuals(areaStatistic,room);
// areaVisualList.setAreaVisuals(areaVisuals);
// areaVisualLists.add(areaVisualList);
// current = new Date(current.getTime() - 86400000);
// }else{
// j--;
// }
// }
// List<Threshold_statistic> threshold_statistics = thresholdDao.getThresholdSByRid(rid);
// Integer[] average = {0,0,0,0,0,0,0,0,0,0,0};
// Integer[] standard = {0,0,0,0,0,0,0,0,0,0,0};
// for(int i = 0;i <= 10;i++){
// Integer sum = 0;
// for(int j = 0;j < 7;j++){
// sum = sum + areaVisualLists.get(j).getAreaVisuals().get(i).getSumTime();
// }
// average[i] = sum / 7;
// double sumd = 0;
// double two = 2;
// for(int j = 0;j < 7;j++){
// sumd = sumd + Math.pow(areaVisualLists.get(j).getAreaVisuals().get(i).getSumTime().doubleValue()-average[i].doubleValue(),two);
// }
// standard[i] = (int)Math.sqrt(sumd/7);
// AreaVisual areaVisual = areaVisuals1.get(i);
// Integer deviation = Math.abs(areaVisual.getSumTime() - average[i]);
// Integer threshold = getThreshold(threshold_statistics,areaVisual.getAreaNumber());
// if(threshold != null)
// if((threshold == 404 && deviation > standard[i]) || (threshold!=404 && deviation > threshold)){ //报警
// Warn_statistic warn_statistic = new Warn_statistic();
// OldMan oldMan = dataDao.getOldManByOid(oid);
// warn_statistic.setOldMan(oldMan);
// warn_statistic.setRoom(room.getRoomName());
// warn_statistic.setAreaInfo(areaVisual.getAreaName());
// warn_statistic.setDate(today);
// warn_statistic.setDeviation(deviation);
// DwrData dwrData = new DwrData();
// dwrData.setType("warn_statistic");
// AreaStatistic areaStatistic = areaStatistic1.get(0);
// areaStatistic.setNormal(1);
// statisticDao.updateNormal(areaStatistic);
// dwrData.setWarn_statistic(warn_statistic);
// warnHistoryService.addWarnHistory(dwrData);
// Remote.noticeNewOrder(dwrData);
// }
// }
// key = true;
// }
private Integer getThreshold(List<Threshold_statistic> threshold_statistics,Integer num){
for(Threshold_statistic threshold_statistic:threshold_statistics){
if(threshold_statistic.getArea().equals(num))
return num;
}
return null;
}
// private void mergeVisualsD(List<AreaStatistic> areaStatistics, Room room, Map<String,Integer> areaNum,String date){
// String areaTime[] = areaStatistics.get(0).getStatisticInfo().split("#");
// for (int i = 0; i < areaTime.length; i++) {
// AreaVisual areaVisual = new AreaVisual();
// if(Tool.getPositionInfo(i,room).equals("户外"))
// areaVisual.setAreaName("户外"+"-"+date);
// else
// areaVisual.setAreaName(room.getRoomName() + ":" + Tool.getPositionInfo(i, room) + "-" + date);
// areaVisual.setAreaNumber(i);
// areaVisual.setSumTime(Integer.parseInt(areaTime[i]) / 2);//转化成分钟
// if(areaNum.containsKey(areaVisual.getAreaName())) {
// Integer sum = areaVisual.getSumTime() + areaNum.get(areaVisual.getAreaName());
// areaNum.put(areaVisual.getAreaName(),sum);
// }else
// areaNum.put(areaVisual.getAreaName(),areaVisual.getSumTime());
// }
// }
private void mergeVsiuals(List<AreaStatistic> areaStatistics,Room room,Map<String,Integer> areaNum){
if (areaStatistics.size() != 0) {
//List<Room> roomList = roomDao.getAllRoomByOldManId(oldMan.getOid());
String areaTime[] = areaStatistics.get(0).getStatisticInfo().split("#");
for (int i = 0; i < areaTime.length; i++) {
AreaVisual areaVisual = new AreaVisual();
if(Tool.getPositionInfo(i,room).equals("户外"))
areaVisual.setAreaName("户外");
else
areaVisual.setAreaName(room.getRoomName() + ":" + Tool.getPositionInfo(i, room));
areaVisual.setAreaNumber(i);
areaVisual.setSumTime(Integer.parseInt(areaTime[i]) / 2);//转化成分钟
if(areaNum.containsKey(areaVisual.getAreaName())){
Integer sum = areaVisual.getSumTime() + areaNum.get(areaVisual.getAreaName());
areaNum.put(areaVisual.getAreaName(),sum);
}else
areaNum.put(areaVisual.getAreaName(),areaVisual.getSumTime());
}
} else {
for (int i = 0; i <= 10; i++) {
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(room.getRoomName() + ":" + Tool.getPositionInfo(i, room));
areaVisual.setAreaNumber(i);
areaVisual.setSumTime(0);
areaNum.put(areaVisual.getAreaName(),areaVisual.getSumTime());
}
}
}
private List<AreaVisual> setVisuals(List<AreaStatistic> areaStatistic,Room room){
List<AreaVisual> areaVisuals = new ArrayList<>();
if (areaStatistic.size() != 0) {
//List<Room> roomList = roomDao.getAllRoomByOldManId(oldMan.getOid());
String areaTime[] = areaStatistic.get(0).getStatisticInfo().split("#");
for (int i = 0; i < areaTime.length; i++) {
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(Tool.getPositionInfo(i, room));
areaVisual.setAreaNumber(i);
areaVisual.setSumTime(Integer.parseInt(areaTime[i]) / 2);//转化成分钟
areaVisuals.add(areaVisual);
}
} else {
for (int i = 0; i <= 10; i++) {
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(Tool.getPositionInfo(i, room));
areaVisual.setAreaNumber(i);
areaVisual.setSumTime(0);
areaVisuals.add(areaVisual);
}
}
return areaVisuals;
}
}
|
UTF-8
|
Java
| 23,595 |
java
|
StatisticServiceImpl.java
|
Java
|
[] | null |
[] |
package com.warn.service.impl;
import com.warn.dao.DataDao;
import com.warn.dao.RoomDao;
import com.warn.dao.StatisticDao;
import com.warn.dao.ThresholdDao;
import com.warn.dto.DwrData;
import com.warn.dto.Warn_statistic;
import com.warn.dto.visual.AreaVisual;
import com.warn.dto.visual.AreaVisualList;
import com.warn.dto.visual.AreaVisualLists;
import com.warn.dwr.Remote;
import com.warn.entity.*;
import com.warn.mongodb.model.SensorCollection;
import com.warn.sensordata.dao.SensorMogoSecDao;
import com.warn.service.SensorService;
import com.warn.service.StatisticService;
import com.warn.service.WarnHistoryService;
import com.warn.util.DynamicDataSourceHolder;
import com.warn.util.Tool.Tool;
import org.omg.CORBA.MARSHAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Service
public class StatisticServiceImpl implements StatisticService {
@Autowired
SensorMogoSecDao sensorMogoSecDao;
@Autowired
DataDao dataDao;
@Autowired
RoomDao roomDao;
@Autowired
StatisticDao statisticDao;
@Autowired
ThresholdDao thresholdDao;
@Autowired
WarnHistoryService warnHistoryService;
// public static Map<OldMan,Boolean> doorS=new HashMap<OldMan,Boolean>();//存储老人是否出门了(门动的时间) 出门了就不在计数;
public static Map<Integer,Boolean> out = new HashMap<>();//initial false
public static Map<Integer,Boolean> judge = new HashMap<>();//initial false
public static Map<Integer,Boolean> key = new HashMap<>();//initial true
//public static Map<String,Integer> AreaNum = new HashMap<>();
@Override
public void getStatisticData(Integer gatewayId){
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String current = date.format(new Date());//现在的时间
String yesterday = date.format(new Date().getTime() - 86400000);
String start = yesterday.split(" ")[0] + " " + "20:00:00";
String end = current.split(" ")[0] + " " + "20:00:00";
String today = current.split(" ")[0];
OldMan oldMan = dataDao.getOldManByGatewayID(gatewayId);
List<Room> roomList = roomDao.getAllRoomByOldManId(oldMan.getOid());
Integer rSize = roomList.size();
List<AreaStatistic> areaStatistics = statisticDao.getStatisticByDate(today,oldMan.getOid());
Integer areas[][] = new Integer[11][11];
String statisticInfo[] = new String[11];
for(Room room:roomList) {//更新,先获取今天的数据,如果没有就从零开始
if (areaStatistics.size() == 0){
for (int j = 0; j <= 10; j++) {
areas[Integer.parseInt(room.getCollectId())][j] = 0;//collectId即每个采集点、就是房间
areas[0][10] = 0;
areas[0][0] = 0;
}
out.put(gatewayId,false);
judge.put(gatewayId,false);
key.put(gatewayId,true);
}
else{
for (AreaStatistic areaStatistic : areaStatistics) {
if(areaStatistic.getRoomId() == room.getRid()){
String tempArea[] = areaStatistic.getStatisticInfo().split("#");
areas[Integer.parseInt(room.getCollectId())][0] = 0;//把户外设为0?
for(int j = 0; j <= 10 ; j++)
areas[Integer.parseInt(room.getCollectId())][j] = Integer.parseInt(tempArea[j]);
}
}
start = areaStatistics.get(0).getTime();
}
}
List<Integer> sensorPointIds = new ArrayList<>();
for(Room room:roomList){
sensorPointIds.add(Integer.parseInt(room.getCollectId()));
}
// String now = date.format(new Date());//现在的时间
// String startOfDay = now.split(" ")[0] + " " + "00:00:00";//当天的开始
// String endOfDay = now.split(" ")[0] + " " + "23:59:59";//当天的结束
// Long fTime = date.parse(startOfDay).getTime();//转换成时间戳
// Long nTime = date.parse(now).getTime();
// Long eTime = date.parse(endOfDay).getTime();
//Integer limit = 3600 / 30 * roomList.size()+20;
// List<SensorCollection> sensorCollections = sensorMogoSecDao.findToStatistic(gatewayId, sensorPointIds,limit);
List<SensorCollection> sensorCollections = sensorMogoSecDao.findToStatisticBeta(gatewayId,sensorPointIds,start,end);
Set<String> zero = new HashSet<>();
// for(int i = limit - 1; i >=0 ; i--){
Integer tempY = 10;//用来标其他区域
Integer tempX = 0;//同上
for(int i=0;i<sensorCollections.size();i++){
SensorCollection sensorCollection = sensorCollections.get(i);
if(judge.get(gatewayId))//衔接上一个时间段的出门的判断
for(int j = i;j <= rSize * 2 * 2;j ++){
SensorCollection sensorCollection1 = sensorCollections.get(i+j);
if(sensorCollection1.getSensorID() == 1)
if(sensorCollection1.getSensorData() != 0){
out.put(gatewayId,false);//没出门
break;
}
if(j == rSize * 4)
out.put(gatewayId,true);//出门了
}
if(sensorCollection.getSensorID() == 1){//如果是行为数据
if(sensorCollection.getSensorData() == 0){
zero.add(sensorCollection.getSensorPointID());
if(zero.size() == rSize ){//出门了就户外,没出门就算其他区域
if(!out.get(gatewayId))
areas[tempX][tempY]++;
else
areas[0][0]++;
zero.clear();
}
}
else {
areas[Integer.parseInt(sensorCollection.getSensorPointID())][sensorCollection.getSensorData()]++;//在原来的数据上加
tempX = Integer.parseInt(sensorCollection.getSensorPointID());
tempY = sensorCollection.getSensorData();
zero.clear();
out.put(gatewayId,false);
}
}else{
if(sensorCollections.size() - i < rSize * 2 * 4)
judge.put(gatewayId,true);
else
for(int j = rSize * 2 * 2; j < rSize * 8 ; j++){ //出门判断(有门的霍尔数据的2-4分钟内,房间内 没有人的数据 的话,判断为出门)
SensorCollection sensorCollection1 = sensorCollections.get(i+j);
if(sensorCollection1.getSensorID() == 1)
if(sensorCollection1.getSensorData() != 0){
out.put(gatewayId,false);//没出门
break;
}
if(j == rSize * 8)
out.put(gatewayId,true);//出门了
}
}
// Long fiTime = date.parse(firstTime).getTime()
}
for(Room room:roomList){
Integer i = Integer.parseInt(room.getCollectId());
String temp = areas[0][0].toString() + "#";
for(Integer j = 1;j <= 9;j++){
temp = temp + areas[i][j].toString() + "#";
}
temp = temp + areas[0][10].toString();
statisticInfo[i] = temp;
}
List<AreaStatistic> areaStatisticr = statisticDao.getStatisticByDate(today,oldMan.getOid());
if(areaStatisticr.size() == 0){
for(Room room:roomList){
AreaStatistic areaStatistic = new AreaStatistic();
areaStatistic.setDate(today);
areaStatistic.setTime(current);
areaStatistic.setOid(oldMan.getOid());
areaStatistic.setRoomId(room.getRid());
areaStatistic.setStatisticInfo(statisticInfo[Integer.parseInt(room.getCollectId())]);
statisticDao.addAreaStatistic(areaStatistic);
}
}else{
for(AreaStatistic areaStatistic:areaStatistics){
for(Room room:roomList){
if(room.getRid() == areaStatistic.getRoomId())
areaStatistic.setStatisticInfo(statisticInfo[Integer.parseInt(room.getCollectId())]);
}
areaStatistic.setTime(current);
statisticDao.updateAreaStatistic(areaStatistic);
}
}
}
@Override
public List<AreaVisualList> getStatisticArea(Integer oid,Integer rid,String time){
//OldMan oldMan = dataDao.getOldManByOid(oid);
Map<String,Integer> areaNum = new HashMap<>();
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
String current = date.format(new Date());//现在的时间
String today = current.split(" ")[0];
List<AreaVisualList> areaVisualLists = new ArrayList<>();
List<AreaStatistic> areaStatistics = new ArrayList<>();
List<AreaVisual> areaVisuals = new ArrayList<>();
Room room1 = new Room();
if(time == null)
areaStatistics = statisticDao.getStatisticInfo(today,oid);//就算取不到也不会报Null 的异常
else
areaStatistics = statisticDao.getStatisticInfo(time,oid);
if(areaStatistics.size() != 0)
for(AreaStatistic areaStatistic:areaStatistics){
room1 = roomDao.getRoomById(areaStatistic.getRoomId());
List<AreaStatistic> areaStatistics1 = new ArrayList<>();
areaStatistics1.clear();
areaStatistics1.add(areaStatistic);
mergeVsiuals(areaStatistics1,room1,areaNum);
}
for(Map.Entry<String,Integer> entry:areaNum.entrySet()){
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(entry.getKey());
if(entry.getKey().equals("户外"))
areaVisual.setSumTime(entry.getValue() / areaStatistics.size());
else
areaVisual.setSumTime(entry.getValue());
areaVisuals.add(areaVisual);
}
AreaVisualList areaVisualList = new AreaVisualList();
areaVisualList.setAreaVisuals(areaVisuals);
areaVisualList.setRoomName("区域时间统计");
areaVisualLists.add(areaVisualList);
areaVisualLists.add(getAreaAverage(oid));
return areaVisualLists;
}
private AreaVisualList getAreaAverage(Integer oid){
Map<String,Integer> areaNum = new HashMap<>();
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat week = new SimpleDateFormat("EEEE");
date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
week.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date current = new Date();//现在的时间
List<String> dates = new ArrayList<>();
List<Room> roomList = roomDao.getAllRoomByOldManId(oid);
List<AreaVisualLists> visualLists = new ArrayList<>();
List<AreaVisual> areaVisuals = new ArrayList<>();
for(int j = 0; j < 7; j++){
dates.add(date.format(current).split(" ")[0]);
current = new Date(current.getTime() - 86400000);
}
for(Room room:roomList){
List<AreaStatistic> areaStatistics = statisticDao.getStatisitcInfos(dates,oid,room.getRid());//就算取不到也不会报Null 的异常
for(AreaStatistic areaStatistic:areaStatistics){
List<AreaStatistic> areaStatistics1 = new ArrayList<>();
areaStatistics1.clear();
areaStatistics1.add(areaStatistic);
mergeVsiuals(areaStatistics1,room,areaNum);
}
}
for(Map.Entry<String,Integer> entry:areaNum.entrySet()){
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(entry.getKey());
if(entry.getKey().equals("户外"))
areaVisual.setSumTime(entry.getValue()/(7 * roomList.size()));
else
areaVisual.setSumTime(entry.getValue()/7);
areaVisuals.add(areaVisual);
}
AreaVisualList areaVisualList = new AreaVisualList();
areaVisualList.setAreaVisuals(areaVisuals);
areaVisualList.setRoomName("周平均值");
return areaVisualList;
}
@Override
public List<AreaVisualLists> getStatisticAreaList(Integer oid,Integer rid) {
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat week = new SimpleDateFormat("EEEE");
date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
week.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date current = new Date();//现在的时间
List<String> dates = new ArrayList<>();
List<Room> roomList = roomDao.getAllRoomByOldManId(oid);
List<AreaVisualLists> visualLists = new ArrayList<>();
for(int j = 0; j < 7; j++){
dates.add(date.format(current).split(" ")[0]);
current = new Date(current.getTime() - 86400000);
}
for(Room room:roomList){
AreaVisualLists visualList = new AreaVisualLists();
List<AreaStatistic> areaStatistics = statisticDao.getStatisitcInfos(dates,oid,room.getRid());//就算取不到也不会报Null 的异常
List<AreaVisualList> areaVisualLists = new ArrayList<>();
for(AreaStatistic areaStatistic:areaStatistics){
AreaVisualList areaVisualList = new AreaVisualList();
areaVisualList.setDate(areaStatistic.getDate()+"("+week.format(current)+")");
List<AreaStatistic> areaStatistics1 = new ArrayList<>();
areaStatistics1.clear();
areaStatistics1.add(areaStatistic);
List<AreaVisual> areaVisuals = setVisuals(areaStatistics1,room);
areaVisualList.setAreaVisuals(areaVisuals);
areaVisualLists.add(areaVisualList);
current = new Date(current.getTime() - 86400000);
}
Collections.reverse(areaVisualLists);
visualList.setAreaVisual(areaVisualLists);
visualList.setRoomName(room.getRoomName());
visualLists.add(visualList);
}
return visualLists;
}
@Override
public void transferData(List<SensorData> sensorDatas){
}
// @Override
// public void checkStatistic(Integer oid,Integer rid){
// try {
// Random r = new Random();
// TimeUnit.SECONDS.sleep(r.nextInt(20));
// }catch(Exception e){
// System.out.println("timeunit wrong");
// }
// if(key){
// key = false;
// }else
// return;
// SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// date.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
// Date current = new Date();//现在的时间
// List<AreaVisualList> areaVisualLists = new ArrayList<>();
// List<AreaVisual> areaVisuals = new ArrayList<>();
// current = new Date(current.getTime() - 86400000);
// String today = date.format(new Date()).split(" ")[0];
// List<AreaStatistic> areaStatistic1 = statisticDao.getStatisticInfo(today,oid);//就算取不到也不会报Null 的异常
// Room room = roomDao.getRoomById(rid);
// List<AreaVisual> areaVisuals1 = setVisuals(areaStatistic1,room);
// for (int j = 0; j < 7; j++) {
// AreaVisualList areaVisualList = new AreaVisualList();
// String time = date.format(current).split(" ")[0];
// areaVisualList.setDate(time);
// List<AreaStatistic> areaStatistic = statisticDao.getStatisticInfo(time, oid);//就算取不到也不会报Null 的异常
// if(areaStatistic.get(0).getNormal() == 0){
// areaVisuals = setVisuals(areaStatistic,room);
// areaVisualList.setAreaVisuals(areaVisuals);
// areaVisualLists.add(areaVisualList);
// current = new Date(current.getTime() - 86400000);
// }else{
// j--;
// }
// }
// List<Threshold_statistic> threshold_statistics = thresholdDao.getThresholdSByRid(rid);
// Integer[] average = {0,0,0,0,0,0,0,0,0,0,0};
// Integer[] standard = {0,0,0,0,0,0,0,0,0,0,0};
// for(int i = 0;i <= 10;i++){
// Integer sum = 0;
// for(int j = 0;j < 7;j++){
// sum = sum + areaVisualLists.get(j).getAreaVisuals().get(i).getSumTime();
// }
// average[i] = sum / 7;
// double sumd = 0;
// double two = 2;
// for(int j = 0;j < 7;j++){
// sumd = sumd + Math.pow(areaVisualLists.get(j).getAreaVisuals().get(i).getSumTime().doubleValue()-average[i].doubleValue(),two);
// }
// standard[i] = (int)Math.sqrt(sumd/7);
// AreaVisual areaVisual = areaVisuals1.get(i);
// Integer deviation = Math.abs(areaVisual.getSumTime() - average[i]);
// Integer threshold = getThreshold(threshold_statistics,areaVisual.getAreaNumber());
// if(threshold != null)
// if((threshold == 404 && deviation > standard[i]) || (threshold!=404 && deviation > threshold)){ //报警
// Warn_statistic warn_statistic = new Warn_statistic();
// OldMan oldMan = dataDao.getOldManByOid(oid);
// warn_statistic.setOldMan(oldMan);
// warn_statistic.setRoom(room.getRoomName());
// warn_statistic.setAreaInfo(areaVisual.getAreaName());
// warn_statistic.setDate(today);
// warn_statistic.setDeviation(deviation);
// DwrData dwrData = new DwrData();
// dwrData.setType("warn_statistic");
// AreaStatistic areaStatistic = areaStatistic1.get(0);
// areaStatistic.setNormal(1);
// statisticDao.updateNormal(areaStatistic);
// dwrData.setWarn_statistic(warn_statistic);
// warnHistoryService.addWarnHistory(dwrData);
// Remote.noticeNewOrder(dwrData);
// }
// }
// key = true;
// }
private Integer getThreshold(List<Threshold_statistic> threshold_statistics,Integer num){
for(Threshold_statistic threshold_statistic:threshold_statistics){
if(threshold_statistic.getArea().equals(num))
return num;
}
return null;
}
// private void mergeVisualsD(List<AreaStatistic> areaStatistics, Room room, Map<String,Integer> areaNum,String date){
// String areaTime[] = areaStatistics.get(0).getStatisticInfo().split("#");
// for (int i = 0; i < areaTime.length; i++) {
// AreaVisual areaVisual = new AreaVisual();
// if(Tool.getPositionInfo(i,room).equals("户外"))
// areaVisual.setAreaName("户外"+"-"+date);
// else
// areaVisual.setAreaName(room.getRoomName() + ":" + Tool.getPositionInfo(i, room) + "-" + date);
// areaVisual.setAreaNumber(i);
// areaVisual.setSumTime(Integer.parseInt(areaTime[i]) / 2);//转化成分钟
// if(areaNum.containsKey(areaVisual.getAreaName())) {
// Integer sum = areaVisual.getSumTime() + areaNum.get(areaVisual.getAreaName());
// areaNum.put(areaVisual.getAreaName(),sum);
// }else
// areaNum.put(areaVisual.getAreaName(),areaVisual.getSumTime());
// }
// }
private void mergeVsiuals(List<AreaStatistic> areaStatistics,Room room,Map<String,Integer> areaNum){
if (areaStatistics.size() != 0) {
//List<Room> roomList = roomDao.getAllRoomByOldManId(oldMan.getOid());
String areaTime[] = areaStatistics.get(0).getStatisticInfo().split("#");
for (int i = 0; i < areaTime.length; i++) {
AreaVisual areaVisual = new AreaVisual();
if(Tool.getPositionInfo(i,room).equals("户外"))
areaVisual.setAreaName("户外");
else
areaVisual.setAreaName(room.getRoomName() + ":" + Tool.getPositionInfo(i, room));
areaVisual.setAreaNumber(i);
areaVisual.setSumTime(Integer.parseInt(areaTime[i]) / 2);//转化成分钟
if(areaNum.containsKey(areaVisual.getAreaName())){
Integer sum = areaVisual.getSumTime() + areaNum.get(areaVisual.getAreaName());
areaNum.put(areaVisual.getAreaName(),sum);
}else
areaNum.put(areaVisual.getAreaName(),areaVisual.getSumTime());
}
} else {
for (int i = 0; i <= 10; i++) {
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(room.getRoomName() + ":" + Tool.getPositionInfo(i, room));
areaVisual.setAreaNumber(i);
areaVisual.setSumTime(0);
areaNum.put(areaVisual.getAreaName(),areaVisual.getSumTime());
}
}
}
private List<AreaVisual> setVisuals(List<AreaStatistic> areaStatistic,Room room){
List<AreaVisual> areaVisuals = new ArrayList<>();
if (areaStatistic.size() != 0) {
//List<Room> roomList = roomDao.getAllRoomByOldManId(oldMan.getOid());
String areaTime[] = areaStatistic.get(0).getStatisticInfo().split("#");
for (int i = 0; i < areaTime.length; i++) {
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(Tool.getPositionInfo(i, room));
areaVisual.setAreaNumber(i);
areaVisual.setSumTime(Integer.parseInt(areaTime[i]) / 2);//转化成分钟
areaVisuals.add(areaVisual);
}
} else {
for (int i = 0; i <= 10; i++) {
AreaVisual areaVisual = new AreaVisual();
areaVisual.setAreaName(Tool.getPositionInfo(i, room));
areaVisual.setAreaNumber(i);
areaVisual.setSumTime(0);
areaVisuals.add(areaVisual);
}
}
return areaVisuals;
}
}
| 23,595 | 0.564765 | 0.553975 | 473 | 46.589851 | 27.791828 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.866808 | false | false |
0
|
734580cfc35d3656ddaf230af24ad6f9c626b7c7
| 35,038,343,238,277 |
dac81fdbf2f84486363e4528ed87ab211f7368c9
|
/Rute.Ar/RuteAr/src/rest/recursos/KMLResource.java
|
10a7336a11f7ac55aad656eafa0509f94a13449c
|
[] |
no_license
|
m474dor/ServerJava
|
https://github.com/m474dor/ServerJava
|
89963be4180312171691af746ce9f8678103707d
|
90c2fbb0146d2ec78594386d712b297dfc0e04cc
|
refs/heads/master
| 2020-03-28T18:10:31.795000 | 2018-10-04T20:26:04 | 2018-10-04T20:26:04 | 148,858,130 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package rest.recursos;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Request;
import javax.ws.rs.POST;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import de.micromata.opengis.kml.v_2_2_0.Coordinate;
import de.micromata.opengis.kml.v_2_2_0.Document;
import de.micromata.opengis.kml.v_2_2_0.Feature;
import de.micromata.opengis.kml.v_2_2_0.Kml;
import de.micromata.opengis.kml.v_2_2_0.Placemark;
import de.micromata.opengis.kml.v_2_2_0.Point;
import manager.factoryDAO;
import iDAO.*;
import model.*;
@Path("/kml")
public class KMLResource {
@Context
UriInfo uriInfo;
@Context
Request request;
private iDAORoute rdao = factoryDAO.getRouteDAO();
private iDAOMapPoint mdao = factoryDAO.getMapPointDAO();
private static final String UPLOAD_FOLDER = "uploadedKML/";
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public List<MapPoint> getPhotos(@PathParam("id") Integer id) {
Route aux = rdao.findId(id);
return aux.getPoints();
}
@DELETE
@Path("delete/{id}")
@Produces(MediaType.TEXT_PLAIN)
public Response borrar(@PathParam("id") Integer id) {
MapPoint aux = mdao.findId(id);
// User us = aux.getOwner();
// List<Route> list = us.getMyRoute();
// for(int i=0;i<list.size();i++) {
// if(list.get(i).getId()==aux.getId()) {
// list.remove(i);
// break;
// }
// }
// us.setMyRoute(list);
if (aux != null) {// && us != null) {
//udao.update(us);
mdao.delete(aux);
return Response.ok().build();
} else {
String mensaje = "No se entro a eliminar";
return Response.status(Response.Status.NOT_FOUND).entity(mensaje).build();
}
}
@POST
@Path("{id}/{fileDetail}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response crear(
@PathParam("id") Integer id,
@PathParam("fileDetail") String fileDetail,
InputStream uploadedInputStream) {
Route aux = rdao.findId(id);
// check if all form parameters are provided
if (uploadedInputStream == null || fileDetail == null)
return Response.status(400).entity("Invalid form data").build();
// create our destination folder, if it not exists
try {
createFolderIfNotExists(UPLOAD_FOLDER);
} catch (SecurityException se) {
return Response.status(500).entity("Can not create destination folder on server").build();
}
String uploadedFileLocation = UPLOAD_FOLDER + fileDetail;
try {
saveToFile(uploadedInputStream, uploadedFileLocation);
final Kml kml = Kml.unmarshal(new File(uploadedFileLocation));
final Placemark doc = (Placemark) kml.getFeature();
Point point = (Point) doc.getGeometry();
List<Coordinate> coordinates = point.getCoordinates();
for (Coordinate coordinate : coordinates) {
System.out.println(coordinate.getLatitude());
System.out.println(coordinate.getLongitude());
System.out.println(coordinate.getAltitude());
MapPoint ma = new MapPoint();
ma.setLat(coordinate.getLatitude());
ma.setLong(coordinate.getLongitude());
ma.setRoute(aux);
mdao.insert(ma);
}
// List<MapPoint> list = aux.getPoints();
// for(MapPoint map: list) {
//
// }
//
// aux.setPoints(list);
// rdao.update(aux);
} catch (IOException e) {
return Response.status(500).entity("Can not save file").build();
}
return Response.status(200).entity("File saved to " + uploadedFileLocation).build();
}
/**
* Utility method to save InputStream data to target location/file
*
* @param inStream
* - InputStream to be saved
* @param target
* - full path to destination file
*/
private void saveToFile(InputStream inStream, String target) throws IOException {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(target));
while ((read = inStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
/**
* Creates a folder to desired location if it not already exists
*
* @param dirName
* - full path to the folder
* @throws SecurityException
* - in case you don't have permission to create the folder
*/
private void createFolderIfNotExists(String dirName) throws SecurityException {
File theDir = new File(dirName);
if (!theDir.exists()) {
theDir.mkdir();
}
}
}
|
UTF-8
|
Java
| 4,732 |
java
|
KMLResource.java
|
Java
|
[] | null |
[] |
package rest.recursos;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Request;
import javax.ws.rs.POST;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import de.micromata.opengis.kml.v_2_2_0.Coordinate;
import de.micromata.opengis.kml.v_2_2_0.Document;
import de.micromata.opengis.kml.v_2_2_0.Feature;
import de.micromata.opengis.kml.v_2_2_0.Kml;
import de.micromata.opengis.kml.v_2_2_0.Placemark;
import de.micromata.opengis.kml.v_2_2_0.Point;
import manager.factoryDAO;
import iDAO.*;
import model.*;
@Path("/kml")
public class KMLResource {
@Context
UriInfo uriInfo;
@Context
Request request;
private iDAORoute rdao = factoryDAO.getRouteDAO();
private iDAOMapPoint mdao = factoryDAO.getMapPointDAO();
private static final String UPLOAD_FOLDER = "uploadedKML/";
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public List<MapPoint> getPhotos(@PathParam("id") Integer id) {
Route aux = rdao.findId(id);
return aux.getPoints();
}
@DELETE
@Path("delete/{id}")
@Produces(MediaType.TEXT_PLAIN)
public Response borrar(@PathParam("id") Integer id) {
MapPoint aux = mdao.findId(id);
// User us = aux.getOwner();
// List<Route> list = us.getMyRoute();
// for(int i=0;i<list.size();i++) {
// if(list.get(i).getId()==aux.getId()) {
// list.remove(i);
// break;
// }
// }
// us.setMyRoute(list);
if (aux != null) {// && us != null) {
//udao.update(us);
mdao.delete(aux);
return Response.ok().build();
} else {
String mensaje = "No se entro a eliminar";
return Response.status(Response.Status.NOT_FOUND).entity(mensaje).build();
}
}
@POST
@Path("{id}/{fileDetail}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response crear(
@PathParam("id") Integer id,
@PathParam("fileDetail") String fileDetail,
InputStream uploadedInputStream) {
Route aux = rdao.findId(id);
// check if all form parameters are provided
if (uploadedInputStream == null || fileDetail == null)
return Response.status(400).entity("Invalid form data").build();
// create our destination folder, if it not exists
try {
createFolderIfNotExists(UPLOAD_FOLDER);
} catch (SecurityException se) {
return Response.status(500).entity("Can not create destination folder on server").build();
}
String uploadedFileLocation = UPLOAD_FOLDER + fileDetail;
try {
saveToFile(uploadedInputStream, uploadedFileLocation);
final Kml kml = Kml.unmarshal(new File(uploadedFileLocation));
final Placemark doc = (Placemark) kml.getFeature();
Point point = (Point) doc.getGeometry();
List<Coordinate> coordinates = point.getCoordinates();
for (Coordinate coordinate : coordinates) {
System.out.println(coordinate.getLatitude());
System.out.println(coordinate.getLongitude());
System.out.println(coordinate.getAltitude());
MapPoint ma = new MapPoint();
ma.setLat(coordinate.getLatitude());
ma.setLong(coordinate.getLongitude());
ma.setRoute(aux);
mdao.insert(ma);
}
// List<MapPoint> list = aux.getPoints();
// for(MapPoint map: list) {
//
// }
//
// aux.setPoints(list);
// rdao.update(aux);
} catch (IOException e) {
return Response.status(500).entity("Can not save file").build();
}
return Response.status(200).entity("File saved to " + uploadedFileLocation).build();
}
/**
* Utility method to save InputStream data to target location/file
*
* @param inStream
* - InputStream to be saved
* @param target
* - full path to destination file
*/
private void saveToFile(InputStream inStream, String target) throws IOException {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(target));
while ((read = inStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
/**
* Creates a folder to desired location if it not already exists
*
* @param dirName
* - full path to the folder
* @throws SecurityException
* - in case you don't have permission to create the folder
*/
private void createFolderIfNotExists(String dirName) throws SecurityException {
File theDir = new File(dirName);
if (!theDir.exists()) {
theDir.mkdir();
}
}
}
| 4,732 | 0.688081 | 0.680051 | 162 | 28.216049 | 21.227957 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.030864 | false | false |
0
|
964ec537bbbabf47904e40a714c62fb34548a461
| 35,038,343,238,936 |
f65b022d8461f4f27c5468a431c99116a5a55021
|
/src/main/java/com/chervon/iot/mobile/util/SendEmail.java
|
7e27a4e3e5afea797e2cf86330a2e7d7ccf1af7d
|
[] |
no_license
|
oscarLiuMinhui/chervon
|
https://github.com/oscarLiuMinhui/chervon
|
9ae240bd4d8374ae20d8826ae30cd5beda1f2dd8
|
5b3b457f6af2356f47b350eda572911779628c93
|
refs/heads/master
| 2021-01-01T20:50:33.308000 | 2017-07-31T08:42:12 | 2017-07-31T08:42:12 | 98,944,902 | 0 | 0 | null | true | 2017-08-01T01:19:51 | 2017-08-01T01:19:51 | 2017-07-31T08:54:20 | 2017-07-31T08:54:18 | 353 | 0 | 0 | 0 | null | null | null |
package com.chervon.iot.mobile.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
@Component
public class SendEmail{
@Autowired
private MailSender mailSender;
@Value("${spring.mail.username}")
private String fromEmail;
public void sendAttachmentsMail(String email,String url)throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail);//发送者.
message.setTo(email);//接收者.
message.setSubject("测试邮件(邮件主题)");//邮件主题.
message.setText(url);//邮件内容.
mailSender.send(message);//
}
}
|
UTF-8
|
Java
| 853 |
java
|
SendEmail.java
|
Java
|
[] | null |
[] |
package com.chervon.iot.mobile.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
@Component
public class SendEmail{
@Autowired
private MailSender mailSender;
@Value("${spring.mail.username}")
private String fromEmail;
public void sendAttachmentsMail(String email,String url)throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail);//发送者.
message.setTo(email);//接收者.
message.setSubject("测试邮件(邮件主题)");//邮件主题.
message.setText(url);//邮件内容.
mailSender.send(message);//
}
}
| 853 | 0.741615 | 0.741615 | 22 | 35.590908 | 20.13739 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false |
0
|
8ef2ebae7f40b51594e7602d7de6a52735b1d677
| 39,067,022,524,747 |
e6afe22af34c4f5b215321812d2f0b3107f24336
|
/Day10/tcp/TCPClient.java
|
ac99ea30543a8b8c92a68ef97fb75ad348e01711
|
[] |
no_license
|
Class-util/Class-code
|
https://github.com/Class-util/Class-code
|
a909d0b38eefa8a862ef36e7c4595b6bf26dbd78
|
dad4f6721abf0233534c00e8278a05bd3810a729
|
refs/heads/master
| 2023-05-12T17:42:15.440000 | 2021-05-30T09:24:15 | 2021-05-30T09:24:15 | 321,014,043 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Day10.tcp;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* Description:
* User:吴博
* Date:2021 04 15
* Time:19:59
*/
public class TCPClient {
private static final String ip = "127.0.0.1";
private static final int port = 9003;
public static void main(String[] args) throws IOException {
//创建并启动客户端,顺便连服务器
Socket socket = new Socket(ip,port);
try(
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream())
);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())
);
Scanner sc = new Scanner(System.in);
){
while (true){
//发送消息
System.out.print("->");
String msg = sc.nextLine();
writer.write(msg + "\n");
writer.flush();
//接收消息
String serMsg = reader.readLine();
if(serMsg != null && !serMsg.equals("")){
System.out.println("服务器端说:" + serMsg);
}
}
}
}
}
|
UTF-8
|
Java
| 1,328 |
java
|
TCPClient.java
|
Java
|
[
{
"context": "eated with IntelliJ IDEA.\n * Description:\n * User:吴博\n * Date:2021 04 15\n * Time:19:59\n */\npublic class",
"end": 150,
"score": 0.913344144821167,
"start": 148,
"tag": "NAME",
"value": "吴博"
},
{
"context": "TCPClient {\n private static final String ip = \"127.0.0.1\";\n private static final int port = 9003;\n p",
"end": 260,
"score": 0.9997832179069519,
"start": 251,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null |
[] |
package Day10.tcp;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* Description:
* User:吴博
* Date:2021 04 15
* Time:19:59
*/
public class TCPClient {
private static final String ip = "127.0.0.1";
private static final int port = 9003;
public static void main(String[] args) throws IOException {
//创建并启动客户端,顺便连服务器
Socket socket = new Socket(ip,port);
try(
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream())
);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())
);
Scanner sc = new Scanner(System.in);
){
while (true){
//发送消息
System.out.print("->");
String msg = sc.nextLine();
writer.write(msg + "\n");
writer.flush();
//接收消息
String serMsg = reader.readLine();
if(serMsg != null && !serMsg.equals("")){
System.out.println("服务器端说:" + serMsg);
}
}
}
}
}
| 1,328 | 0.500789 | 0.481861 | 44 | 27.818182 | 20.541834 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false |
0
|
faad7882787c58bd7d4cab3cb726bf6d1f668916
| 33,552,284,569,428 |
292959db63ec69a5b4e6784eefa75af85717d54e
|
/BattleShipGame/src/main/java/com/game/initialize/ValidateAndInitializeSequences.java
|
89f4c773813f0ca928100ffda5949821e2c50648
|
[] |
no_license
|
AwesomeJD/BattleShipGame
|
https://github.com/AwesomeJD/BattleShipGame
|
897910d50acd7afa170444274b0522583c7cbb18
|
c07f2f8eb5062c1192483cdc193459450b8792a0
|
refs/heads/master
| 2020-03-29T18:21:22.884000 | 2018-09-25T04:26:45 | 2018-09-25T04:26:45 | 150,207,322 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* @author Janardhan Sharma
*/
package com.game.initialize;
import com.game.exception.InvalidInputException;
import com.game.model.Coordinate;
import com.game.model.Player;
import com.game.util.Util;
/**
* The Class ValidateAndInitializeSequences.
*/
public class ValidateAndInitializeSequences implements ValidateAndInitialize {
/** The player. */
private Player player;
/** The sequences. */
private String sequences;
/**
* Instantiates a new validate and initialize sequences.
*
* @param player the player
* @param sequences the sequences
*/
public ValidateAndInitializeSequences(Player player, String sequences) {
super();
this.player = player;
this.sequences = sequences;
}
/* (non-Javadoc)
* @see com.game.initialize.ValidateAndInitialize#validateAndInitiaze()
*/
@Override
public void validateAndInitiaze() throws InvalidInputException {
String[] sequencesArray = Util.getStringArray(sequences);
for (String sequence : sequencesArray) {
Character height = Util.getCharacter(sequence.substring(0, 1));
Integer width = Util.getInteger(sequence.substring(1, 2));
if (player.getArea().isHeightPresent(height) && player.getArea().isWidthPresent(width)) {
player.setHitSequence(new Coordinate(height, width));
} else {
throw new InvalidInputException("Invalid hit sequence detected. " + sequence);
}
}
}
}
|
UTF-8
|
Java
| 1,383 |
java
|
ValidateAndInitializeSequences.java
|
Java
|
[
{
"context": "/*\n * @author Janardhan Sharma\n */\npackage com.game.initialize;\n\nimport com.game",
"end": 30,
"score": 0.9998669624328613,
"start": 14,
"tag": "NAME",
"value": "Janardhan Sharma"
}
] | null |
[] |
/*
* @author <NAME>
*/
package com.game.initialize;
import com.game.exception.InvalidInputException;
import com.game.model.Coordinate;
import com.game.model.Player;
import com.game.util.Util;
/**
* The Class ValidateAndInitializeSequences.
*/
public class ValidateAndInitializeSequences implements ValidateAndInitialize {
/** The player. */
private Player player;
/** The sequences. */
private String sequences;
/**
* Instantiates a new validate and initialize sequences.
*
* @param player the player
* @param sequences the sequences
*/
public ValidateAndInitializeSequences(Player player, String sequences) {
super();
this.player = player;
this.sequences = sequences;
}
/* (non-Javadoc)
* @see com.game.initialize.ValidateAndInitialize#validateAndInitiaze()
*/
@Override
public void validateAndInitiaze() throws InvalidInputException {
String[] sequencesArray = Util.getStringArray(sequences);
for (String sequence : sequencesArray) {
Character height = Util.getCharacter(sequence.substring(0, 1));
Integer width = Util.getInteger(sequence.substring(1, 2));
if (player.getArea().isHeightPresent(height) && player.getArea().isWidthPresent(width)) {
player.setHitSequence(new Coordinate(height, width));
} else {
throw new InvalidInputException("Invalid hit sequence detected. " + sequence);
}
}
}
}
| 1,373 | 0.735358 | 0.732466 | 53 | 25.094339 | 26.388437 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.377358 | false | false |
0
|
5a6098e3da9cc79932c5eb60d36fae6471da3a75
| 403,726,975,537 |
6172c5567c945ad725ff35b8ddb23efb6dfa842d
|
/src/main/java/com/example/demo/service/CommentService.java
|
e67ca55c68291de54b840ea0b5dde1c7a39f64bd
|
[] |
no_license
|
sung0513/testsite-back
|
https://github.com/sung0513/testsite-back
|
d92a4132204cd0fed76ed853f11cfb83f95189d6
|
1f77d30640c5bdc2be515626bba9933b050e3338
|
refs/heads/insung
| 2023-01-12T04:57:53.232000 | 2020-03-25T08:45:11 | 2020-03-25T08:45:11 | 240,197,154 | 2 | 0 | null | false | 2023-01-05T10:36:02 | 2020-02-13T06:59:56 | 2020-04-30T14:26:25 | 2023-01-05T10:36:01 | 9,490 | 0 | 0 | 21 |
JavaScript
| false | false |
package com.example.demo.service;
import com.example.demo.domain.Comments;
import com.example.demo.repository.CommentRepository;
import com.example.demo.web.Request.CommentSaveRequestDto;
import com.example.demo.web.Update.CommentUpdateRequestDto;
import com.example.demo.web.Response.CommentResponseDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
@Transactional
public class CommentService {
private final CommentRepository commentRepository;
@Transactional
public Long save(CommentSaveRequestDto requestDto) {
return commentRepository.save(requestDto.toEntity()).getId(); //바로 db에저장된다!
}
//수정하기
public Long update(Long id, CommentUpdateRequestDto requestDto){
Comments comments = commentRepository.findById(id)
.orElseThrow(()-> new IllegalArgumentException("글이 없습니다. id="+ id));
comments.update(requestDto.getGuest_comment(), requestDto.getUser_comment());
return id;
}
//띄우기
public CommentResponseDto findById(Long id){
Comments entity = commentRepository.findById(id)
.orElseThrow(()->new IllegalArgumentException("글이 없습니다. id="+ id));
return new CommentResponseDto(entity);
}
}
|
UTF-8
|
Java
| 1,415 |
java
|
CommentService.java
|
Java
|
[] | null |
[] |
package com.example.demo.service;
import com.example.demo.domain.Comments;
import com.example.demo.repository.CommentRepository;
import com.example.demo.web.Request.CommentSaveRequestDto;
import com.example.demo.web.Update.CommentUpdateRequestDto;
import com.example.demo.web.Response.CommentResponseDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
@Transactional
public class CommentService {
private final CommentRepository commentRepository;
@Transactional
public Long save(CommentSaveRequestDto requestDto) {
return commentRepository.save(requestDto.toEntity()).getId(); //바로 db에저장된다!
}
//수정하기
public Long update(Long id, CommentUpdateRequestDto requestDto){
Comments comments = commentRepository.findById(id)
.orElseThrow(()-> new IllegalArgumentException("글이 없습니다. id="+ id));
comments.update(requestDto.getGuest_comment(), requestDto.getUser_comment());
return id;
}
//띄우기
public CommentResponseDto findById(Long id){
Comments entity = commentRepository.findById(id)
.orElseThrow(()->new IllegalArgumentException("글이 없습니다. id="+ id));
return new CommentResponseDto(entity);
}
}
| 1,415 | 0.741012 | 0.741012 | 41 | 32.243904 | 28.627789 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.439024 | false | false |
0
|
10279a5036b58bdcadb8f16ec3d06d05c48b3192
| 12,781,822,727,048 |
e2953a9044dc63d81cc7985538628da34db0e804
|
/SRC/StaffChatAPI_v1.2/src/com/radialbog9/bungee/staff/API/Main.java
|
c6f086000d12c39c467418322f2630ebd5c5d1ec
|
[] |
no_license
|
TheJoeCoder/Radialbog9StaffChat
|
https://github.com/TheJoeCoder/Radialbog9StaffChat
|
e07b78dfef6fcf11bca7c8ef843cf3eaf93e0f18
|
3a878b68666837483e4a946a6afbd8182313afd8
|
refs/heads/master
| 2020-05-30T15:18:25.693000 | 2020-02-19T16:15:08 | 2020-02-19T16:15:08 | 189,815,171 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.radialbog9.bungee.staff.API;
import net.md_5.bungee.api.plugin.Plugin;
public class Main extends Plugin {
@Override
public void onEnable() {
getLogger().info("StaffChatAPI has been Enabled!");
}
@Override
public void onDisable() {
getLogger().info("StaffChatAPI has been Disabled!");
}
}
|
UTF-8
|
Java
| 326 |
java
|
Main.java
|
Java
|
[
{
"context": "package com.radialbog9.bungee.staff.API;\r\n\r\nimport net.md_5.bungee.api.p",
"end": 22,
"score": 0.8046770095825195,
"start": 12,
"tag": "USERNAME",
"value": "radialbog9"
}
] | null |
[] |
package com.radialbog9.bungee.staff.API;
import net.md_5.bungee.api.plugin.Plugin;
public class Main extends Plugin {
@Override
public void onEnable() {
getLogger().info("StaffChatAPI has been Enabled!");
}
@Override
public void onDisable() {
getLogger().info("StaffChatAPI has been Disabled!");
}
}
| 326 | 0.696319 | 0.690184 | 14 | 21.285715 | 19.509809 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
0
|
03695358bde4abd7315c62027ef54bb34f92a110
| 5,222,680,287,893 |
efeb4d4ec0a2c05d2de67d38f53da487dcf87cdb
|
/Standard Labs/src/Chapter4/ex1_RomanNumerals.java
|
2a5b853007abfd4813fe99da7369c39af6712d0e
|
[] |
no_license
|
pasha11c/JavaLabs
|
https://github.com/pasha11c/JavaLabs
|
02fdf1cfd78ae48363601d8b0df7e130d8186105
|
3a9f5ec959d4aa80f228c835ce8574857d9996e6
|
refs/heads/master
| 2017-11-11T14:04:57.512000 | 2017-03-07T16:56:28 | 2017-03-07T16:56:28 | 83,901,281 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Chapter4;
/**
* Created by Alek on 1/25/2017.
*/
public class ex1_RomanNumerals
{
public static String Roman(String userInput){
int input = Integer.parseInt(userInput);
String output = "";
switch (input)
{
case 1: output = "I";
break;
case 2: output = "II";
break;
case 3: output = "III";
break;
case 4: output = "IV";
break;
case 5: output = "V";
break;
case 6: output = "VI";
break;
case 7: output = "VII";
break;
case 8: output = "VIII";
break;
case 9: output = "IX";
break;
case 10: output = "X";
break;
}
return output;
}
}
|
UTF-8
|
Java
| 879 |
java
|
ex1_RomanNumerals.java
|
Java
|
[
{
"context": "package Chapter4;\n\n/**\n * Created by Alek on 1/25/2017.\n */\npublic class ex1_RomanNumerals\n",
"end": 41,
"score": 0.9970914125442505,
"start": 37,
"tag": "NAME",
"value": "Alek"
}
] | null |
[] |
package Chapter4;
/**
* Created by Alek on 1/25/2017.
*/
public class ex1_RomanNumerals
{
public static String Roman(String userInput){
int input = Integer.parseInt(userInput);
String output = "";
switch (input)
{
case 1: output = "I";
break;
case 2: output = "II";
break;
case 3: output = "III";
break;
case 4: output = "IV";
break;
case 5: output = "V";
break;
case 6: output = "VI";
break;
case 7: output = "VII";
break;
case 8: output = "VIII";
break;
case 9: output = "IX";
break;
case 10: output = "X";
break;
}
return output;
}
}
| 879 | 0.399317 | 0.376564 | 38 | 22.131578 | 13.37549 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false |
0
|
b200cef5c90372719e33855dc5fd59bcada13c2d
| 15,522,011,869,493 |
744be2c0265bace63ffb79470fdd393214654c59
|
/src/de/endrullis/idea/postfixtemplates/language/CptUtil.java
|
dcb1aa414da3bf29c20f12dc3376afffdbe3bc48
|
[
"Apache-2.0"
] |
permissive
|
baoxin/intellij-postfix-templates
|
https://github.com/baoxin/intellij-postfix-templates
|
d5d4b2d4de3e733b74b54ff02cbadabc992f7dd5
|
d23e02725593d0f2ada73e8f7e518ab59abaa9d4
|
refs/heads/master
| 2020-03-25T04:10:32.881000 | 2018-07-26T06:17:00 | 2018-07-26T06:17:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.endrullis.idea.postfixtemplates.language;
import com.intellij.ide.DataManager;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.indexing.FileBasedIndex;
import de.endrullis.idea.postfixtemplates.language.psi.CptFile;
import de.endrullis.idea.postfixtemplates.language.psi.CptMapping;
import de.endrullis.idea.postfixtemplates.settings.CptApplicationSettings;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.util.*;
import static de.endrullis.idea.postfixtemplates.utils.CollectionUtils._List;
@SuppressWarnings("WeakerAccess")
public class CptUtil {
public static final String PLUGIN_ID = "de.endrullis.idea.postfixtemplates";
public static final Set<String> SUPPORTED_LANGUAGES = new HashSet<>(_List("java", "javascript", "scala", "kotlin", "dart"));
public static Project findProject(PsiElement element) {
PsiFile containingFile = element.getContainingFile();
if (containingFile == null) {
if (!element.isValid()) {
return null;
}
} else if (!containingFile.isValid()) {
return null;
}
return (containingFile == null ? element : containingFile).getProject();
}
public static List<CptMapping> findMappings(Project project, String key) {
List<CptMapping> result = null;
Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
GlobalSearchScope.allScope(project));
for (VirtualFile virtualFile : virtualFiles) {
CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);
if (cptFile != null) {
CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
if (mappings != null) {
for (CptMapping mapping : mappings) {
if (key.equals(mapping.getMatchingClassName())) {
if (result == null) {
result = new ArrayList<>();
}
result.add(mapping);
}
}
}
}
}
return result != null ? result : Collections.emptyList();
}
public static List<CptMapping> findMappings(Project project) {
List<CptMapping> result = new ArrayList<>();
Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
GlobalSearchScope.allScope(project));
for (VirtualFile virtualFile : virtualFiles) {
CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);
if (cptFile != null) {
CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
if (mappings != null) {
Collections.addAll(result, mappings);
}
}
}
return result;
}
public static String getDefaultTemplates(String language) {
InputStream stream = CptUtil.class.getResourceAsStream("defaulttemplates/" + language + ".postfixTemplates");
return getContent(stream);
}
public static String getContent(@NotNull File file) throws FileNotFoundException {
return getContent(new FileInputStream(file));
}
private static String getContent(@NotNull InputStream stream) {
StringBuilder sb = new StringBuilder();
// convert system newlines into UNIX newlines, because IDEA works only with UNIX newlines
try (BufferedReader in = new BufferedReader(new InputStreamReader(stream, "UTF-8"))) {
String line;
while ((line = in.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static File getPluginPath() {
File path = PluginManager.getPlugin(PluginId.getId(CptUtil.PLUGIN_ID)).getPath();
if (path.getName().endsWith(".jar")) {
path = new File(path.getParentFile(), path.getName().substring(0, path.getName().length() - 4));
}
return path;
}
public static File getTemplatesPath() {
return new File(getPluginPath(), "templates");
}
public static void createTemplateFile(@NotNull String language, String content) {
File file = new File(CptUtil.getTemplatesPath(), language + ".postfixTemplates");
//noinspection ResultOfMethodCallIgnored
file.getParentFile().mkdirs();
try (PrintStream out = new PrintStream(file, "UTF-8")) {
out.println(content);
out.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(language + " template file could not copied to " + file.getAbsolutePath(), e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 not supported", e);
}
}
public static Optional<File> getTemplateFile(@NotNull String language) {
if (SUPPORTED_LANGUAGES.contains(language.toLowerCase())) {
File file = new File(CptUtil.getTemplatesPath(), language + ".postfixTemplates");
if (!file.exists()) {
createTemplateFile(language, CptUtil.getDefaultTemplates(language));
}
return Optional.of(file);
} else {
return Optional.empty();
}
}
public static String getLanguageOfTemplateFile(@NotNull VirtualFile vFile) {
return vFile.getName().replaceAll("\\.postfixTemplates", "");
}
public static void openFileInEditor(@NotNull Project project, @NotNull File file) {
VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (vFile == null) {
vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
}
assert vFile != null;
openFileInEditor(project, vFile);
}
public static void openFileInEditor(@NotNull Project project, @NotNull VirtualFile vFile) {
// open templates file in an editor
new OpenFileDescriptor(project, vFile).navigate(true);
}
public static Project getActiveProject() {
DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult();
return DataKeys.PROJECT.getData(dataContext);
}
public static boolean isTemplateFile(VirtualFile vFile) {
return vFile != null && vFile.getCanonicalPath() != null &&
vFile.getCanonicalPath().replace('\\', '/').startsWith(CptUtil.getTemplatesPath().getAbsolutePath().replace('\\', '/'));
}
public static boolean isTemplateFile(VirtualFile vFile, String language) {
return vFile != null && vFile.getCanonicalPath() != null &&
vFile.getCanonicalPath().replace('\\', '/').startsWith(CptUtil.getTemplatesPath().getAbsolutePath().replace('\\', '/') + "/" + language);
}
@NotNull
public static String getTemplateSuffix() {
return CptApplicationSettings.getInstance().getPluginSettings().getTemplateSuffix();
}
}
|
UTF-8
|
Java
| 7,006 |
java
|
CptUtil.java
|
Java
|
[] | null |
[] |
package de.endrullis.idea.postfixtemplates.language;
import com.intellij.ide.DataManager;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.indexing.FileBasedIndex;
import de.endrullis.idea.postfixtemplates.language.psi.CptFile;
import de.endrullis.idea.postfixtemplates.language.psi.CptMapping;
import de.endrullis.idea.postfixtemplates.settings.CptApplicationSettings;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.util.*;
import static de.endrullis.idea.postfixtemplates.utils.CollectionUtils._List;
@SuppressWarnings("WeakerAccess")
public class CptUtil {
public static final String PLUGIN_ID = "de.endrullis.idea.postfixtemplates";
public static final Set<String> SUPPORTED_LANGUAGES = new HashSet<>(_List("java", "javascript", "scala", "kotlin", "dart"));
public static Project findProject(PsiElement element) {
PsiFile containingFile = element.getContainingFile();
if (containingFile == null) {
if (!element.isValid()) {
return null;
}
} else if (!containingFile.isValid()) {
return null;
}
return (containingFile == null ? element : containingFile).getProject();
}
public static List<CptMapping> findMappings(Project project, String key) {
List<CptMapping> result = null;
Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
GlobalSearchScope.allScope(project));
for (VirtualFile virtualFile : virtualFiles) {
CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);
if (cptFile != null) {
CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
if (mappings != null) {
for (CptMapping mapping : mappings) {
if (key.equals(mapping.getMatchingClassName())) {
if (result == null) {
result = new ArrayList<>();
}
result.add(mapping);
}
}
}
}
}
return result != null ? result : Collections.emptyList();
}
public static List<CptMapping> findMappings(Project project) {
List<CptMapping> result = new ArrayList<>();
Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, CptFileType.INSTANCE,
GlobalSearchScope.allScope(project));
for (VirtualFile virtualFile : virtualFiles) {
CptFile cptFile = (CptFile) PsiManager.getInstance(project).findFile(virtualFile);
if (cptFile != null) {
CptMapping[] mappings = PsiTreeUtil.getChildrenOfType(cptFile, CptMapping.class);
if (mappings != null) {
Collections.addAll(result, mappings);
}
}
}
return result;
}
public static String getDefaultTemplates(String language) {
InputStream stream = CptUtil.class.getResourceAsStream("defaulttemplates/" + language + ".postfixTemplates");
return getContent(stream);
}
public static String getContent(@NotNull File file) throws FileNotFoundException {
return getContent(new FileInputStream(file));
}
private static String getContent(@NotNull InputStream stream) {
StringBuilder sb = new StringBuilder();
// convert system newlines into UNIX newlines, because IDEA works only with UNIX newlines
try (BufferedReader in = new BufferedReader(new InputStreamReader(stream, "UTF-8"))) {
String line;
while ((line = in.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static File getPluginPath() {
File path = PluginManager.getPlugin(PluginId.getId(CptUtil.PLUGIN_ID)).getPath();
if (path.getName().endsWith(".jar")) {
path = new File(path.getParentFile(), path.getName().substring(0, path.getName().length() - 4));
}
return path;
}
public static File getTemplatesPath() {
return new File(getPluginPath(), "templates");
}
public static void createTemplateFile(@NotNull String language, String content) {
File file = new File(CptUtil.getTemplatesPath(), language + ".postfixTemplates");
//noinspection ResultOfMethodCallIgnored
file.getParentFile().mkdirs();
try (PrintStream out = new PrintStream(file, "UTF-8")) {
out.println(content);
out.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(language + " template file could not copied to " + file.getAbsolutePath(), e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 not supported", e);
}
}
public static Optional<File> getTemplateFile(@NotNull String language) {
if (SUPPORTED_LANGUAGES.contains(language.toLowerCase())) {
File file = new File(CptUtil.getTemplatesPath(), language + ".postfixTemplates");
if (!file.exists()) {
createTemplateFile(language, CptUtil.getDefaultTemplates(language));
}
return Optional.of(file);
} else {
return Optional.empty();
}
}
public static String getLanguageOfTemplateFile(@NotNull VirtualFile vFile) {
return vFile.getName().replaceAll("\\.postfixTemplates", "");
}
public static void openFileInEditor(@NotNull Project project, @NotNull File file) {
VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (vFile == null) {
vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
}
assert vFile != null;
openFileInEditor(project, vFile);
}
public static void openFileInEditor(@NotNull Project project, @NotNull VirtualFile vFile) {
// open templates file in an editor
new OpenFileDescriptor(project, vFile).navigate(true);
}
public static Project getActiveProject() {
DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult();
return DataKeys.PROJECT.getData(dataContext);
}
public static boolean isTemplateFile(VirtualFile vFile) {
return vFile != null && vFile.getCanonicalPath() != null &&
vFile.getCanonicalPath().replace('\\', '/').startsWith(CptUtil.getTemplatesPath().getAbsolutePath().replace('\\', '/'));
}
public static boolean isTemplateFile(VirtualFile vFile, String language) {
return vFile != null && vFile.getCanonicalPath() != null &&
vFile.getCanonicalPath().replace('\\', '/').startsWith(CptUtil.getTemplatesPath().getAbsolutePath().replace('\\', '/') + "/" + language);
}
@NotNull
public static String getTemplateSuffix() {
return CptApplicationSettings.getInstance().getPluginSettings().getTemplateSuffix();
}
}
| 7,006 | 0.737939 | 0.737225 | 205 | 33.17561 | 32.100277 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.15122 | false | false |
0
|
06b5253122f9edc0583deea9cf1883edc55d3e85
| 35,201,551,996,520 |
095b0f77ffdad9d735710c883d5dafd9b30f8379
|
/src/com/google/tagmanager/a/ba.java
|
945b686ba5bb81d2680eaa9f00e992f634650850
|
[] |
no_license
|
wubainian/smali_to_java
|
https://github.com/wubainian/smali_to_java
|
d49f9b1b9b5ae3b41e350cc17c84045bdc843cde
|
47cfc88bbe435a5289fb71a26d7b730db8366373
|
refs/heads/master
| 2021-01-10T01:52:44.648000 | 2016-03-10T12:10:09 | 2016-03-10T12:10:09 | 53,547,707 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.google.tagmanager.a
import java.util.Iterator;
final class ba implements Iterator{
//init method
ba(){
}
//ordinary method
public boolean hasNext(){
}
public Object next(){
}
public void remove(){
}
}
|
UTF-8
|
Java
| 247 |
java
|
ba.java
|
Java
|
[] | null |
[] |
package com.google.tagmanager.a
import java.util.Iterator;
final class ba implements Iterator{
//init method
ba(){
}
//ordinary method
public boolean hasNext(){
}
public Object next(){
}
public void remove(){
}
}
| 247 | 0.635628 | 0.635628 | 18 | 11.611111 | 12.13873 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false |
0
|
91521fd1a630377e90f6dc422f0a13a05816eaae
| 34,986,803,630,872 |
3611c6238a0ddc2031eb1a0cf2cf3fa9402b01a7
|
/src/main/java/launcher/Register.java
|
2fa835215882251c537ff0869a5dafbc7293b27f
|
[] |
no_license
|
shaykemelov/kz.iww.ttt
|
https://github.com/shaykemelov/kz.iww.ttt
|
dbbbcdb78a802a393158e859d7f9991e0ae329a6
|
1c763c2dba61c418fb434e2fda31176b049a30e0
|
refs/heads/master
| 2017-04-23T19:06:42.402000 | 2016-09-04T10:31:35 | 2016-09-04T10:31:35 | 64,480,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package launcher;
import main.Database;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
/**
* Created by iww on 7/26/16.
*/
class Register extends JPanel implements ActionListener {
private Launcher launcher;
private Database database;
private JTextField loginField;
private JPasswordField passwordField;
private JButton registerButton;
private JButton cancelButton;
Register(Launcher launcher, Database database) {
this.launcher = launcher;
this.database = database;
loginField = new JTextField();
loginField.setHorizontalAlignment(SwingConstants.CENTER);
passwordField = new JPasswordField();
passwordField.setHorizontalAlignment(SwingConstants.CENTER);
registerButton = new JButton("Register");
registerButton.setFocusable(false);
registerButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.setFocusable(false);
cancelButton.addActionListener(this);
setLayout(new GridBagLayout());
add(loginField, new GridBagConstraints(0, 0, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(75, 50, 1, 50), 0, 0));
add(passwordField, new GridBagConstraints(0, 1, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(1, 50, 1, 50), 0, 0));
add(registerButton, new GridBagConstraints(0, 2, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(1, 50, 1, 50), 0, 0));
add(cancelButton, new GridBagConstraints(0, 3, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(1, 50, 75, 50), 0, 0));
clearText();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == registerButton) {
register();
} else if (e.getSource() == cancelButton) {
cancel();
}
}
private void register() {
if (database.register(loginField.getText(), Arrays.toString(passwordField.getPassword()))) {
launcher.changePanel("login");
} else {
JOptionPane.showMessageDialog(launcher, "Try to use another login");
}
clearText();
}
private void cancel() {
clearText();
launcher.changePanel("login");
}
private void clearText() {
loginField.setText("Type login");
passwordField.setText("Password");
}
}
|
UTF-8
|
Java
| 2,704 |
java
|
Register.java
|
Java
|
[
{
"context": "tener;\nimport java.util.Arrays;\n\n/**\n * Created by iww on 7/26/16.\n */\n\nclass Register extends JPanel im",
"end": 203,
"score": 0.9994023442268372,
"start": 200,
"tag": "USERNAME",
"value": "iww"
},
{
"context": "ext(\"Type login\");\n passwordField.setText(\"Password\");\n }\n}\n",
"end": 2692,
"score": 0.9986544847488403,
"start": 2684,
"tag": "PASSWORD",
"value": "Password"
}
] | null |
[] |
package launcher;
import main.Database;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
/**
* Created by iww on 7/26/16.
*/
class Register extends JPanel implements ActionListener {
private Launcher launcher;
private Database database;
private JTextField loginField;
private JPasswordField passwordField;
private JButton registerButton;
private JButton cancelButton;
Register(Launcher launcher, Database database) {
this.launcher = launcher;
this.database = database;
loginField = new JTextField();
loginField.setHorizontalAlignment(SwingConstants.CENTER);
passwordField = new JPasswordField();
passwordField.setHorizontalAlignment(SwingConstants.CENTER);
registerButton = new JButton("Register");
registerButton.setFocusable(false);
registerButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.setFocusable(false);
cancelButton.addActionListener(this);
setLayout(new GridBagLayout());
add(loginField, new GridBagConstraints(0, 0, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(75, 50, 1, 50), 0, 0));
add(passwordField, new GridBagConstraints(0, 1, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(1, 50, 1, 50), 0, 0));
add(registerButton, new GridBagConstraints(0, 2, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(1, 50, 1, 50), 0, 0));
add(cancelButton, new GridBagConstraints(0, 3, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
new Insets(1, 50, 75, 50), 0, 0));
clearText();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == registerButton) {
register();
} else if (e.getSource() == cancelButton) {
cancel();
}
}
private void register() {
if (database.register(loginField.getText(), Arrays.toString(passwordField.getPassword()))) {
launcher.changePanel("login");
} else {
JOptionPane.showMessageDialog(launcher, "Try to use another login");
}
clearText();
}
private void cancel() {
clearText();
launcher.changePanel("login");
}
private void clearText() {
loginField.setText("Type login");
passwordField.setText("<PASSWORD>");
}
}
| 2,706 | 0.628698 | 0.605399 | 92 | 28.391304 | 24.658077 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.076087 | false | false |
0
|
fb0c90b1768940c6ebba826f183b56154aa123fd
| 29,978,871,794,959 |
4800bdf48bec1c478497c13c1430e60638b5f764
|
/ssosys2/src/main/java/com/zhicheng/ssosys/controller/BaseController.java
|
7bf3731fcaff7d90dc02c82da649d88a94d5c0b0
|
[] |
no_license
|
ludycool/ssoSys2
|
https://github.com/ludycool/ssoSys2
|
56b7bf0c31cf7fcb3c87b1e22e87624e4ea530d9
|
3b66ef767f59d1ce4f73a9f7fbfc48ad2b9a8f3d
|
refs/heads/master
| 2020-04-02T18:12:41.821000 | 2018-10-25T15:16:01 | 2018-10-25T15:16:01 | 154,690,911 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zhicheng.ssosys.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhicheng.ssosys.config.appConfig;
import com.zhicheng.ssosys.entity.RmsPermission;
import com.zhicheng.ssosys.entity.common.AdminUserInfo;
import com.zhicheng.ssosys.entity.common.Manu;
import com.zhicheng.ssosys.tool.FilterTools;
import com.zhicheng.ssosys.tool.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BaseController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
binder.registerCustomEditor(Integer.class,new CustomNumberEditor(Integer.class, false));
binder.registerCustomEditor(int.class,new CustomNumberEditor(Integer.class, false));
binder.registerCustomEditor(long.class,new CustomNumberEditor(Integer.class, false));
/*
private void createDefaultEditors() {
this.defaultEditors = new HashMap<Class, PropertyEditor>(64);
// Simple editors, without parameterization capabilities.
// The JDK does not contain a default editor for any of these target types.
this.defaultEditors.put(Charset.class, new CharsetEditor());
this.defaultEditors.put(Class.class, new ClassEditor());
this.defaultEditors.put(Class[].class, new ClassArrayEditor());
this.defaultEditors.put(Currency.class, new CurrencyEditor());
this.defaultEditors.put(File.class, new FileEditor());
this.defaultEditors.put(InputStream.class, new InputStreamEditor());
this.defaultEditors.put(InputSource.class, new InputSourceEditor());
this.defaultEditors.put(Locale.class, new LocaleEditor());
this.defaultEditors.put(Pattern.class, new PatternEditor());
this.defaultEditors.put(Properties.class, new PropertiesEditor());
this.defaultEditors.put(Resource[].class, new ResourceArrayPropertyEditor());
this.defaultEditors.put(TimeZone.class, new TimeZoneEditor());
this.defaultEditors.put(URI.class, new URIEditor());
this.defaultEditors.put(URL.class, new URLEditor());
this.defaultEditors.put(UUID.class, new UUIDEditor());
// Default instances of collection editors.
// Can be overridden by registering custom instances of those as custom editors.
this.defaultEditors.put(Collection.class, new CustomCollectionEditor(Collection.class));
this.defaultEditors.put(Set.class, new CustomCollectionEditor(Set.class));
this.defaultEditors.put(SortedSet.class, new CustomCollectionEditor(SortedSet.class));
this.defaultEditors.put(List.class, new CustomCollectionEditor(List.class));
this.defaultEditors.put(SortedMap.class, new CustomMapEditor(SortedMap.class));
// Default editors for primitive arrays.
this.defaultEditors.put(byte[].class, new ByteArrayPropertyEditor());
this.defaultEditors.put(char[].class, new CharArrayPropertyEditor());
// The JDK does not contain a default editor for char!
this.defaultEditors.put(char.class, new CharacterEditor(false));
this.defaultEditors.put(Character.class, new CharacterEditor(true));
// Spring's CustomBooleanEditor accepts more flag values than the JDK's default editor.
this.defaultEditors.put(boolean.class, new CustomBooleanEditor(false));
this.defaultEditors.put(Boolean.class, new CustomBooleanEditor(true));
// The JDK does not contain default editors for number wrapper types!
// Override JDK primitive number editors with our own CustomNumberEditor.
this.defaultEditors.put(byte.class, new CustomNumberEditor(Byte.class, false));
this.defaultEditors.put(Byte.class, new CustomNumberEditor(Byte.class, true));
this.defaultEditors.put(short.class, new CustomNumberEditor(Short.class, false));
this.defaultEditors.put(Short.class, new CustomNumberEditor(Short.class, true));
this.defaultEditors.put(int.class, new CustomNumberEditor(Integer.class, false));
this.defaultEditors.put(Integer.class, new CustomNumberEditor(Integer.class, true));
this.defaultEditors.put(long.class, new CustomNumberEditor(Long.class, false));
this.defaultEditors.put(Long.class, new CustomNumberEditor(Long.class, true));
this.defaultEditors.put(float.class, new CustomNumberEditor(Float.class, false));
this.defaultEditors.put(Float.class, new CustomNumberEditor(Float.class, true));
this.defaultEditors.put(double.class, new CustomNumberEditor(Double.class, false));
this.defaultEditors.put(Double.class, new CustomNumberEditor(Double.class, true));
this.defaultEditors.put(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true));
this.defaultEditors.put(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));
// Only register config value editors if explicitly requested.
if (this.configValueEditorsActive) {
StringArrayPropertyEditor sae = new StringArrayPropertyEditor();
this.defaultEditors.put(String[].class, sae);
this.defaultEditors.put(short[].class, sae);
this.defaultEditors.put(int[].class, sae);
this.defaultEditors.put(long[].class, sae);
}
}
*/
}
@Autowired
protected HttpServletRequest request;
public AdminUserInfo getUserData() {
AdminUserInfo item = (AdminUserInfo) request.getSession().getAttribute(appConfig.USER_SESSION_KEY);
return item;
}
public void setUserData(AdminUserInfo _item) {
request.getSession().setAttribute(appConfig.USER_SESSION_KEY, _item);
}
/// <summary>
///当前用户 是否是系统管理员
/// </summary>
/// <returns></returns>
public boolean IsSysRole() {
if (getUserData() == null)
return false;
return getUserData().getRoleId().equals(appConfig.getSysRoleId());
}
/// <summary>
/// 获取地址
/// </summary>
/// <returns></returns>
public String routeUrl() {
String url = "";
// url += request.getScheme() +"://";
//url +=request.getServerName();
// url +=":" +request.getServerPort();
url += request.getServletPath();
/*if (request.getQueryString() != null){
url += "?" + request.getQueryString();
}
*/
return " var BaseUrl = '" + url + "/';";
}
/// <summary>
/// 操作按键列表
/// </summary>
/// <param name="Ftype">1为 包含搜索,2 为不包含搜索</param>
/// <returns></returns>
public String toolbar(int Ftype)
{
String controller = request.getServletPath().replace("/","").toLowerCase();
String tool = " var toolbars =[";
String search = "";
int cout = 0;//统计
Manu ManuItem = getUserData().getListManusD().get(controller);
if (ManuItem != null)//
{
//3.0以上版本
for ( RmsPermission item : ManuItem.getHavebuttonsD()) {
//Map.entry<Integer,String> 映射项(键-值对) 有几个方法:用上面的名字entry
//entry.getKey() ;entry.getValue(); entry.setValue();
//map.entrySet() 返回此映射中包含的映射关系的 Set视图。
// System.out.println("key= " + item.getKey() + " and value= " + item.getValue());
if (Ftype == 2 && item.getUrl().toLowerCase().equals("search"))//搜索 不用添加进来
{
}
else
{
tool += "{";
tool += String.format("id: '%s',", item.getPcode());
tool += String.format("text: '%s',", item.getPname());
tool += String.format("iconCls: '%s',", item.getIcon());
tool += "handler: function () { " + item.getUrl() + "(); }}";
tool += ",'-',";
cout += 1;
}
}
if (cout > 0)
{
tool = tool.substring(0, tool.length() - 5);
}
}
tool += "];";
return tool + search;
}
public static String getWhereStr(String sqlSet) {
String[] data = sqlSet.split("█");
String sql = " 1=1 ";
if (!StringHelper.isEmpty(sqlSet)) {
for (int i = 0; i < data.length; i++) {
int index = data[i].indexOf(":");
String nameData = data[i].substring(0, index);
String[] name = nameData.split("_");
String value = FilterTools.FilterSpecial(data[i].substring(index + 1));
sql += " and " + getOP(name[0], name[1], value);
}
}
return sql;
}
public static String getOP(String name, String op, String values) {
//#region 多字段 模糊查询 如: OwnerName|OwnerCode|BuildingCode|HouseCode_like
String[] names = name.split("|");
if (names.length > 1) {
String sql = "(";
for (int i = 0; i < names.length; i++) {
if (op.equals("like")) {
sql += names[i] + " like N'%" + values + "%' ";
if (i != names.length - 1) {
sql += " or ";
}
}
}
sql += ")";
return sql;
}
switch (op) {
case "like"://all
return name + " like N'%" + values + "%' ";
case "like1":// 前固定
return name + " like N'" + values + "%' ";
case "like2"://后固定
return name + " like N'%" + values + "' ";
case "eq":
return name + " = '" + values + "' ";
case "lt":
return name + " < '" + values + "' ";
case "le":
return name + " <= '" + values + "' ";
case "gt":
return name + " > '" + values + "' ";
case "ge":
return name + " >= '" + values + "' ";
case "ne":
return name + " != '" + values + "' ";
default:
return "";
}
}
public static QueryWrapper getQueryWrapper(String sqlSet) {
QueryWrapper wrapper = new QueryWrapper<>();
if (!StringHelper.isEmpty(sqlSet)) {
String[] data = sqlSet.split("█");
for (int i = 0; i < data.length; i++) {
int index = data[i].indexOf(":");
String nameData = data[i].substring(0, index);
String[] name = nameData.split("_");
String value = FilterTools.FilterSpecial(data[i].substring(index + 1));
wrapper = getQwOP(name[0], name[1], value, wrapper);
}
}
return wrapper;
}
public static QueryWrapper getQwOP(String name, String op, String values, QueryWrapper wrapper) {
//#region 多字段 模糊查询 如: OwnerName|OwnerCode|BuildingCode|HouseCode_like
String[] names = name.split("\\|");
if (names.length > 1) {
for (int i = 0; i < names.length; i++) {
if (op.equals("like")) {
wrapper.like(names[i], values);
if (i != names.length - 1) {
wrapper.or();
}
}
}
return wrapper;
}
switch (op) {
case "like"://all
wrapper.like(name, values);
break;
case "like1":// 前固定
wrapper.likeRight(name, values);
break;
case "like2"://后固定
wrapper.likeLeft(name, values);
break;
case "eq":
wrapper.eq(name, values);
break;
case "lt":
wrapper.lt(name, values);
break;
case "le":
wrapper.le(name, values);
break;
case "gt":
wrapper.gt(name, values);
break;
case "ge":
wrapper.ge(name, values);
break;
case "ne":
wrapper.ne(name, values);
break;
default:
break;
}
return wrapper;
}
public static String getSqlSelect(String fields, String tablename, String whereStr, String orderStr) {
String sql = " select " + fields + " from " + tablename + " where " + whereStr + orderStr;
return sql;
}
}
|
UTF-8
|
Java
| 13,627 |
java
|
BaseController.java
|
Java
|
[] | null |
[] |
package com.zhicheng.ssosys.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhicheng.ssosys.config.appConfig;
import com.zhicheng.ssosys.entity.RmsPermission;
import com.zhicheng.ssosys.entity.common.AdminUserInfo;
import com.zhicheng.ssosys.entity.common.Manu;
import com.zhicheng.ssosys.tool.FilterTools;
import com.zhicheng.ssosys.tool.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BaseController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
binder.registerCustomEditor(Integer.class,new CustomNumberEditor(Integer.class, false));
binder.registerCustomEditor(int.class,new CustomNumberEditor(Integer.class, false));
binder.registerCustomEditor(long.class,new CustomNumberEditor(Integer.class, false));
/*
private void createDefaultEditors() {
this.defaultEditors = new HashMap<Class, PropertyEditor>(64);
// Simple editors, without parameterization capabilities.
// The JDK does not contain a default editor for any of these target types.
this.defaultEditors.put(Charset.class, new CharsetEditor());
this.defaultEditors.put(Class.class, new ClassEditor());
this.defaultEditors.put(Class[].class, new ClassArrayEditor());
this.defaultEditors.put(Currency.class, new CurrencyEditor());
this.defaultEditors.put(File.class, new FileEditor());
this.defaultEditors.put(InputStream.class, new InputStreamEditor());
this.defaultEditors.put(InputSource.class, new InputSourceEditor());
this.defaultEditors.put(Locale.class, new LocaleEditor());
this.defaultEditors.put(Pattern.class, new PatternEditor());
this.defaultEditors.put(Properties.class, new PropertiesEditor());
this.defaultEditors.put(Resource[].class, new ResourceArrayPropertyEditor());
this.defaultEditors.put(TimeZone.class, new TimeZoneEditor());
this.defaultEditors.put(URI.class, new URIEditor());
this.defaultEditors.put(URL.class, new URLEditor());
this.defaultEditors.put(UUID.class, new UUIDEditor());
// Default instances of collection editors.
// Can be overridden by registering custom instances of those as custom editors.
this.defaultEditors.put(Collection.class, new CustomCollectionEditor(Collection.class));
this.defaultEditors.put(Set.class, new CustomCollectionEditor(Set.class));
this.defaultEditors.put(SortedSet.class, new CustomCollectionEditor(SortedSet.class));
this.defaultEditors.put(List.class, new CustomCollectionEditor(List.class));
this.defaultEditors.put(SortedMap.class, new CustomMapEditor(SortedMap.class));
// Default editors for primitive arrays.
this.defaultEditors.put(byte[].class, new ByteArrayPropertyEditor());
this.defaultEditors.put(char[].class, new CharArrayPropertyEditor());
// The JDK does not contain a default editor for char!
this.defaultEditors.put(char.class, new CharacterEditor(false));
this.defaultEditors.put(Character.class, new CharacterEditor(true));
// Spring's CustomBooleanEditor accepts more flag values than the JDK's default editor.
this.defaultEditors.put(boolean.class, new CustomBooleanEditor(false));
this.defaultEditors.put(Boolean.class, new CustomBooleanEditor(true));
// The JDK does not contain default editors for number wrapper types!
// Override JDK primitive number editors with our own CustomNumberEditor.
this.defaultEditors.put(byte.class, new CustomNumberEditor(Byte.class, false));
this.defaultEditors.put(Byte.class, new CustomNumberEditor(Byte.class, true));
this.defaultEditors.put(short.class, new CustomNumberEditor(Short.class, false));
this.defaultEditors.put(Short.class, new CustomNumberEditor(Short.class, true));
this.defaultEditors.put(int.class, new CustomNumberEditor(Integer.class, false));
this.defaultEditors.put(Integer.class, new CustomNumberEditor(Integer.class, true));
this.defaultEditors.put(long.class, new CustomNumberEditor(Long.class, false));
this.defaultEditors.put(Long.class, new CustomNumberEditor(Long.class, true));
this.defaultEditors.put(float.class, new CustomNumberEditor(Float.class, false));
this.defaultEditors.put(Float.class, new CustomNumberEditor(Float.class, true));
this.defaultEditors.put(double.class, new CustomNumberEditor(Double.class, false));
this.defaultEditors.put(Double.class, new CustomNumberEditor(Double.class, true));
this.defaultEditors.put(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true));
this.defaultEditors.put(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));
// Only register config value editors if explicitly requested.
if (this.configValueEditorsActive) {
StringArrayPropertyEditor sae = new StringArrayPropertyEditor();
this.defaultEditors.put(String[].class, sae);
this.defaultEditors.put(short[].class, sae);
this.defaultEditors.put(int[].class, sae);
this.defaultEditors.put(long[].class, sae);
}
}
*/
}
@Autowired
protected HttpServletRequest request;
public AdminUserInfo getUserData() {
AdminUserInfo item = (AdminUserInfo) request.getSession().getAttribute(appConfig.USER_SESSION_KEY);
return item;
}
public void setUserData(AdminUserInfo _item) {
request.getSession().setAttribute(appConfig.USER_SESSION_KEY, _item);
}
/// <summary>
///当前用户 是否是系统管理员
/// </summary>
/// <returns></returns>
public boolean IsSysRole() {
if (getUserData() == null)
return false;
return getUserData().getRoleId().equals(appConfig.getSysRoleId());
}
/// <summary>
/// 获取地址
/// </summary>
/// <returns></returns>
public String routeUrl() {
String url = "";
// url += request.getScheme() +"://";
//url +=request.getServerName();
// url +=":" +request.getServerPort();
url += request.getServletPath();
/*if (request.getQueryString() != null){
url += "?" + request.getQueryString();
}
*/
return " var BaseUrl = '" + url + "/';";
}
/// <summary>
/// 操作按键列表
/// </summary>
/// <param name="Ftype">1为 包含搜索,2 为不包含搜索</param>
/// <returns></returns>
public String toolbar(int Ftype)
{
String controller = request.getServletPath().replace("/","").toLowerCase();
String tool = " var toolbars =[";
String search = "";
int cout = 0;//统计
Manu ManuItem = getUserData().getListManusD().get(controller);
if (ManuItem != null)//
{
//3.0以上版本
for ( RmsPermission item : ManuItem.getHavebuttonsD()) {
//Map.entry<Integer,String> 映射项(键-值对) 有几个方法:用上面的名字entry
//entry.getKey() ;entry.getValue(); entry.setValue();
//map.entrySet() 返回此映射中包含的映射关系的 Set视图。
// System.out.println("key= " + item.getKey() + " and value= " + item.getValue());
if (Ftype == 2 && item.getUrl().toLowerCase().equals("search"))//搜索 不用添加进来
{
}
else
{
tool += "{";
tool += String.format("id: '%s',", item.getPcode());
tool += String.format("text: '%s',", item.getPname());
tool += String.format("iconCls: '%s',", item.getIcon());
tool += "handler: function () { " + item.getUrl() + "(); }}";
tool += ",'-',";
cout += 1;
}
}
if (cout > 0)
{
tool = tool.substring(0, tool.length() - 5);
}
}
tool += "];";
return tool + search;
}
public static String getWhereStr(String sqlSet) {
String[] data = sqlSet.split("█");
String sql = " 1=1 ";
if (!StringHelper.isEmpty(sqlSet)) {
for (int i = 0; i < data.length; i++) {
int index = data[i].indexOf(":");
String nameData = data[i].substring(0, index);
String[] name = nameData.split("_");
String value = FilterTools.FilterSpecial(data[i].substring(index + 1));
sql += " and " + getOP(name[0], name[1], value);
}
}
return sql;
}
public static String getOP(String name, String op, String values) {
//#region 多字段 模糊查询 如: OwnerName|OwnerCode|BuildingCode|HouseCode_like
String[] names = name.split("|");
if (names.length > 1) {
String sql = "(";
for (int i = 0; i < names.length; i++) {
if (op.equals("like")) {
sql += names[i] + " like N'%" + values + "%' ";
if (i != names.length - 1) {
sql += " or ";
}
}
}
sql += ")";
return sql;
}
switch (op) {
case "like"://all
return name + " like N'%" + values + "%' ";
case "like1":// 前固定
return name + " like N'" + values + "%' ";
case "like2"://后固定
return name + " like N'%" + values + "' ";
case "eq":
return name + " = '" + values + "' ";
case "lt":
return name + " < '" + values + "' ";
case "le":
return name + " <= '" + values + "' ";
case "gt":
return name + " > '" + values + "' ";
case "ge":
return name + " >= '" + values + "' ";
case "ne":
return name + " != '" + values + "' ";
default:
return "";
}
}
public static QueryWrapper getQueryWrapper(String sqlSet) {
QueryWrapper wrapper = new QueryWrapper<>();
if (!StringHelper.isEmpty(sqlSet)) {
String[] data = sqlSet.split("█");
for (int i = 0; i < data.length; i++) {
int index = data[i].indexOf(":");
String nameData = data[i].substring(0, index);
String[] name = nameData.split("_");
String value = FilterTools.FilterSpecial(data[i].substring(index + 1));
wrapper = getQwOP(name[0], name[1], value, wrapper);
}
}
return wrapper;
}
public static QueryWrapper getQwOP(String name, String op, String values, QueryWrapper wrapper) {
//#region 多字段 模糊查询 如: OwnerName|OwnerCode|BuildingCode|HouseCode_like
String[] names = name.split("\\|");
if (names.length > 1) {
for (int i = 0; i < names.length; i++) {
if (op.equals("like")) {
wrapper.like(names[i], values);
if (i != names.length - 1) {
wrapper.or();
}
}
}
return wrapper;
}
switch (op) {
case "like"://all
wrapper.like(name, values);
break;
case "like1":// 前固定
wrapper.likeRight(name, values);
break;
case "like2"://后固定
wrapper.likeLeft(name, values);
break;
case "eq":
wrapper.eq(name, values);
break;
case "lt":
wrapper.lt(name, values);
break;
case "le":
wrapper.le(name, values);
break;
case "gt":
wrapper.gt(name, values);
break;
case "ge":
wrapper.ge(name, values);
break;
case "ne":
wrapper.ne(name, values);
break;
default:
break;
}
return wrapper;
}
public static String getSqlSelect(String fields, String tablename, String whereStr, String orderStr) {
String sql = " select " + fields + " from " + tablename + " where " + whereStr + orderStr;
return sql;
}
}
| 13,627 | 0.558202 | 0.555663 | 351 | 36.156696 | 30.307652 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.797721 | false | false |
0
|
95bf36fdda724e498e0b63dd70e83757e996bd4b
| 31,301,721,713,083 |
a14ddbbfe1fd018f32c4306621eddf824cdbbaf1
|
/app/src/main/java/com/singwai/currenttoptennews/fragment/HomeFragment.java
|
d12d52b30233b73192fb65ea641be119b705c4e4
|
[
"Apache-2.0"
] |
permissive
|
Singwai/AndroidGetTopTenCurrentNews
|
https://github.com/Singwai/AndroidGetTopTenCurrentNews
|
7e07b045f75ed5b3861597eee563d502025ead74
|
77f07ced3b71cbe09b2623193d2c1c743056ebbc
|
refs/heads/master
| 2016-09-06T13:10:04.547000 | 2015-02-07T18:11:12 | 2015-02-07T18:11:12 | 30,172,671 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.singwai.currenttoptennews.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.NumberPicker;
import android.widget.Spinner;
import com.singwai.currenttoptennews.activity.NewsActivity;
import com.singwai.currenttoptennews.R;
import com.singwai.currenttoptennews.configutation.Configuration;
/**
* Created by Singwai Chan on 2/1/15.
*/
public class HomeFragment extends BaseFragment implements View.OnClickListener {
private Configuration configuration;
//Views
private View rootView;
private CheckBox mCheckBox;
private NumberPicker mNumberPicker;
private Spinner mSpinner;
private Button mButton;
private Button resetButton;
//Grab all declare all non-view information here.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configuration = Configuration.get_instance();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (rootView == null) {
rootView = inflater.inflate(R.layout.fragment_setting, null);
}
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
//Get All the views.
mCheckBox = (CheckBox) rootView.findViewById(R.id.checkbox);
mNumberPicker = (NumberPicker) rootView.findViewById(R.id.numberPickerAutoSwapTimer);
mNumberPicker.setMaxValue(60);
mNumberPicker.setMinValue(3);
mSpinner = (Spinner) rootView.findViewById(R.id.spinnerNewsSection);
mButton = (Button)rootView.findViewById(R.id.buttonGetNews);
mButton.setOnClickListener(this);
//Fill Configuration data;
setConfigurationViews();
return rootView;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.buttonGetNews){
//Save Configuration
getConfigurationDataFromViews();
Configuration.saveConfiguration();
//Go to NewsActivity
Intent i = new Intent(this.getActivity(), NewsActivity.class);
this.getActivity().startActivity(i);
//((HomeActivity) this.getActivity()).getLatestNews(configuration.getNewsSectionPosition());
}
}
public void getConfigurationDataFromViews (){
configuration.setAutoSwap(mCheckBox.isChecked());
configuration.setAutoSwapTime(mNumberPicker.getValue());
configuration.setNewsSectionPosition(mSpinner.getSelectedItemPosition());
}
public void setConfigurationViews() {
Log.e("Filling date", " ");
Configuration.print();
mCheckBox.setChecked(configuration.getAutoSwap());
mNumberPicker.setValue(configuration.getAutoSwapTime());
mSpinner.setSelection(configuration.getNewsSectionPosition());
}
}
|
UTF-8
|
Java
| 3,205 |
java
|
HomeFragment.java
|
Java
|
[
{
"context": "ws.configutation.Configuration;\n\n/**\n * Created by Singwai Chan on 2/1/15.\n */\npublic class HomeFragment extends ",
"end": 551,
"score": 0.9997522234916687,
"start": 539,
"tag": "NAME",
"value": "Singwai Chan"
}
] | null |
[] |
package com.singwai.currenttoptennews.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.NumberPicker;
import android.widget.Spinner;
import com.singwai.currenttoptennews.activity.NewsActivity;
import com.singwai.currenttoptennews.R;
import com.singwai.currenttoptennews.configutation.Configuration;
/**
* Created by <NAME> on 2/1/15.
*/
public class HomeFragment extends BaseFragment implements View.OnClickListener {
private Configuration configuration;
//Views
private View rootView;
private CheckBox mCheckBox;
private NumberPicker mNumberPicker;
private Spinner mSpinner;
private Button mButton;
private Button resetButton;
//Grab all declare all non-view information here.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configuration = Configuration.get_instance();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (rootView == null) {
rootView = inflater.inflate(R.layout.fragment_setting, null);
}
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
//Get All the views.
mCheckBox = (CheckBox) rootView.findViewById(R.id.checkbox);
mNumberPicker = (NumberPicker) rootView.findViewById(R.id.numberPickerAutoSwapTimer);
mNumberPicker.setMaxValue(60);
mNumberPicker.setMinValue(3);
mSpinner = (Spinner) rootView.findViewById(R.id.spinnerNewsSection);
mButton = (Button)rootView.findViewById(R.id.buttonGetNews);
mButton.setOnClickListener(this);
//Fill Configuration data;
setConfigurationViews();
return rootView;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.buttonGetNews){
//Save Configuration
getConfigurationDataFromViews();
Configuration.saveConfiguration();
//Go to NewsActivity
Intent i = new Intent(this.getActivity(), NewsActivity.class);
this.getActivity().startActivity(i);
//((HomeActivity) this.getActivity()).getLatestNews(configuration.getNewsSectionPosition());
}
}
public void getConfigurationDataFromViews (){
configuration.setAutoSwap(mCheckBox.isChecked());
configuration.setAutoSwapTime(mNumberPicker.getValue());
configuration.setNewsSectionPosition(mSpinner.getSelectedItemPosition());
}
public void setConfigurationViews() {
Log.e("Filling date", " ");
Configuration.print();
mCheckBox.setChecked(configuration.getAutoSwap());
mNumberPicker.setValue(configuration.getAutoSwapTime());
mSpinner.setSelection(configuration.getNewsSectionPosition());
}
}
| 3,199 | 0.699532 | 0.697348 | 100 | 31.049999 | 26.402037 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57 | false | false |
0
|
f76e9f58c8a7c1e63d4c1232bf75fd3b51aa8363
| 31,301,721,714,871 |
81a30b67e6425c981277f0684a6aab9f6a08f52f
|
/src/main/java/actions/mappers/DeleteAPIMapper.java
|
8a05a9edee90146312abdd23a11051054415718e
|
[] |
no_license
|
rajat007kamra/cliq20
|
https://github.com/rajat007kamra/cliq20
|
edf3883550b798a28bf18d89df16192266818fbc
|
6d84cf6eef6b52257046750cd547858763296bc2
|
refs/heads/master
| 2023-04-10T02:37:22.345000 | 2021-04-14T09:03:00 | 2021-04-14T09:03:00 | 357,839,629 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package actions.mappers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import core.api.model.ApiModel;
import core.api.model.Context;
import core.api.model.Header;
import core.api.model.Response;
import core.cliqdb.model.SectionData;
import core.cliqdb.model.StepContext;
import core.cliqdb.model.TestcaseJsonData;
public class DeleteAPIMapper implements Mapper {
private ApiModel apiModel;
public DeleteAPIMapper() {
this.apiModel = new ApiModel();
}
@Override
public List<String> getMappedAction(SectionData sectionData, StepContext stepContext) {
// TODO Auto-generated method stub
return null;
}
/**
* This method is responsible for fetching data from TESTCASE SCREEN
*
*/
public List<String> getMappedAction(List<SectionData> sections, Map<String, Map<String, String>> screenData,
Map<String, String> mZoneData, TestcaseJsonData testJsonData) {
List<String> actionString = new ArrayList<String>();
List<Header> headerList = new ArrayList<Header>();
SectionData inputAPISection = getInputAPISection(sections);
SectionData checkAPISection = getCheckAPISection(sections);
SectionData uploadSection = getUploadSection(sections);
Context context = new Context();
context.setApi(inputAPISection.getSectionContext().get(0).get("CALL STRING"));
context.setApiVersion(inputAPISection.getSectionContext().get(0).get("VERSION"));
Header contentType = new Header();
contentType.setName("Content-Type");
contentType.setValue("application/json");
Header authHeader = new Header();
authHeader.setName("Authorization");
authHeader.setValue(inputAPISection.getSectionContext().get(0).get("JWT TOKEN"));
headerList.add(contentType);
headerList.add(authHeader);
context.setHeader(headerList);
context.setBody(inputAPISection.getSectionContext().get(0).get("JSON"));
Response response = new Response();
response.setStatuscode(checkAPISection.getSectionContext().get(0).get("HTTP CODE"));
response.setStatusmessage(checkAPISection.getSectionContext().get(0).get("HTTP MESSAGE"));
context.setResponse(response);
this.apiModel.setContext(context);
this.apiModel.setName(testJsonData.getApiMethod());
String actionJson = new Gson().toJson(this.apiModel);
actionString.add(actionJson);
return actionString;
}
private SectionData getInputAPISection(List<SectionData> sections) {
for (SectionData sectionData : sections) {
if (sectionData.getName().equalsIgnoreCase("INPUT-API")) {
return sectionData;
}
}
return null;
}
private SectionData getCheckAPISection(List<SectionData> sections) {
for (SectionData sectionData : sections) {
if (sectionData.getName().equalsIgnoreCase("CHECK-API")) {
return sectionData;
}
}
return null;
}
private SectionData getUploadSection(List<SectionData> sections) {
for (SectionData sectionData : sections) {
if (sectionData.getName().equalsIgnoreCase("UPLOAD")) {
return sectionData;
}
}
return null;
}
}
|
UTF-8
|
Java
| 3,023 |
java
|
DeleteAPIMapper.java
|
Java
|
[] | null |
[] |
package actions.mappers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import core.api.model.ApiModel;
import core.api.model.Context;
import core.api.model.Header;
import core.api.model.Response;
import core.cliqdb.model.SectionData;
import core.cliqdb.model.StepContext;
import core.cliqdb.model.TestcaseJsonData;
public class DeleteAPIMapper implements Mapper {
private ApiModel apiModel;
public DeleteAPIMapper() {
this.apiModel = new ApiModel();
}
@Override
public List<String> getMappedAction(SectionData sectionData, StepContext stepContext) {
// TODO Auto-generated method stub
return null;
}
/**
* This method is responsible for fetching data from TESTCASE SCREEN
*
*/
public List<String> getMappedAction(List<SectionData> sections, Map<String, Map<String, String>> screenData,
Map<String, String> mZoneData, TestcaseJsonData testJsonData) {
List<String> actionString = new ArrayList<String>();
List<Header> headerList = new ArrayList<Header>();
SectionData inputAPISection = getInputAPISection(sections);
SectionData checkAPISection = getCheckAPISection(sections);
SectionData uploadSection = getUploadSection(sections);
Context context = new Context();
context.setApi(inputAPISection.getSectionContext().get(0).get("CALL STRING"));
context.setApiVersion(inputAPISection.getSectionContext().get(0).get("VERSION"));
Header contentType = new Header();
contentType.setName("Content-Type");
contentType.setValue("application/json");
Header authHeader = new Header();
authHeader.setName("Authorization");
authHeader.setValue(inputAPISection.getSectionContext().get(0).get("JWT TOKEN"));
headerList.add(contentType);
headerList.add(authHeader);
context.setHeader(headerList);
context.setBody(inputAPISection.getSectionContext().get(0).get("JSON"));
Response response = new Response();
response.setStatuscode(checkAPISection.getSectionContext().get(0).get("HTTP CODE"));
response.setStatusmessage(checkAPISection.getSectionContext().get(0).get("HTTP MESSAGE"));
context.setResponse(response);
this.apiModel.setContext(context);
this.apiModel.setName(testJsonData.getApiMethod());
String actionJson = new Gson().toJson(this.apiModel);
actionString.add(actionJson);
return actionString;
}
private SectionData getInputAPISection(List<SectionData> sections) {
for (SectionData sectionData : sections) {
if (sectionData.getName().equalsIgnoreCase("INPUT-API")) {
return sectionData;
}
}
return null;
}
private SectionData getCheckAPISection(List<SectionData> sections) {
for (SectionData sectionData : sections) {
if (sectionData.getName().equalsIgnoreCase("CHECK-API")) {
return sectionData;
}
}
return null;
}
private SectionData getUploadSection(List<SectionData> sections) {
for (SectionData sectionData : sections) {
if (sectionData.getName().equalsIgnoreCase("UPLOAD")) {
return sectionData;
}
}
return null;
}
}
| 3,023 | 0.756202 | 0.754218 | 100 | 29.23 | 27.173096 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.84 | false | false |
0
|
9072c525e638b069e4f78cb089e29fe7a99b1787
| 31,301,721,712,992 |
86f6d141ed8647f18b2ea1744dacd8f9e1774e79
|
/src/rush/itensespeciais/addons/McMMO.java
|
34cf4ab12744e48c86e17a279515872b949948af
|
[] |
no_license
|
LeoHandler/MambaItensEspeciais
|
https://github.com/LeoHandler/MambaItensEspeciais
|
fce1860de892d41a1e245b25192e2bfdfd4795ec
|
139b80af8f46aef0bd53e047b88b6d5efa8294f8
|
refs/heads/master
| 2023-03-17T07:53:45.342000 | 2020-05-16T15:55:07 | 2020-05-16T15:55:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package rush.itensespeciais.addons;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityActivateEvent;
import rush.itensespeciais.itens.Itens;
public class McMMO implements Listener {
@EventHandler
public void aoAtivarSkill(McMMOPlayerAbilityActivateEvent e) {
if (e.getAbility() == AbilityType.SUPER_BREAKER) {
if (e.getPlayer().getItemInHand().isSimilar(Itens.PICARETA)) {
e.setCancelled(true);
}
}
}
}
|
UTF-8
|
Java
| 571 |
java
|
McMMO.java
|
Java
|
[
{
"context": "rt org.bukkit.event.Listener;\n\nimport com.gmail.nossr50.datatypes.skills.AbilityType;\nimport com.gmail.no",
"end": 134,
"score": 0.8167888522148132,
"start": 129,
"tag": "USERNAME",
"value": "ssr50"
},
{
"context": ".datatypes.skills.AbilityType;\nimport com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityActivat",
"end": 189,
"score": 0.7791954874992371,
"start": 184,
"tag": "USERNAME",
"value": "ssr50"
}
] | null |
[] |
package rush.itensespeciais.addons;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import com.gmail.nossr50.datatypes.skills.AbilityType;
import com.gmail.nossr50.events.skills.abilities.McMMOPlayerAbilityActivateEvent;
import rush.itensespeciais.itens.Itens;
public class McMMO implements Listener {
@EventHandler
public void aoAtivarSkill(McMMOPlayerAbilityActivateEvent e) {
if (e.getAbility() == AbilityType.SUPER_BREAKER) {
if (e.getPlayer().getItemInHand().isSimilar(Itens.PICARETA)) {
e.setCancelled(true);
}
}
}
}
| 571 | 0.781086 | 0.774081 | 22 | 25 | 25.479046 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.181818 | false | false |
0
|
63d3fa57b11404f7ccd507d7684bf215a90d79d8
| 37,434,934,968,293 |
c3f30c8c75e63335e299f1ea63769034d158a032
|
/blerpc/src/test/java/com/blerpc/AssertTest.java
|
4ca9b30a2ef22d4beecbf9938e62c9d0cfff9f88
|
[
"MIT"
] |
permissive
|
Monnoroch/blerpc-android
|
https://github.com/Monnoroch/blerpc-android
|
fbbc361552a4a6c660185b92f94e4a7f47768cd8
|
191162def0df9dc65fa480c68e8cb5b9932e056d
|
refs/heads/master
| 2023-04-22T19:13:32.920000 | 2020-05-19T11:55:27 | 2020-05-19T11:55:27 | 115,001,774 | 3 | 4 |
MIT
| false | 2021-05-14T06:14:26 | 2017-12-21T12:07:48 | 2020-05-19T11:55:31 | 2021-05-14T06:13:31 | 1,753 | 2 | 2 | 23 |
Java
| false | false |
package com.blerpc;
import static com.blerpc.Assert.assertError;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import junit.framework.AssertionFailedError;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Tests for {@link Assert}.
*/
@RunWith(MockitoJUnitRunner.class)
public class AssertTest {
private static final String ERROR_MESSAGE = "error message";
private static final String WRONG_ERROR_MESSAGE = "wrong message";
@Test
public void assertError_throwError() {
assertError(() -> {
throw new RuntimeException(ERROR_MESSAGE);
}, ERROR_MESSAGE);
}
@Test
public void assertError_notThrowError() {
try {
assertError(() -> {
// Do nothing
}, ERROR_MESSAGE);
fail("assertError() method must throw an error if execution had no errors");
} catch (AssertionFailedError error) {
assertThat(error.getMessage()).contains("Error was expected: error message");
}
}
@Test
public void assertError_wrongErrorMessage() {
try {
assertError(() -> {
throw new RuntimeException(WRONG_ERROR_MESSAGE);
}, ERROR_MESSAGE);
fail("assertError() method must throw an error if execution error not contains expected message");
} catch (AssertionError error) {
assertThat(error.getMessage()).contains("Not true that <\"wrong message\"> contains <\"error message\">");
}
}
}
|
UTF-8
|
Java
| 1,486 |
java
|
AssertTest.java
|
Java
|
[] | null |
[] |
package com.blerpc;
import static com.blerpc.Assert.assertError;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import junit.framework.AssertionFailedError;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Tests for {@link Assert}.
*/
@RunWith(MockitoJUnitRunner.class)
public class AssertTest {
private static final String ERROR_MESSAGE = "error message";
private static final String WRONG_ERROR_MESSAGE = "wrong message";
@Test
public void assertError_throwError() {
assertError(() -> {
throw new RuntimeException(ERROR_MESSAGE);
}, ERROR_MESSAGE);
}
@Test
public void assertError_notThrowError() {
try {
assertError(() -> {
// Do nothing
}, ERROR_MESSAGE);
fail("assertError() method must throw an error if execution had no errors");
} catch (AssertionFailedError error) {
assertThat(error.getMessage()).contains("Error was expected: error message");
}
}
@Test
public void assertError_wrongErrorMessage() {
try {
assertError(() -> {
throw new RuntimeException(WRONG_ERROR_MESSAGE);
}, ERROR_MESSAGE);
fail("assertError() method must throw an error if execution error not contains expected message");
} catch (AssertionError error) {
assertThat(error.getMessage()).contains("Not true that <\"wrong message\"> contains <\"error message\">");
}
}
}
| 1,486 | 0.693136 | 0.693136 | 51 | 28.137255 | 27.313015 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.431373 | false | false |
0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.