code
stringlengths 10
749k
| repo_name
stringlengths 5
108
| path
stringlengths 7
333
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 10
749k
|
---|---|---|---|---|---|
package org.kohsuke.github;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static java.lang.String.*;
/**
* Release in a github repository.
*
* @see GHRepository#getReleases() GHRepository#getReleases()
* @see GHRepository#listReleases() () GHRepository#listReleases()
* @see GHRepository#createRelease(String) GHRepository#createRelease(String)
*/
public class GHRelease extends GHObject {
GHRepository owner;
private String html_url;
private String assets_url;
private List<GHAsset> assets;
private String upload_url;
private String tag_name;
private String target_commitish;
private String name;
private String body;
private boolean draft;
private boolean prerelease;
private Date published_at;
private String tarball_url;
private String zipball_url;
private String discussion_url;
/**
* Gets discussion url. Only present if a discussion relating to the release exists
*
* @return the discussion url
*/
public String getDiscussionUrl() {
return discussion_url;
}
/**
* Gets assets url.
*
* @return the assets url
*/
public String getAssetsUrl() {
return assets_url;
}
/**
* Gets body.
*
* @return the body
*/
public String getBody() {
return body;
}
/**
* Is draft boolean.
*
* @return the boolean
*/
public boolean isDraft() {
return draft;
}
/**
* Sets draft.
*
* @param draft
* the draft
* @return the draft
* @throws IOException
* the io exception
* @deprecated Use {@link #update()}
*/
@Deprecated
public GHRelease setDraft(boolean draft) throws IOException {
return update().draft(draft).update();
}
public URL getHtmlUrl() {
return GitHubClient.parseURL(html_url);
}
/**
* Gets name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets name.
*
* @param name
* the name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets owner.
*
* @return the owner
*/
@SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected behavior")
public GHRepository getOwner() {
return owner;
}
/**
* Sets owner.
*
* @param owner
* the owner
* @deprecated Do not use this method. It was added due to incomplete understanding of Jackson binding.
*/
@Deprecated
public void setOwner(GHRepository owner) {
throw new RuntimeException("Do not use this method.");
}
/**
* Is prerelease boolean.
*
* @return the boolean
*/
public boolean isPrerelease() {
return prerelease;
}
/**
* Gets published at.
*
* @return the published at
*/
public Date getPublished_at() {
return new Date(published_at.getTime());
}
/**
* Gets tag name.
*
* @return the tag name
*/
public String getTagName() {
return tag_name;
}
/**
* Gets target commitish.
*
* @return the target commitish
*/
public String getTargetCommitish() {
return target_commitish;
}
/**
* Gets upload url.
*
* @return the upload url
*/
public String getUploadUrl() {
return upload_url;
}
/**
* Gets zipball url.
*
* @return the zipball url
*/
public String getZipballUrl() {
return zipball_url;
}
/**
* Gets tarball url.
*
* @return the tarball url
*/
public String getTarballUrl() {
return tarball_url;
}
GHRelease wrap(GHRepository owner) {
this.owner = owner;
return this;
}
static GHRelease[] wrap(GHRelease[] releases, GHRepository owner) {
for (GHRelease release : releases) {
release.wrap(owner);
}
return releases;
}
/**
* Because github relies on SNI (http://en.wikipedia.org/wiki/Server_Name_Indication) this method will only work on
* Java 7 or greater. Options for fixing this for earlier JVMs can be found here
* http://stackoverflow.com/questions/12361090/server-name-indication-sni-on-java but involve more complicated
* handling of the HTTP requests to github's API.
*
* @param file
* the file
* @param contentType
* the content type
* @return the gh asset
* @throws IOException
* the io exception
*/
public GHAsset uploadAsset(File file, String contentType) throws IOException {
FileInputStream s = new FileInputStream(file);
try {
return uploadAsset(file.getName(), s, contentType);
} finally {
s.close();
}
}
/**
* Upload asset gh asset.
*
* @param filename
* the filename
* @param stream
* the stream
* @param contentType
* the content type
* @return the gh asset
* @throws IOException
* the io exception
*/
public GHAsset uploadAsset(String filename, InputStream stream, String contentType) throws IOException {
Requester builder = owner.root().createRequest().method("POST");
String url = getUploadUrl();
// strip the helpful garbage from the url
url = url.substring(0, url.indexOf('{'));
url += "?name=" + URLEncoder.encode(filename, "UTF-8");
return builder.contentType(contentType).with(stream).withUrlPath(url).fetch(GHAsset.class).wrap(this);
}
/**
* Get the cached assets.
*
* @return the assets
*
* @deprecated This should be the default behavior of {@link #getAssets()} in a future release. This method is
* introduced in addition to enable a transition to using cached asset information while keeping the
* existing logic in place for backwards compatibility.
*/
@Deprecated
public List<GHAsset> assets() {
return Collections.unmodifiableList(assets);
}
/**
* Re-fetch the assets of this release.
*
* @return the assets
* @throws IOException
* the io exception
* @deprecated The behavior of this method will change in a future release. It will then provide cached assets as
* provided by {@link #assets()}. Use {@link #listAssets()} instead to fetch up-to-date information of
* assets.
*/
@Deprecated
public List<GHAsset> getAssets() throws IOException {
return listAssets().toList();
}
/**
* Re-fetch the assets of this release.
*
* @return the assets
* @throws IOException
* the io exception
*/
public PagedIterable<GHAsset> listAssets() throws IOException {
Requester builder = owner.root().createRequest();
return builder.withUrlPath(getApiTailUrl("assets")).toIterable(GHAsset[].class, item -> item.wrap(this));
}
/**
* Deletes this release.
*
* @throws IOException
* the io exception
*/
public void delete() throws IOException {
root().createRequest().method("DELETE").withUrlPath(owner.getApiTailUrl("releases/" + getId())).send();
}
/**
* Updates this release via a builder.
*
* @return the gh release updater
*/
public GHReleaseUpdater update() {
return new GHReleaseUpdater(this);
}
private String getApiTailUrl(String end) {
return owner.getApiTailUrl(format("releases/%s/%s", getId(), end));
}
}
| kohsuke/github-api | src/main/java/org/kohsuke/github/GHRelease.java | Java | mit | 8,107 |
package com.lynx.service;
import java.util.Collection;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.lynx.domain.User;
import com.lynx.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Optional<User> getUserById(String id) {
log.debug("Getting user={}", id);
return Optional.ofNullable(userRepository.findOne(id));
}
public Optional<User> getUserByEmail(String email) {
log.debug("Getting user by email={}", email.replaceFirst("@.*", "@***"));
return userRepository.findOneByEmail(email);
}
public Collection<User> getAllUsers() {
log.debug("Getting all users");
return userRepository.findAll(new Sort("email"));
}
public User create(User user) {
return userRepository.save(user);
}
}
| 6o1/lynx-server | src/main/java/com/lynx/service/UserService.java | Java | mit | 978 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.09.02 at 01:00:06 PM UYT
//
package dgi.classes.respuestas.reporte;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for RSAKeyValueType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RSAKeyValueType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Modulus" type="{http://www.w3.org/2000/09/xmldsig#}CryptoBinary"/>
* <element name="Exponent" type="{http://www.w3.org/2000/09/xmldsig#}CryptoBinary"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RSAKeyValueType", propOrder = {
"modulus",
"exponent"
})
public class RSAKeyValueType {
@XmlElement(name = "Modulus", required = true)
protected byte[] modulus;
@XmlElement(name = "Exponent", required = true)
protected byte[] exponent;
/**
* Gets the value of the modulus property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getModulus() {
return modulus;
}
/**
* Sets the value of the modulus property.
*
* @param value
* allowed object is
* byte[]
*/
public void setModulus(byte[] value) {
this.modulus = value;
}
/**
* Gets the value of the exponent property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getExponent() {
return exponent;
}
/**
* Sets the value of the exponent property.
*
* @param value
* allowed object is
* byte[]
*/
public void setExponent(byte[] value) {
this.exponent = value;
}
}
| nicoribeiro/java_efactura_uy | app/dgi/classes/respuestas/reporte/RSAKeyValueType.java | Java | mit | 2,365 |
package cn.jzvd.demo;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
/**
* Created by Nathen
* On 2016/05/23 21:34
*/
public class ActivityListViewMultiHolder extends AppCompatActivity {
ListView listView;
VideoListAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview_normal);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setTitle("MultiHolderListView");
listView = findViewById(R.id.listview);
mAdapter = new VideoListAdapter(this);
listView.setAdapter(mAdapter);
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (Jzvd.CURRENT_JZVD == null) return;
int lastVisibleItem = firstVisibleItem + visibleItemCount;
int currentPlayPosition = Jzvd.CURRENT_JZVD.positionInList;
// Log.e(TAG, "onScrollReleaseAllVideos: " +
// currentPlayPosition + " " + firstVisibleItem + " " + currentPlayPosition + " " + lastVisibleItem);
if (currentPlayPosition >= 0) {
if ((currentPlayPosition < firstVisibleItem || currentPlayPosition > (lastVisibleItem - 1))) {
if (Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
Jzvd.releaseAllVideos();//为什么最后一个视频横屏会调用这个,其他地方不会
}
}
}
}
});
}
@Override
public void onBackPressed() {
if (Jzvd.backPress()) {
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
Jzvd.releaseAllVideos();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public class VideoListAdapter extends BaseAdapter {
int[] viewtype = {0, 0, 0, 1, 0, 0, 0, 1, 0, 0};//1 = jzvdStd, 0 = textView
Context context;
LayoutInflater mInflater;
public VideoListAdapter(Context context) {
this.context = context;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return viewtype.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == 1) {
VideoHolder viewHolder;
if (convertView != null && convertView.getTag() != null && convertView.getTag() instanceof VideoHolder) {
viewHolder = (VideoHolder) convertView.getTag();
} else {
viewHolder = new VideoHolder();
convertView = mInflater.inflate(R.layout.item_videoview, null);
viewHolder.jzvdStd = convertView.findViewById(R.id.videoplayer);
convertView.setTag(viewHolder);
}
viewHolder.jzvdStd.setUp(
VideoConstant.videoUrls[0][position],
VideoConstant.videoTitles[0][position], Jzvd.SCREEN_NORMAL);
viewHolder.jzvdStd.positionInList = position;
Glide.with(ActivityListViewMultiHolder.this)
.load(VideoConstant.videoThumbs[0][position])
.into(viewHolder.jzvdStd.thumbImageView);
} else {
TextViewHolder textViewHolder;
if (convertView != null && convertView.getTag() != null && convertView.getTag() instanceof TextViewHolder) {
textViewHolder = (TextViewHolder) convertView.getTag();
} else {
textViewHolder = new TextViewHolder();
LayoutInflater mInflater = LayoutInflater.from(context);
convertView = mInflater.inflate(R.layout.item_textview, null);
textViewHolder.textView = convertView.findViewById(R.id.textview);
convertView.setTag(textViewHolder);
}
}
return convertView;
}
@Override
public int getItemViewType(int position) {
return viewtype[position];
}
@Override
public int getViewTypeCount() {
return 2;
}
class VideoHolder {
JzvdStd jzvdStd;
}
class TextViewHolder {
TextView textView;
}
}
}
| lipangit/JiaoZiVideoPlayer | app/src/main/java/cn/jzvd/demo/ActivityListViewMultiHolder.java | Java | mit | 5,869 |
package com.yngvark.communicate_through_named_pipes.input;
import org.slf4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import static org.slf4j.LoggerFactory.getLogger;
public class InputFileReader {
private final Logger logger = getLogger(getClass());
private final BufferedReader bufferedReader;
private boolean run = true;
private boolean streamClosed = false;
public InputFileReader(BufferedReader bufferedReader) {
this.bufferedReader = bufferedReader;
}
/**
* @throws IORuntimeException If an {@link java.io.IOException} occurs.
*/
public void consume(MessageListener messageListener) throws RuntimeException {
logger.debug("Consume: start.");
try {
tryToConsume(messageListener);
} catch (IOException e) {
throw new IORuntimeException(e);
}
logger.debug("");
logger.debug("Consume: done.");
}
private void tryToConsume(MessageListener messageListener) throws IOException {
String msg = null;
while (run) {
msg = bufferedReader.readLine();
if (msg == null)
break;
logger.trace("<<< From other side: " + msg);
messageListener.messageReceived(msg);
}
if (msg == null) {
logger.debug("Consume file stream was closed from other side.");
}
bufferedReader.close();
}
public synchronized void closeStream() {
logger.debug("Stopping consuming input file...");
if (streamClosed) {
logger.info("Already stopped.");
return;
}
run = false;
try {
logger.trace("Closing buffered reader.");
bufferedReader.close();
streamClosed = true;
} catch (IOException e) {
logger.error("Caught exception when closing stream: {}", e);
}
logger.debug("Stopping consuming input file... done");
}
}
| yngvark/gridwalls2 | source/lib/communicate-through-named-pipes/source/src/main/java/com/yngvark/communicate_through_named_pipes/input/InputFileReader.java | Java | mit | 2,016 |
package com.yunpian.sdk.model;
/**
* Created by bingone on 15/11/8.
*/
public class VoiceSend extends BaseInfo {
}
| yunpian/yunpian-java-sdk | src/main/java/com/yunpian/sdk/model/VoiceSend.java | Java | mit | 119 |
package com.ipvans.flickrgallery.ui.main;
import android.util.Log;
import com.ipvans.flickrgallery.data.SchedulerProvider;
import com.ipvans.flickrgallery.di.PerActivity;
import com.ipvans.flickrgallery.domain.FeedInteractor;
import com.ipvans.flickrgallery.domain.UpdateEvent;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.PublishSubject;
import static com.ipvans.flickrgallery.ui.main.MainViewState.*;
@PerActivity
public class MainPresenterImpl implements MainPresenter<MainViewState> {
private final FeedInteractor interactor;
private final SchedulerProvider schedulers;
private BehaviorSubject<MainViewState> stateSubject = BehaviorSubject.createDefault(empty());
private PublishSubject<UpdateEvent> searchSubject = PublishSubject.create();
private Disposable disposable = new CompositeDisposable();
@Inject
public MainPresenterImpl(FeedInteractor interactor, SchedulerProvider schedulers) {
this.interactor = interactor;
this.schedulers = schedulers;
}
@Override
public void onAttach() {
Observable.combineLatest(searchSubject
.debounce(150, TimeUnit.MILLISECONDS, schedulers.io())
.doOnNext(interactor::getFeed),
interactor.observe(),
(tags, feed) -> new MainViewState(feed.isLoading(),
feed.getError(), feed.getData(), tags.getTags()))
.withLatestFrom(stateSubject,
(newState, oldState) -> new MainViewState(
newState.isLoading(), newState.getError(),
newState.getData() != null ? newState.getData() : oldState.getData(),
newState.getTags()
))
.observeOn(schedulers.io())
.subscribeWith(stateSubject)
.onSubscribe(disposable);
}
@Override
public void onDetach() {
disposable.dispose();
}
@Override
public void restoreState(MainViewState data) {
stateSubject.onNext(data);
}
@Override
public Observable<MainViewState> observe() {
return stateSubject;
}
@Override
public MainViewState getLatestState() {
return stateSubject.getValue();
}
@Override
public void search(String tags, boolean force) {
searchSubject.onNext(new UpdateEvent(tags, force));
}
}
| VansPo/flickr-gallery | FlickrGallery/app/src/main/java/com/ipvans/flickrgallery/ui/main/MainPresenterImpl.java | Java | mit | 2,680 |
package aaron.org.anote.viewbinder;
import android.app.Activity;
import android.os.Bundle;
public class DynamicActivity extends Activity {
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
Layout.start(this);
}
}
| phil0522/anote | anote-mobile/ANote/app/src/main/java/aaron/org/anote/viewbinder/DynamicActivity.java | Java | mit | 279 |
/*
* Copyright (c) 2005 Dizan Vasquez.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.jenet;
import java.nio.ByteBuffer;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* Wraps information to be sent through JeNet.
* @author Dizan Vasquez
*/
public class Packet implements IBufferable {
/**
* Indicates that this packet is reliable
*/
public static final int FLAG_RELIABLE = 1;
/**
* Indicates that the packet should be processed no
* matter its order relative to other packets.
*/
public static final int FLAG_UNSEQUENCED = 2;
protected int referenceCount;
protected int flags;
protected ByteBuffer data;
protected int dataLength;
private Packet() {
super();
}
/**
* Creates a new Packet.
* The constructor allocates a new packet and allocates a
* buffer of <code>dataLength</code> bytes for it.
*
* @param dataLength
* The size in bytes of this packet.
* @param flags
* An byte inidicating the how to handle this packet.
*/
public Packet( int dataLength, int flags ) {
data = ByteBuffer.allocateDirect( dataLength );
this.dataLength = dataLength;
this.flags = flags;
}
/**
* Copies this packet's data into the given buffer.
* @param buffer
* Destination buffer
*/
public void toBuffer( ByteBuffer buffer ) {
data.flip();
for ( int i = 0; i < dataLength; i++ ) {
buffer.put( data.get() );
}
}
/**
* Copies part of this packet's data into the given buffer.
* @param buffer
* Destination buffer
* @param offset
* Initial position of the destination buffer
* @param length
* Total number of bytes to copy
*/
public void toBuffer( ByteBuffer buffer, int offset, int length ) {
int position = data.position();
int limit = data.limit();
data.flip();
data.position( offset );
for ( int i = 0; i < length; i++ ) {
buffer.put( data.get() );
}
data.position( position );
data.limit( limit );
}
/**
* Copies the given buffer into this packet's data.
* @ param buffer
* Buffer to copy from
*/
public void fromBuffer( ByteBuffer buffer ) {
data.clear();
for ( int i = 0; i < dataLength; i++ ) {
data.put( buffer.get() );
}
}
/**
* Copies part of the given buffer into this packet's data.
* @param buffer
* Buffer to copy from
* @param fragmentOffset
* Position of the first byte to copy
* @param length
* Total number of bytes to copy
*/
public void fromBuffer( ByteBuffer buffer, int fragmentOffset, int length ) {
data.position( fragmentOffset );
for ( int i = 0; i < length; i++ ) {
data.put( buffer.get() );
}
data.position( dataLength );
data.limit( dataLength );
}
/**
* Returs size of this packet.
* @return Size in bytes of this packet
*/
public int byteSize() {
return dataLength;
}
/**
* Returns the data contained in this packet
* @return Returns the data.
*/
public ByteBuffer getData() {
return data;
}
/**
* Returns the size in bytes of this packet's data
* @return Returns the dataLength.
*/
public int getDataLength() {
return dataLength;
}
/**
* Returns this packet's flags.
* @return Returns the flags.
*/
public int getFlags() {
return flags;
}
/**
* @return Returns the referenceCount.
*/
int getReferenceCount() {
return referenceCount;
}
/**
* Sets the flags for this packet.
* The parameter is an or of the flags <code>FLAG_RELIABLE</code> and <code>FLAG_UNSEQUENCED</code>
* a value of zero indicates an unreliable, sequenced (last one is kept) packet.
* @param flags
* The flags to set.
*/
public void setFlags( int flags ) {
this.flags = flags;
}
/**
* @param referenceCount
* The referenceCount to set.
*/
void setReferenceCount( int referenceCount ) {
this.referenceCount = referenceCount;
}
public String toString() {
return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE );
}
} | seeseekey/jenet | src/net/jenet/Packet.java | Java | mit | 6,482 |
package com.aspose.cloud.sdk.cells.model;
public enum ValidFormatsForDocumentEnum {
csv,
xlsx,
xlsm,
xltx,
xltm,
text,
html,
pdf,
ods,
xls,
spreadsheetml,
xlsb,
xps,
tiff,
jpeg,
png,
emf,
bmp,
gif
}
| asposeforcloud/Aspose_Cloud_SDK_For_Android | asposecloudsdk/src/main/java/com/aspose/cloud/sdk/cells/model/ValidFormatsForDocumentEnum.java | Java | mit | 236 |
package ch.hesso.master.caldynam;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Outline;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.Toast;
import ch.hesso.master.caldynam.ui.fragment.FoodAddFragment;
import ch.hesso.master.caldynam.ui.fragment.FoodCatalogFragment;
import ch.hesso.master.caldynam.ui.fragment.FoodViewFragment;
import ch.hesso.master.caldynam.ui.fragment.LoggingFragment;
import ch.hesso.master.caldynam.ui.fragment.NavigationDrawerFragment;
import ch.hesso.master.caldynam.ui.fragment.SummaryFragment;
import ch.hesso.master.caldynam.ui.fragment.WeightMeasurementFragment;
import me.drakeet.materialdialog.MaterialDialog;
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks,
SummaryFragment.OnFragmentInteractionListener,
WeightMeasurementFragment.OnFragmentInteractionListener,
LoggingFragment.OnFragmentInteractionListener,
FoodCatalogFragment.OnFragmentInteractionListener,
FoodAddFragment.OnFragmentInteractionListener,
FoodViewFragment.OnFragmentInteractionListener {
private Fragment fragment = null;
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #updateToolbar()}.
*/
private CharSequence mTitle;
private Toolbar mToolbar;
private View mFabButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Handle Toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// Handle different Drawer States :D
// mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
// Fab Button
mFabButton = findViewById(R.id.fab_button);
mFabButton.setOnClickListener(fabClickListener);
mFabButton.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
outline.setOval(0, 0, size, size);
}
});
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout)
);
updateToolbar();
mTitle = getTitle();
}
@Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
fragment = SummaryFragment.newInstance();
break;
case 1:
fragment = WeightMeasurementFragment.newInstance();
break;
case 2:
fragment = LoggingFragment.newInstance();
break;
case 3:
fragment = FoodCatalogFragment.newInstance();
break;
}
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
loadFragment(fragment, false);
}
View.OnClickListener fabClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "New data", Toast.LENGTH_SHORT).show();
}
};
public void onSectionAttached(int resourceId) {
mTitle = (resourceId != 0) ? getString(resourceId) : null;
}
public void updateToolbar() {
if (mTitle != null) {
mToolbar.setTitle(mTitle);
}
resizeToolbar(mNavigationDrawerFragment.isToolbarLarge() ? 1.0f : 0.0f);
mFabButton.setAlpha(mNavigationDrawerFragment.isFABVisible() ? 1.0f : 0.0f);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
if (fragment != null) {
fragment.onCreateOptionsMenu(menu, getMenuInflater());
}
//getMenuInflater().inflate(R.menu.main, menu);
updateToolbar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
/**
* Handle action bar item clicks here. The action bar will
* automatically handle clicks on the Home/Up button, so long
* as you specify a parent activity in AndroidManifest.xml.
*
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
fragment.onOptionsItemSelected(item);
if (id == R.id.action_about) {
showAboutDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.d(Constants.PROJECT_NAME, "Popping backstack");
fm.popBackStackImmediate();
this.fragment = getActiveFragment();
} else {
Log.d(Constants.PROJECT_NAME, "Nothing on backstack, calling super");
super.onBackPressed();
}
}
private void showAboutDialog() {
View contentView = LayoutInflater.from(this)
.inflate(R.layout.fragment_about_dialog, null);
final MaterialDialog aboutDialog = new MaterialDialog(this);
aboutDialog
.setContentView(contentView)
.setPositiveButton(getString(R.string.ok), new View.OnClickListener() {
@Override
public void onClick(View v) {
aboutDialog.dismiss();
}
});
aboutDialog.show();
}
public Fragment getActiveFragment() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String tag = getFragmentManager()
.getBackStackEntryAt(getFragmentManager().getBackStackEntryCount() - 1)
.getName();
return getFragmentManager().findFragmentByTag(tag);
}
public void loadFragment(Fragment fragment) {
loadFragment(fragment, true);
}
public void loadFragment(Fragment fragment, boolean addToBackStack) {
this.fragment = fragment;
String tag = fragment.getClass().getSimpleName();
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, this.fragment, tag);
if (addToBackStack) {
Log.d("Fragment", tag);
ft.addToBackStack(tag);
}
ft.commit();
// Replace current menu with the fragment menu
this.invalidateOptionsMenu();
}
public void resizeToolbar(float offset) {
float minSize = mToolbar.getMinimumHeight();
float maxSize = getResources().getDimension(R.dimen.toolbar_height_large);
ViewGroup.LayoutParams layout = mToolbar.getLayoutParams();
layout.height = (int) (minSize + (maxSize - minSize) * offset);
mToolbar.requestLayout();
}
public View getAddButton() {
return mFabButton;
}
/**
* an animation for resizing the view.
*/
private class ResizeAnimation extends Animation {
private View mView;
private float mToHeight;
private float mFromHeight;
private float mToWidth;
private float mFromWidth;
public ResizeAnimation(View v, float fromWidth, float fromHeight, float toWidth, float toHeight) {
mToHeight = toHeight;
mToWidth = toWidth;
mFromHeight = fromHeight;
mFromWidth = fromWidth;
mView = v;
setDuration(300);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float height = (mToHeight - mFromHeight) * interpolatedTime + mFromHeight;
float width = (mToWidth - mFromWidth) * interpolatedTime + mFromWidth;
ViewGroup.LayoutParams p = mView.getLayoutParams();
p.height = (int) height;
p.width = (int) width;
mView.requestLayout();
}
}
} | Chavjoh/CalDynam | app/src/main/java/ch/hesso/master/caldynam/MainActivity.java | Java | mit | 9,388 |
/**
* The MIT License
* Copyright (c) 2003 David G Jones
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package info.dgjones.abora.white.edgeregion;
import java.io.PrintWriter;
import info.dgjones.abora.white.rcvr.Rcvr;
import info.dgjones.abora.white.rcvr.Xmtr;
import info.dgjones.abora.white.spaces.basic.Position;
import info.dgjones.abora.white.xpp.basic.Heaper;
/**
* Clients of EdgeManager define concrete subclasses of this, which are then used by the
* EdgeManager code
*/
public abstract class TransitionEdge extends Heaper {
/*
udanax-top.st:63348:
Heaper subclass: #TransitionEdge
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Xanadu-EdgeRegion'!
*/
/*
udanax-top.st:63352:
TransitionEdge comment:
'Clients of EdgeManager define concrete subclasses of this, which are then used by the EdgeManager code'!
*/
/*
udanax-top.st:63354:
(TransitionEdge getOrMakeCxxClassDescription)
attributes: ((Set new) add: #DEFERRED; add: #COPY; yourself)!
*/
/////////////////////////////////////////////
// Constructors
protected TransitionEdge() {
super();
}
public TransitionEdge ceiling(TransitionEdge other) {
if (other.isGE(this)) {
return other;
} else {
return this;
}
/*
udanax-top.st:63359:TransitionEdge methodsFor: 'accessing'!
{TransitionEdge} ceiling: other {TransitionEdge}
(other isGE: self)
ifTrue: [^other]
ifFalse: [^self]!
*/
}
public TransitionEdge floor(TransitionEdge other) {
if (isGE(other)) {
return other;
} else {
return this;
}
/*
udanax-top.st:63365:TransitionEdge methodsFor: 'accessing'!
{TransitionEdge} floor: other {TransitionEdge}
(self isGE: other)
ifTrue: [^other]
ifFalse: [^self]!
*/
}
public int actualHashForEqual() {
return System.identityHashCode(this);
// return Heaper.takeOop();
/*
udanax-top.st:63373:TransitionEdge methodsFor: 'testing'!
{UInt32} actualHashForEqual
^Heaper takeOop!
*/
}
/**
* Whether the position is strictly less than this edge
*/
public abstract boolean follows(Position pos);
/*
udanax-top.st:63377:TransitionEdge methodsFor: 'testing'!
{BooleanVar} follows: pos {Position}
"Whether the position is strictly less than this edge"
self subclassResponsibility!
*/
public abstract boolean isEqual(Heaper other);
/*
udanax-top.st:63382:TransitionEdge methodsFor: 'testing'!
{BooleanVar} isEqual: other {Heaper}
self subclassResponsibility!
*/
/**
* Whether there is precisely one position between this edge and the next one
*/
public abstract boolean isFollowedBy(TransitionEdge next);
/*
udanax-top.st:63386:TransitionEdge methodsFor: 'testing'!
{BooleanVar} isFollowedBy: next {TransitionEdge}
"Whether there is precisely one position between this edge and the next one"
self subclassResponsibility!
*/
/**
* Defines a full ordering among all edges in a given CoordinateSpace
*/
public abstract boolean isGE(TransitionEdge other);
/*
udanax-top.st:63391:TransitionEdge methodsFor: 'testing'!
{BooleanVar} isGE: other {TransitionEdge}
"Defines a full ordering among all edges in a given CoordinateSpace"
self subclassResponsibility!
*/
/**
* Whether this edge touches the same position the other does
*/
public abstract boolean touches(TransitionEdge other);
/*
udanax-top.st:63396:TransitionEdge methodsFor: 'testing'!
{BooleanVar} touches: other {TransitionEdge}
"Whether this edge touches the same position the other does"
self subclassResponsibility!
*/
/**
* Print a description of this transition
*/
public abstract void printTransitionOn(PrintWriter oo, boolean entering, boolean touchesPrevious);
/*
udanax-top.st:63403:TransitionEdge methodsFor: 'printing'!
{void} printTransitionOn: oo {ostream reference}
with: entering {BooleanVar}
with: touchesPrevious {BooleanVar}
"Print a description of this transition"
self subclassResponsibility!
*/
public TransitionEdge(Rcvr receiver) {
super(receiver);
/*
udanax-top.st:63412:TransitionEdge methodsFor: 'generated:'!
create.Rcvr: receiver {Rcvr}
super create.Rcvr: receiver.!
*/
}
public void sendSelfTo(Xmtr xmtr) {
super.sendSelfTo(xmtr);
/*
udanax-top.st:63415:TransitionEdge methodsFor: 'generated:'!
{void} sendSelfTo: xmtr {Xmtr}
super sendSelfTo: xmtr.!
*/
}
}
| jonesd/abora-white | src/main/java/info/dgjones/abora/white/edgeregion/TransitionEdge.java | Java | mit | 5,464 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.resources.implementation;
import com.microsoft.azure.management.resources.ResourceGroupProperties;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Resource group information.
*/
public class ResourceGroupInner {
/**
* The ID of the resource group.
*/
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String id;
/**
* The name of the resource group.
*/
private String name;
/**
* The properties property.
*/
private ResourceGroupProperties properties;
/**
* The location of the resource group. It cannot be changed after the
* resource group has been created. It muct be one of the supported Azure
* locations.
*/
@JsonProperty(required = true)
private String location;
/**
* The ID of the resource that manages this resource group.
*/
private String managedBy;
/**
* The tags attached to the resource group.
*/
private Map<String, String> tags;
/**
* Get the id value.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Get the name value.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name value.
*
* @param name the name value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withName(String name) {
this.name = name;
return this;
}
/**
* Get the properties value.
*
* @return the properties value
*/
public ResourceGroupProperties properties() {
return this.properties;
}
/**
* Set the properties value.
*
* @param properties the properties value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withProperties(ResourceGroupProperties properties) {
this.properties = properties;
return this;
}
/**
* Get the location value.
*
* @return the location value
*/
public String location() {
return this.location;
}
/**
* Set the location value.
*
* @param location the location value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withLocation(String location) {
this.location = location;
return this;
}
/**
* Get the managedBy value.
*
* @return the managedBy value
*/
public String managedBy() {
return this.managedBy;
}
/**
* Set the managedBy value.
*
* @param managedBy the managedBy value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withManagedBy(String managedBy) {
this.managedBy = managedBy;
return this;
}
/**
* Get the tags value.
*
* @return the tags value
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set the tags value.
*
* @param tags the tags value to set
* @return the ResourceGroupInner object itself.
*/
public ResourceGroupInner withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
}
| pomortaz/azure-sdk-for-java | azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/ResourceGroupInner.java | Java | mit | 3,619 |
package uk.gov.dvsa.ui.pages.vehicleinformation;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import uk.gov.dvsa.domain.model.vehicle.Make;
import uk.gov.dvsa.domain.navigation.PageNavigator;
import uk.gov.dvsa.framework.config.webdriver.MotAppDriver;
import uk.gov.dvsa.helper.FormDataHelper;
import uk.gov.dvsa.helper.PageInteractionHelper;
import uk.gov.dvsa.ui.pages.Page;
public class VehicleMakePage extends Page {
private static final String PAGE_TITLE = "What is the vehicle's make?";
public static final String PATH = "/create-vehicle/make";
@FindBy(id = "vehicleMake") private WebElement vehicleMakeDropdown;
@FindBy(className = "button") private WebElement continueButton;
public VehicleMakePage(MotAppDriver driver) {
super(driver);
selfVerify();
}
@Override
protected boolean selfVerify() {
return PageInteractionHelper.verifyTitle(this.getTitle(), PAGE_TITLE);
}
public VehicleMakePage selectMake(Make make){
FormDataHelper.selectFromDropDownByValue(vehicleMakeDropdown, make.getId().toString());
vehicleMakeDropdown.sendKeys(Keys.TAB);
return this;
}
public VehicleModelPage continueToVehicleModelPage() {
continueButton.click();
return new VehicleModelPage(driver);
}
public VehicleModelPage updateVehicleMake(Make make) {
FormDataHelper.selectFromDropDownByValue(vehicleMakeDropdown, make.getId().toString());
vehicleMakeDropdown.sendKeys(Keys.TAB);
return continueToVehicleModelPage();
}
}
| dvsa/mot | mot-selenium/src/main/java/uk/gov/dvsa/ui/pages/vehicleinformation/VehicleMakePage.java | Java | mit | 1,635 |
package io.prajesh.config;
import io.prajesh.domain.HelloWorld;
import io.prajesh.service.HelloWorldService;
import io.prajesh.service.HelloWorldServiceImpl;
import io.prajesh.service.factory.HelloWorldFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* @author Prajesh Ananthan
* Created on 16/7/2017.
*/
@Configuration
public class HelloConfig {
@Bean
public HelloWorldFactory helloWorldFactory() {
return new HelloWorldFactory();
}
@Bean
public HelloWorldService helloWorldService() {
return new HelloWorldServiceImpl();
}
@Bean
@Profile("English")
public HelloWorld helloWorldEn(HelloWorldFactory factory) {
return factory.getHelloWorldFactory("en");
}
@Bean
@Profile("Malay")
public HelloWorld helloWorldMy(HelloWorldFactory factory) {
return factory.getHelloWorldFactory("my");
}
}
| prajesh-ananthan/spring-playfield | spring-core/src/main/java/io/prajesh/config/HelloConfig.java | Java | mit | 980 |
package sql.fredy.sqltools;
/**
XLSExport exports the result of a query into a XLS-file. To do this it is
using HSSF from the Apache POI Project: http://jakarta.apache.org/poi
Version 1.0 Date 7. aug. 2003 Author Fredy Fischer
XLSExport is part of the Admin-Suite
Once instantiated there are the following steps to go to get a XLS-file out
of a query
XLSExport xe = new XLSExport(java.sql.Connection con)
xe.setQuery(java.lang.String query) please set herewith the the query to get
its results as XLS-file
int xe.createXLS(java.lang.String fileName) this will then create the
XLS-File. If this file already exists, it will be overwritten!
it returns the number of rows written to the File
2015-11-16 Creating an additional Worksheet containing the SQL-Query
Admin is a Tool around SQL to do basic jobs for DB-Administrations, like: -
create/ drop tables - create indices - perform sql-statements - simple form -
a guided query and a other usefull things in DB-arena
Copyright (c) 2017 Fredy Fischer, [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import sql.fredy.share.t_connect;
import java.io.InputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.*;
import java.util.logging.*;
import java.util.Date;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.model.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import java.util.ArrayList;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
public class XLSExport {
private Logger logger;
Connection con = null;
/**
* Get the value of con.
*
* @return value of con.
*/
public Connection getCon() {
return con;
}
/**
* Set the value of con.
*
* @param v Value to assign to con.
*/
public void setCon(Connection v) {
this.con = v;
}
String query=null;
/**
* Get the value of query.
*
* @return value of query.
*/
public String getQuery() {
return query;
}
/**
* Set the value of query.
*
* @param v Value to assign to query.
*/
public void setQuery(String v) {
this.query = v;
}
java.sql.SQLException exception;
/**
* Get the value of exception.
*
* @return value of exception.
*/
public java.sql.SQLException getException() {
return exception;
}
/**
* Set the value of exception.
*
* @param v Value to assign to exception.
*/
public void setException(java.sql.SQLException v) {
this.exception = v;
}
private PreparedStatement pstmt = null;
/*
is this file xlsx or xls?
we detect this out of the filename extension
*/
private boolean xlsx = false;
private void checkXlsx(String fileName) {
String[] extension = fileName.split("\\.");
int l = extension.length - 1;
String fileType = extension[l].toLowerCase();
if ("xlsx".equals(fileType)) {
setXlsx(true);
}
}
/*
we need to check, if the extension of the Filename is either xls or xlsx if not,
we set to xlsx as default
*/
private String fixFileName(String f) {
String prefix = "", postfix = "";
String fixed = f;
int i = f.lastIndexOf(".");
// no postfix at all set
if (i < 0) {
fixed = f + ".xlsx";
} else {
prefix = f.substring(0, i);
postfix = f.substring(i + 1);
logger.log(Level.FINE, "Prefix: " + prefix + " Postfix: " + postfix);
if ((postfix.equalsIgnoreCase("xlsx")) || (postfix.equalsIgnoreCase("xls"))) {
// nothing to do
} else {
postfix = "xlsx";
}
fixed = prefix + "." + postfix;
}
logger.log(Level.INFO, "Filename: " + fixed);
return fixed;
}
/**
* Create the XLS-File named fileName
*
* @param fileName is the Name (incl. Path) of the XLS-file to create
*
*
*/
public int createXLS(String fileName) {
// I need to have a query to process
if ((getQuery() == null) && (getPstmt() == null)) {
logger.log(Level.WARNING, "Need to have a query to process");
return 0;
}
// I also need to have a file to write into
if (fileName == null) {
logger.log(Level.WARNING, "Need to know where to write into");
return 0;
}
fileName = fixFileName(fileName);
checkXlsx(fileName);
// I need to have a connection to the RDBMS
if (getCon() == null) {
logger.log(Level.WARNING, "Need to have a connection to process");
return 0;
}
//Statement stmt = null;
ResultSet resultSet = null;
ResultSetMetaData rsmd = null;
try {
// first we have to create the Statement
if (getPstmt() == null) {
pstmt = getCon().prepareStatement(getQuery());
}
//stmt = getCon().createStatement();
} catch (SQLException sqle1) {
setException(sqle1);
logger.log(Level.WARNING, "Can not create Statement. Message: "
+ sqle1.getMessage().toString());
return 0;
}
logger.log(Level.FINE, "FileName: " + fileName);
logger.log(Level.FINE, "Query : " + getQuery());
logger.log(Level.FINE, "Starting export...");
// create an empty sheet
Workbook wb;
Sheet sheet;
Sheet sqlsheet;
CreationHelper createHelper = null;
//XSSFSheet xsheet;
//HSSFSheet sheet;
if (isXlsx()) {
wb = new SXSSFWorkbook();
createHelper = wb.getCreationHelper();
} else {
wb = new HSSFWorkbook();
createHelper = wb.getCreationHelper();
}
sheet = wb.createSheet("Data Export");
// create a second sheet just containing the SQL Statement
sqlsheet = wb.createSheet("SQL Statement");
Row sqlrow = sqlsheet.createRow(0);
Cell sqltext = sqlrow.createCell(0);
try {
if ( getQuery() != null ) {
sqltext.setCellValue(getQuery());
} else {
sqltext.setCellValue(pstmt.toString());
}
} catch (Exception lex) {
}
CellStyle style = wb.createCellStyle();
style.setWrapText(true);
sqltext.setCellStyle(style);
Row r = null;
int row = 0; // row number
int col = 0; // column number
int columnCount = 0;
try {
//resultSet = stmt.executeQuery(getQuery());
resultSet = pstmt.executeQuery();
logger.log(Level.FINE, "query executed");
} catch (SQLException sqle2) {
setException(sqle2);
logger.log(Level.WARNING, "Can not execute query. Message: "
+ sqle2.getMessage().toString());
return 0;
}
// create Header in XLS-file
ArrayList<String> head = new ArrayList();
try {
rsmd = resultSet.getMetaData();
logger.log(Level.FINE, "Got MetaData of the resultset");
columnCount = rsmd.getColumnCount();
logger.log(Level.FINE, Integer.toString(columnCount)
+ " Columns in this resultset");
r = sheet.createRow(row); // titlerow
if ((!isXlsx()) && (columnCount > 255)) {
columnCount = 255;
}
for (int i = 0; i < columnCount; i++) {
// we create the cell
Cell cell = r.createCell(col);
// set the value of the cell
cell.setCellValue(rsmd.getColumnName(i + 1));
head.add(rsmd.getColumnName(i + 1));
// then we align center
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// now we make it bold
//HSSFFont f = wb.createFont();
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(headerFont);
//cellStyle.setFont(f);
// adapt this font to the cell
cell.setCellStyle(cellStyle);
col++;
}
} catch (SQLException sqle3) {
setException(sqle3);
logger.log(Level.WARNING, "Can not create XLS-Header. Message: "
+ sqle3.getMessage().toString());
return 0;
}
// looping the resultSet
int wbCounter = 0;
try {
while (resultSet.next()) {
// this is the next row
col = 0; // put column counter back to 0 to start at the next row
row++; // next row
// create a new sheet if more then 60'000 Rows and xls file
if ((!isXlsx()) && (row % 65530 == 0)) {
wbCounter++;
row = 0;
sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter));
logger.log(Level.INFO, "created a further page because of a huge amount of data");
// create the head
r = sheet.createRow(row); // titlerow
for (int i = 0; i < head.size(); i++) {
// we create the cell
Cell cell = r.createCell(col);
// set the value of the cell
cell.setCellValue((String) head.get(i));
// then we align center
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// now we make it bold
//HSSFFont f = wb.createFont();
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(headerFont);
//cellStyle.setFont(f);
// adapt this font to the cell
cell.setCellStyle(cellStyle);
col++;
}
row++;
}
try {
r = sheet.createRow(row);
} catch (Exception e) {
logger.log(Level.WARNING, "Error while creating row number " + row + " " + e.getMessage());
wbCounter++;
row = 0;
sheet = wb.createSheet("Data Export " + Integer.toString(wbCounter));
logger.log(Level.WARNING, "created a further page in the hope it helps...");
// create the head
r = sheet.createRow(row); // titlerow
for (int i = 0; i < head.size(); i++) {
// we create the cell
Cell cell = r.createCell(col);
// set the value of the cell
cell.setCellValue((String) head.get(i));
// then we align center
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// now we make it bold
//HSSFFont f = wb.createFont();
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(headerFont);
//cellStyle.setFont(f);
// adapt this font to the cell
cell.setCellStyle(cellStyle);
col++;
}
row++;
}
col = 0; // put column counter back to 0 to start at the next row
String previousMessage = "";
for (int i = 0; i < columnCount; i++) {
try {
// depending on the type, create the cell
switch (rsmd.getColumnType(i + 1)) {
case java.sql.Types.INTEGER:
r.createCell(col).setCellValue(resultSet.getInt(i + 1));
break;
case java.sql.Types.FLOAT:
r.createCell(col).setCellValue(resultSet.getFloat(i + 1));
break;
case java.sql.Types.DOUBLE:
r.createCell(col).setCellValue(resultSet.getDouble(i + 1));
break;
case java.sql.Types.DECIMAL:
r.createCell(col).setCellValue(resultSet.getFloat(i + 1));
break;
case java.sql.Types.NUMERIC:
r.createCell(col).setCellValue(resultSet.getFloat(i + 1));
break;
case java.sql.Types.BIGINT:
r.createCell(col).setCellValue(resultSet.getInt(i + 1));
break;
case java.sql.Types.TINYINT:
r.createCell(col).setCellValue(resultSet.getInt(i + 1));
break;
case java.sql.Types.SMALLINT:
r.createCell(col).setCellValue(resultSet.getInt(i + 1));
break;
case java.sql.Types.DATE:
// first we get the date
java.sql.Date dat = resultSet.getDate(i + 1);
java.util.Date date = new java.util.Date(dat.getTime());
r.createCell(col).setCellValue(date);
break;
case java.sql.Types.TIMESTAMP:
// first we get the date
java.sql.Timestamp ts = resultSet.getTimestamp(i + 1);
Cell c = r.createCell(col);
try {
c.setCellValue(ts);
// r.createCell(col).setCellValue(ts);
// Date Format
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss"));
c.setCellStyle(cellStyle);
} catch (Exception e) {
c.setCellValue(" ");
}
break;
case java.sql.Types.TIME:
// first we get the date
java.sql.Time time = resultSet.getTime(i + 1);
r.createCell(col).setCellValue(time);
break;
case java.sql.Types.BIT:
boolean b1 = resultSet.getBoolean(i + 1);
r.createCell(col).setCellValue(b1);
break;
case java.sql.Types.BOOLEAN:
boolean b2 = resultSet.getBoolean(i + 1);
r.createCell(col).setCellValue(b2);
break;
case java.sql.Types.CHAR:
r.createCell(col).setCellValue(resultSet.getString(i + 1));
break;
case java.sql.Types.NVARCHAR:
r.createCell(col).setCellValue(resultSet.getString(i + 1));
break;
case java.sql.Types.VARCHAR:
try {
r.createCell(col).setCellValue(resultSet.getString(i + 1));
} catch (Exception e) {
r.createCell(col).setCellValue(" ");
logger.log(Level.WARNING, "Exception while writing column {0} row {3} type: {1} Message: {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row});
}
break;
default:
r.createCell(col).setCellValue(resultSet.getString(i + 1));
break;
}
} catch (Exception e) {
//e.printStackTrace();
if (resultSet.wasNull()) {
r.createCell(col).setCellValue(" ");
} else {
logger.log(Level.WARNING, "Unhandled type at column {0}, row {3} type: {1}. Filling up with blank {2}", new Object[]{col, rsmd.getColumnType(i + 1), e.getMessage(), row});
r.createCell(col).setCellValue(" ");
}
}
col++;
}
}
//pstmt.close();
} catch (SQLException sqle3) {
setException(sqle3);
logger.log(Level.WARNING, "Exception while writing data into sheet. Message: "
+ sqle3.getMessage().toString());
}
try {
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
fileOut.close();
logger.log(Level.INFO, "File created");
logger.log(Level.INFO, "Wrote: {0} lines into XLS-File", Integer.toString(row));
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while writing xls-File: " + e.getMessage().toString());
}
return row;
}
public XLSExport(Connection con) {
logger = Logger.getLogger("sql.fredy.sqltools");
setCon(con);
}
public XLSExport() {
logger = Logger.getLogger("sql.fredy.sqltools");
}
public static void main(String args[]) {
String host = "localhost";
String user = System.getProperty("user.name");
String schema = "%";
String database = null;
String password = null;
String query = null;
String file = null;
System.out.println("XLSExport\n"
+ "----------\n"
+ "Syntax: java sql.fredy.sqltools.XLSExport\n"
+ " Parameters: -h Host (default: localhost)\n"
+ " -u User (default: "
+ System.getProperty("user.name") + ")\n"
+ " -p Password\n"
+ " -q Query\n"
+ " -Q Filename of the file containing the Query\n"
+ " -d database\n"
+ " -f File to write into (.xls or xlsx)\n");
int i = 0;
while (i < args.length) {
if (args[i].equals("-h")) {
i++;
host = args[i];
}
if (args[i].equals("-u")) {
i++;
user = args[i];
}
if (args[i].equals("-p")) {
i++;
password = args[i];
}
if (args[i].equals("-d")) {
i++;
database = args[i];
}
if (args[i].equals("-q")) {
i++;
query = args[i];
}
if (args[i].equals("-Q")) {
i++;
sql.fredy.io.ReadFile rf = new sql.fredy.io.ReadFile(args[i]);
query = rf.getText();
}
if (args[i].equals("-f")) {
i++;
file = args[i];
}
i++;
};
t_connect tc = new t_connect(host, user, password, database);
XLSExport xe = new XLSExport(tc.con);
xe.setQuery(query);
xe.createXLS(file);
tc.close();
}
/**
* @return the xlsx
*/
public boolean isXlsx() {
return xlsx;
}
/**
* @param xlsx the xlsx to set
*/
public void setXlsx(boolean xlsx) {
this.xlsx = xlsx;
}
/**
* @return the pstmt
*/
public PreparedStatement getPstmt() {
return pstmt;
}
/**
* @param pstmt the pstmt to set
*/
public void setPstmt(PreparedStatement pstmt) {
this.pstmt = pstmt;
}
}
| hulmen/SQLAdmin | src/fredy/sqltools/XLSExport.java | Java | mit | 23,048 |
/*
* Copyright (c) 2015. Vin @ vinexs.com (MIT License)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.vinexs.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.LinearLayout;
@SuppressWarnings("unused")
public class ScalableLinearLayout extends LinearLayout {
private ScaleGestureDetector scaleDetector;
private float scaleFactor = 1.f;
private float maxScaleFactor = 1.5f;
private float minScaleFactor = 0.5f;
public ScalableLinearLayout(Context context) {
super(context);
scaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
public ScalableLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
scaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
// Let the ScaleGestureDetector inspect all events.
scaleDetector.onTouchEvent(event);
return true;
}
@Override
public void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.scale(scaleFactor, scaleFactor);
super.dispatchDraw(canvas);
canvas.restore();
}
public ScalableLinearLayout setMaxScale(float scale) {
maxScaleFactor = scale;
return this;
}
public ScalableLinearLayout setMinScale(float scale) {
minScaleFactor = scale;
return this;
}
public ScaleGestureDetector getScaleGestureDetector() {
return scaleDetector;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(minScaleFactor, Math.min(scaleFactor, maxScaleFactor));
invalidate();
return true;
}
}
}
| vinexs/extend-enhance-base | eeb-core/src/main/java/com/vinexs/view/ScalableLinearLayout.java | Java | mit | 3,281 |
/*
* Copyright (c) 2016-2017 Mozilla Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package nu.validator.xml;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
public final class UseCountingXMLReaderWrapper
implements XMLReader, ContentHandler {
private final XMLReader wrappedReader;
private ContentHandler contentHandler;
private ErrorHandler errorHandler;
private HttpServletRequest request;
private StringBuilder documentContent;
private boolean inBody;
private boolean loggedLinkWithCharset;
private boolean loggedScriptWithCharset;
private boolean loggedStyleInBody;
private boolean loggedRelAlternate;
private boolean loggedRelAuthor;
private boolean loggedRelBookmark;
private boolean loggedRelCanonical;
private boolean loggedRelDnsPrefetch;
private boolean loggedRelExternal;
private boolean loggedRelHelp;
private boolean loggedRelIcon;
private boolean loggedRelLicense;
private boolean loggedRelNext;
private boolean loggedRelNofollow;
private boolean loggedRelNoopener;
private boolean loggedRelNoreferrer;
private boolean loggedRelPingback;
private boolean loggedRelPreconnect;
private boolean loggedRelPrefetch;
private boolean loggedRelPreload;
private boolean loggedRelPrerender;
private boolean loggedRelPrev;
private boolean loggedRelSearch;
private boolean loggedRelServiceworker;
private boolean loggedRelStylesheet;
private boolean loggedRelTag;
public UseCountingXMLReaderWrapper(XMLReader wrappedReader,
HttpServletRequest request) {
this.wrappedReader = wrappedReader;
this.contentHandler = wrappedReader.getContentHandler();
this.request = request;
this.inBody = false;
this.loggedLinkWithCharset = false;
this.loggedScriptWithCharset = false;
this.loggedStyleInBody = false;
this.loggedRelAlternate = false;
this.loggedRelAuthor = false;
this.loggedRelBookmark = false;
this.loggedRelCanonical = false;
this.loggedRelAlternate = false;
this.loggedRelAuthor = false;
this.loggedRelBookmark = false;
this.loggedRelCanonical = false;
this.loggedRelDnsPrefetch = false;
this.loggedRelExternal = false;
this.loggedRelHelp = false;
this.loggedRelIcon = false;
this.loggedRelLicense = false;
this.loggedRelNext = false;
this.loggedRelNofollow = false;
this.loggedRelNoopener = false;
this.loggedRelNoreferrer = false;
this.loggedRelPingback = false;
this.loggedRelPreconnect = false;
this.loggedRelPrefetch = false;
this.loggedRelPreload = false;
this.loggedRelPrerender = false;
this.loggedRelPrev = false;
this.loggedRelSearch = false;
this.loggedRelServiceworker = false;
this.loggedRelStylesheet = false;
this.loggedRelTag = false;
this.documentContent = new StringBuilder();
wrappedReader.setContentHandler(this);
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#characters(char[], int, int)
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.characters(ch, start, length);
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#endElement(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.endElement(uri, localName, qName);
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#startDocument()
*/
@Override
public void startDocument() throws SAXException {
if (contentHandler == null) {
return;
}
documentContent.setLength(0);
contentHandler.startDocument();
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#startElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if (contentHandler == null) {
return;
}
if ("link".equals(localName)) {
boolean hasAppleTouchIcon = false;
boolean hasSizes = false;
for (int i = 0; i < atts.getLength(); i++) {
if ("rel".equals(atts.getLocalName(i))) {
if (atts.getValue(i).contains("apple-touch-icon")) {
hasAppleTouchIcon = true;
}
} else if ("sizes".equals(atts.getLocalName(i))) {
hasSizes = true;
} else if ("charset".equals(atts.getLocalName(i))
&& !loggedLinkWithCharset) {
loggedLinkWithCharset = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/link-with-charset-found",
true);
}
}
}
if (request != null && hasAppleTouchIcon && hasSizes) {
request.setAttribute(
"http://validator.nu/properties/apple-touch-icon-with-sizes-found",
true);
}
} else if ("script".equals(localName) && !loggedScriptWithCharset) {
for (int i = 0; i < atts.getLength(); i++) {
if ("charset".equals(atts.getLocalName(i))) {
loggedScriptWithCharset = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/script-with-charset-found",
true);
}
}
}
} else if (inBody && "style".equals(localName) && !loggedStyleInBody) {
loggedStyleInBody = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/style-in-body-found",
true);
}
}
if (atts.getIndex("", "rel") > -1
&& ("link".equals(localName) || "a".equals(localName))) {
List<String> relValues = Arrays.asList(
atts.getValue("", "rel").trim().toLowerCase() //
.split("\\s+"));
if (relValues.contains("alternate") && !loggedRelAlternate) {
loggedRelAlternate = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-alternate-found",
true);
}
}
if (relValues.contains("author") && !loggedRelAuthor) {
loggedRelAuthor = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-author-found",
true);
}
}
if (relValues.contains("bookmark") && !loggedRelBookmark) {
loggedRelBookmark = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-bookmark-found",
true);
}
}
if (relValues.contains("canonical") && !loggedRelCanonical) {
loggedRelCanonical = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-canonical-found",
true);
}
}
if (relValues.contains("dns-prefetch") && !loggedRelDnsPrefetch) {
loggedRelDnsPrefetch = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-dns-prefetch-found",
true);
}
}
if (relValues.contains("external") && !loggedRelExternal) {
loggedRelExternal = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-external-found",
true);
}
}
if (relValues.contains("help") && !loggedRelHelp) {
loggedRelHelp = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-help-found",
true);
}
}
if (relValues.contains("icon") && !loggedRelIcon) {
loggedRelIcon = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-icon-found",
true);
}
}
if (relValues.contains("license") && !loggedRelLicense) {
loggedRelLicense = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-license-found",
true);
}
}
if (relValues.contains("next") && !loggedRelNext) {
loggedRelNext = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-next-found",
true);
}
}
if (relValues.contains("nofollow") && !loggedRelNofollow) {
loggedRelNofollow = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-nofollow-found",
true);
}
}
if (relValues.contains("noopener") && !loggedRelNoopener) {
loggedRelNoopener = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-noopener-found",
true);
}
}
if (relValues.contains("noreferrer") && !loggedRelNoreferrer) {
loggedRelNoreferrer = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-noreferrer-found",
true);
}
}
if (relValues.contains("pingback") && !loggedRelPingback) {
loggedRelPingback = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-pingback-found",
true);
}
}
if (relValues.contains("preconnect") && !loggedRelPreconnect) {
loggedRelPreconnect = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-preconnect-found",
true);
}
}
if (relValues.contains("prefetch") && !loggedRelPrefetch) {
loggedRelPrefetch = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-prefetch-found",
true);
}
}
if (relValues.contains("preload") && !loggedRelPreload) {
loggedRelPreload = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-preload-found",
true);
}
}
if (relValues.contains("prerender") && !loggedRelPrerender) {
loggedRelPrerender = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-prerender-found",
true);
}
}
if (relValues.contains("prev") && !loggedRelPrev) {
loggedRelPrev = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-prev-found",
true);
}
}
if (relValues.contains("search") && !loggedRelSearch) {
loggedRelSearch = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-search-found",
true);
}
}
if (relValues.contains("serviceworker")
&& !loggedRelServiceworker) {
loggedRelServiceworker = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-serviceworker-found",
true);
}
}
if (relValues.contains("stylesheet") && !loggedRelStylesheet) {
loggedRelStylesheet = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-stylesheet-found",
true);
}
}
if (relValues.contains("tag") && !loggedRelTag) {
loggedRelTag = true;
if (request != null) {
request.setAttribute(
"http://validator.nu/properties/rel-tag-found",
true);
}
}
}
contentHandler.startElement(uri, localName, qName, atts);
}
/**
* @see org.xml.sax.helpers.XMLFilterImpl#setDocumentLocator(org.xml.sax.Locator)
*/
@Override
public void setDocumentLocator(Locator locator) {
if (contentHandler == null) {
return;
}
contentHandler.setDocumentLocator(locator);
}
@Override
public ContentHandler getContentHandler() {
return contentHandler;
}
/**
* @throws SAXException
* @see org.xml.sax.ContentHandler#endDocument()
*/
@Override
public void endDocument() throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.endDocument();
}
/**
* @param prefix
* @throws SAXException
* @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String)
*/
@Override
public void endPrefixMapping(String prefix) throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.endPrefixMapping(prefix);
}
/**
* @param ch
* @param start
* @param length
* @throws SAXException
* @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int)
*/
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.ignorableWhitespace(ch, start, length);
}
/**
* @param target
* @param data
* @throws SAXException
* @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String,
* java.lang.String)
*/
@Override
public void processingInstruction(String target, String data)
throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.processingInstruction(target, data);
}
/**
* @param name
* @throws SAXException
* @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String)
*/
@Override
public void skippedEntity(String name) throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.skippedEntity(name);
}
/**
* @param prefix
* @param uri
* @throws SAXException
* @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String,
* java.lang.String)
*/
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
if (contentHandler == null) {
return;
}
contentHandler.startPrefixMapping(prefix, uri);
}
/**
* @return
* @see org.xml.sax.XMLReader#getDTDHandler()
*/
@Override
public DTDHandler getDTDHandler() {
return wrappedReader.getDTDHandler();
}
/**
* @return
* @see org.xml.sax.XMLReader#getEntityResolver()
*/
@Override
public EntityResolver getEntityResolver() {
return wrappedReader.getEntityResolver();
}
/**
* @return
* @see org.xml.sax.XMLReader#getErrorHandler()
*/
@Override
public ErrorHandler getErrorHandler() {
return errorHandler;
}
/**
* @param name
* @return
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @see org.xml.sax.XMLReader#getFeature(java.lang.String)
*/
@Override
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
return wrappedReader.getFeature(name);
}
/**
* @param name
* @return
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @see org.xml.sax.XMLReader#getProperty(java.lang.String)
*/
@Override
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
return wrappedReader.getProperty(name);
}
/**
* @param input
* @throws IOException
* @throws SAXException
* @see org.xml.sax.XMLReader#parse(org.xml.sax.InputSource)
*/
@Override
public void parse(InputSource input) throws IOException, SAXException {
wrappedReader.parse(input);
}
/**
* @param systemId
* @throws IOException
* @throws SAXException
* @see org.xml.sax.XMLReader#parse(java.lang.String)
*/
@Override
public void parse(String systemId) throws IOException, SAXException {
wrappedReader.parse(systemId);
}
/**
* @param handler
* @see org.xml.sax.XMLReader#setContentHandler(org.xml.sax.ContentHandler)
*/
@Override
public void setContentHandler(ContentHandler handler) {
contentHandler = handler;
}
/**
* @param handler
* @see org.xml.sax.XMLReader#setDTDHandler(org.xml.sax.DTDHandler)
*/
@Override
public void setDTDHandler(DTDHandler handler) {
wrappedReader.setDTDHandler(handler);
}
/**
* @param resolver
* @see org.xml.sax.XMLReader#setEntityResolver(org.xml.sax.EntityResolver)
*/
@Override
public void setEntityResolver(EntityResolver resolver) {
wrappedReader.setEntityResolver(resolver);
}
/**
* @param handler
* @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler)
*/
@Override
public void setErrorHandler(ErrorHandler handler) {
wrappedReader.setErrorHandler(handler);
}
/**
* @param name
* @param value
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @see org.xml.sax.XMLReader#setFeature(java.lang.String, boolean)
*/
@Override
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException {
wrappedReader.setFeature(name, value);
}
/**
* @param name
* @param value
* @throws SAXNotRecognizedException
* @throws SAXNotSupportedException
* @see org.xml.sax.XMLReader#setProperty(java.lang.String,
* java.lang.Object)
*/
@Override
public void setProperty(String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
wrappedReader.setProperty(name, value);
}
}
| tripu/validator | src/nu/validator/xml/UseCountingXMLReaderWrapper.java | Java | mit | 22,613 |
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.data.types;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.util.annotation.CatalogedBy;
/**
* Represents a type of instrument.
*/
@CatalogedBy(InstrumentTypes.class)
public interface InstrumentType extends CatalogType {
}
| frogocomics/SpongeAPI | src/main/java/org/spongepowered/api/data/types/InstrumentType.java | Java | mit | 1,532 |
package components.diagram.edit.commands;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest;
import components.Component;
import components.ComponentsFactory;
import components.Connection;
import components.Port;
import components.diagram.edit.policies.ComponentModelBaseItemSemanticEditPolicy;
/**
* @generated
*/
public class ConnectionCreateCommand extends EditElementCommand {
/**
* @generated
*/
private final EObject source;
/**
* @generated
*/
private final EObject target;
/**
* @generated
*/
private final Component container;
/**
* @generated
*/
public ConnectionCreateCommand(CreateRelationshipRequest request, EObject source, EObject target) {
super(request.getLabel(), null, request);
this.source = source;
this.target = target;
container = deduceContainer(source, target);
}
/**
* @generated
*/
public boolean canExecute() {
if (source == null && target == null) {
return false;
}
if (source != null && false == source instanceof Port) {
return false;
}
if (target != null && false == target instanceof Port) {
return false;
}
if (getSource() == null) {
return true; // link creation is in progress; source is not defined yet
}
// target may be null here but it's possible to check constraint
if (getContainer() == null) {
return false;
}
return ComponentModelBaseItemSemanticEditPolicy.getLinkConstraints().canCreateConnection_4001(getContainer(),
getSource(), getTarget());
}
/**
* @generated
*/
protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
if (!canExecute()) {
throw new ExecutionException("Invalid arguments in create link command"); //$NON-NLS-1$
}
Connection newElement = ComponentsFactory.eINSTANCE.createConnection();
getContainer().getConnections().add(newElement);
newElement.getTarget().add(getSource());
newElement.getTarget().add(getTarget());
doConfigure(newElement, monitor, info);
((CreateElementRequest) getRequest()).setNewElement(newElement);
return CommandResult.newOKCommandResult(newElement);
}
/**
* @generated
*/
protected void doConfigure(Connection newElement, IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
IElementType elementType = ((CreateElementRequest) getRequest()).getElementType();
ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType);
configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext());
configureRequest.addParameters(getRequest().getParameters());
configureRequest.setParameter(CreateRelationshipRequest.SOURCE, getSource());
configureRequest.setParameter(CreateRelationshipRequest.TARGET, getTarget());
ICommand configureCommand = elementType.getEditCommand(configureRequest);
if (configureCommand != null && configureCommand.canExecute()) {
configureCommand.execute(monitor, info);
}
}
/**
* @generated
*/
protected void setElementToEdit(EObject element) {
throw new UnsupportedOperationException();
}
/**
* @generated
*/
protected Port getSource() {
return (Port) source;
}
/**
* @generated
*/
protected Port getTarget() {
return (Port) target;
}
/**
* @generated
*/
public Component getContainer() {
return container;
}
/**
* Default approach is to traverse ancestors of the source to find instance of container.
* Modify with appropriate logic.
* @generated
*/
private static Component deduceContainer(EObject source, EObject target) {
// Find container element for the new link.
// Climb up by containment hierarchy starting from the source
// and return the first element that is instance of the container class.
for (EObject element = source; element != null; element = element.eContainer()) {
if (element instanceof Component) {
return (Component) element;
}
}
return null;
}
}
| peterbartha/component-diagram | ComponentTester.diagram/src/components/diagram/edit/commands/ConnectionCreateCommand.java | Java | mit | 4,550 |
package edu.gatech.oad.antlab.pkg1;
import edu.cs2335.antlab.pkg3.*;
import edu.gatech.oad.antlab.person.*;
import edu.gatech.oad.antlab.pkg2.*;
/**
* CS2335 Ant Lab
*
* Prints out a simple message gathered from all of the other classes
* in the package structure
*/
public class AntLabMain {
/**antlab11.java message class*/
private AntLab11 ant11;
/**antlab12.java message class*/
private AntLab12 ant12;
/**antlab21.java message class*/
private AntLab21 ant21;
/**antlab22.java message class*/
private AntLab22 ant22;
/**antlab31 java message class which is contained in a jar resource file*/
private AntLab31 ant31;
/**
* the constructor that intializes all the helper classes
*/
public AntLabMain () {
ant11 = new AntLab11();
ant12 = new AntLab12();
ant21 = new AntLab21();
ant22 = new AntLab22();
ant31 = new AntLab31();
}
/**
* gathers a string from all the other classes and prints the message
* out to the console
*
*/
public void printOutMessage() {
String toPrint =
ant11.getMessage() + ant12.getMessage() + ant21.getMessage()
+ ant22.getMessage() + ant31.getMessage();
//Person1 replace P1 with your name
//and gburdell1 with your gt id
Person1 p1 = new Person1("Pranov");
toPrint += p1.toString("pduggasani3");
//Person2 replace P2 with your name
//and gburdell with your gt id
Person2 p2 = new Person2("Austin Dang");
toPrint += p2.toString("adang31");
//Person3 replace P3 with your name
//and gburdell3 with your gt id
Person3 p3 = new Person3("Jay Patel");
toPrint += p3.toString("jpatel345");
//Person4 replace P4 with your name
//and gburdell4 with your gt id
Person4 p4 = new Person4("Jin Chung");
toPrint += p4.toString("jchung89");
//Person5 replace P4 with your name
//and gburdell5 with your gt id
Person5 p5 = new Person5("Zachary Hussin");
toPrint += p5.toString("zhussin3");
System.out.println(toPrint);
}
/**
* entry point for the program
*/
public static void main(String[] args) {
new AntLabMain().printOutMessage();
}
} | PranovD/CS2340 | M2/src/main/java/edu/gatech/oad/antlab/pkg1/AntLabMain.java | Java | mit | 2,551 |
package net.alloyggp.tournament.internal.admin;
import net.alloyggp.escaperope.Delimiters;
import net.alloyggp.escaperope.RopeDelimiter;
import net.alloyggp.escaperope.rope.Rope;
import net.alloyggp.escaperope.rope.ropify.SubclassWeaver;
import net.alloyggp.escaperope.rope.ropify.Weaver;
import net.alloyggp.tournament.api.TAdminAction;
public class InternalAdminActions {
private InternalAdminActions() {
//Not instantiable
}
@SuppressWarnings("deprecation")
public static final Weaver<TAdminAction> WEAVER = SubclassWeaver.builder(TAdminAction.class)
.add(ReplaceGameAction.class, "ReplaceGame", ReplaceGameAction.WEAVER)
.build();
public static RopeDelimiter getStandardDelimiter() {
return Delimiters.getJsonArrayRopeDelimiter();
}
public static TAdminAction fromPersistedString(String persistedString) {
Rope rope = getStandardDelimiter().undelimit(persistedString);
return WEAVER.fromRope(rope);
}
public static String toPersistedString(TAdminAction adminAction) {
Rope rope = WEAVER.toRope(adminAction);
return getStandardDelimiter().delimit(rope);
}
}
| AlexLandau/ggp-tournament | src/main/java/net/alloyggp/tournament/internal/admin/InternalAdminActions.java | Java | mit | 1,179 |
package com.agileEAP.workflow.definition;
/**
活动类型
*/
public enum ActivityType
{
/**
开始活动
*/
//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
//[Remark("开始活动")]
StartActivity(1),
/**
人工活动
*/
//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
//[Remark("人工活动")]
ManualActivity(2),
/**
路由活动
*/
//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
//[Remark("路由活动")]
RouterActivity(3),
/**
子流程活动
*/
//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
//[Remark("子流程活动")]
SubflowActivity(4),
/**
自动活动
*/
//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
//[Remark("自动活动")]
AutoActivity(5),
/**
结束活动
*/
//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
//[Remark("结束活动")]
EndActivity(6),
/**
处理活动
*/
//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
//[Remark("处理活动")]
ProcessActivity(7);
private int intValue;
private static java.util.HashMap<Integer, ActivityType> mappings;
private synchronized static java.util.HashMap<Integer, ActivityType> getMappings()
{
if (mappings == null)
{
mappings = new java.util.HashMap<Integer, ActivityType>();
}
return mappings;
}
private ActivityType(int value)
{
intValue = value;
ActivityType.getMappings().put(value, this);
}
public int getValue()
{
return intValue;
}
public static ActivityType forValue(int value)
{
return getMappings().get(value);
}
} | AgileEAP/aglieEAP | agileEAP-workflow/src/main/java/com/agileEAP/workflow/definition/ActivityType.java | Java | mit | 1,812 |
package com.asayama.rps.simulator;
public enum Hand {
ROCK, PAPER, SCISSORS;
}
| kyoken74/rock-paper-scissors | src/main/java/com/asayama/rps/simulator/Hand.java | Java | mit | 83 |
package foodtruck.linxup;
import java.util.List;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.joda.time.DateTime;
import foodtruck.model.Location;
/**
* @author aviolette
* @since 11/1/16
*/
public class Trip {
private Location start;
private Location end;
private DateTime startTime;
private DateTime endTime;
private List<Position> positions;
private Trip(Builder builder) {
this.start = builder.start;
this.end = builder.end;
this.startTime = builder.startTime;
this.endTime = builder.endTime;
this.positions = ImmutableList.copyOf(builder.positions);
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(Trip instance) {
return new Builder(instance);
}
public String getName() {
return start.getShortenedName() + " to " + end.getShortenedName();
}
public Location getStart() {
return start;
}
public Location getEnd() {
return end;
}
public DateTime getStartTime() {
return startTime;
}
public DateTime getEndTime() {
return endTime;
}
public List<Position> getPositions() {
return positions;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
// .add("start", start)
// .add("end", end)
.add("startTime", startTime)
.add("endTime", endTime)
.toString();
}
public static class Builder {
private Location start;
private Location end;
private DateTime startTime;
private DateTime endTime;
private List<Position> positions = Lists.newLinkedList();
public Builder() {
}
public Builder(Trip instance) {
this.start = instance.start;
this.end = instance.end;
this.startTime = instance.startTime;
this.endTime = instance.endTime;
this.positions = instance.positions;
}
public Builder start(Location start) {
this.start = start;
return this;
}
public Builder end(Location end) {
this.end = end;
return this;
}
public Builder startTime(DateTime startTime) {
this.startTime = startTime;
return this;
}
public Builder endTime(DateTime endTime) {
this.endTime = endTime;
return this;
}
public Trip build() {
return new Trip(this);
}
public DateTime getStartTime() {
return startTime;
}
public DateTime getEndTime() {
return endTime;
}
public Builder addPosition(Position position) {
positions.add(position);
return this;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("start", start.getShortenedName())
.add("end", end.getShortenedName())
// .add("start", start)
// .add("end", end)
.add("startTime", startTime)
.add("endTime", endTime)
.toString();
}
}
}
| aviolette/foodtrucklocator | main/src/main/java/foodtruck/linxup/Trip.java | Java | mit | 3,020 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
/**
* This package contains the classes for AutoRestParameterGroupingTestService.
* Test Infrastructure for AutoRest.
*/
package fixtures.azureparametergrouping;
| matt-gibbs/AutoRest | AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/package-info.java | Java | mit | 485 |
package net.lightstone.net.codec;
import java.io.IOException;
import net.lightstone.msg.Message;
import org.jboss.netty.buffer.ChannelBuffer;
public abstract class MessageCodec<T extends Message> {
private final Class<T> clazz;
private final int opcode;
public MessageCodec(Class<T> clazz, int opcode) {
this.clazz = clazz;
this.opcode = opcode;
}
public final Class<T> getType() {
return clazz;
}
public final int getOpcode() {
return opcode;
}
public abstract ChannelBuffer encode(T message) throws IOException;
public abstract T decode(ChannelBuffer buffer) throws IOException;
}
| grahamedgecombe/lightstone | src/net/lightstone/net/codec/MessageCodec.java | Java | mit | 613 |
package tests_dominio;
import org.junit.Assert;
import org.junit.Test;
import dominio.Asesino;
import dominio.Hechicero;
import dominio.Humano;
public class TestAsesino {
@Test
public void testRobar(){ }
@Test
public void testCritico(){
Humano h = new Humano("Nicolas",new Asesino(),1);
Humano h2 = new Humano("Lautaro",new Hechicero(),2);
Assert.assertEquals(105, h2.getSalud());
if (h.habilidadCasta1(h2))
Assert.assertTrue(93==h2.getSalud());
else
Assert.assertEquals(105, h2.getSalud());
}
@Test
public void testProbEvasion(){
Humano h = new Humano("Nico",100, 100, 25, 20, 30, new Asesino(0.2, 0.3, 1.5), 0, 1, 1);
Assert.assertTrue(0.3==h.getCasta().getProbabilidadEvitarDaño());
h.habilidadCasta2(null);
Assert.assertEquals(0.45, h.getCasta().getProbabilidadEvitarDaño(), 0.01);
h.habilidadCasta2(null);
Assert.assertTrue(0.5==h.getCasta().getProbabilidadEvitarDaño());
}
}
| programacion-avanzada/jrpg-2017a-dominio | src/test/java/tests_dominio/TestAsesino.java | Java | mit | 934 |
// LICENSE
package com.forgedui.editor.edit;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.CreateRequest;
import com.forgedui.editor.GUIEditorPlugin;
import com.forgedui.editor.edit.command.AddToTableViewElementCommand;
import com.forgedui.editor.edit.policy.ContainerEditPolicy;
import com.forgedui.editor.figures.TableViewFigure;
import com.forgedui.model.titanium.SearchBar;
import com.forgedui.model.titanium.TableView;
import com.forgedui.model.titanium.TableViewRow;
import com.forgedui.model.titanium.TableViewSection;
import com.forgedui.model.titanium.TitaniumUIBoundedElement;
import com.forgedui.model.titanium.TitaniumUIElement;
/**
* @author Dmitry {[email protected]}
*
*/
public class TableViewEditPart extends TitaniumContainerEditPart<TableView> {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List<?> getModelChildren_() {
List list = new ArrayList(super.getModelChildren_());
TableView model = (TableView)getModel();
if (model.getHeaderView() != null){
list.add(model.getHeaderView());
}
if (model.getFooterView() != null){
list.add(model.getFooterView());
}
if ((model.getSearchHidden() == null
|| !model.getSearchHidden())
&& model.getSearch() != null){
list.add(model.getSearch());
}
return list;
}
/**
* Making sure to refresh things visual.
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
final String propName = evt.getPropertyName();
if (TableView.PROP_HEADER_VIEW.equals(propName)
|| TableView.PROP_FOOTER_VIEW.equals(propName)
|| TableView.PROP_SEARCH_VIEW.equals(propName)
|| TableView.PROP_SEARCH_VIEW_HIDDEN.equals(propName)
|| TableView.PROP_MIN_ROW_HEIGHT.equals(propName)
|| TableView.PROP_MAX_ROW_HEIGHT.equals(propName)
) {
refresh();
} else {
super.propertyChange(evt);
}
}
@Override
protected void createEditPolicies() {
super.createEditPolicies();
installEditPolicy(ContainerEditPolicy.KEY, new TableViewEditPolicy());
}
@Override
protected void refreshVisuals() {
TableView model = (TableView)getModel();
TableViewFigure figure = (TableViewFigure)getFigure();
figure.setHeaderTitle(model.getHeaderTitle());
figure.setFooterTitle(model.getFooterTitle());
figure.setHasHeaderView(model.getHeaderView() != null);
figure.setHasFooterView(model.getFooterView() != null);
super.refreshVisuals();
}
}
class TableViewEditPolicy extends ContainerEditPolicy {
protected Command getCreateCommand(CreateRequest request) {
// And then passed those to the validate facility.
Object newObject = request.getNewObject();
Object container = getHost().getModel();
if (!GUIEditorPlugin.getComponentValidator().validate(newObject, container))
return null;
if (!(newObject instanceof TableViewRow) &&
!(newObject instanceof TableViewSection) &&
newObject instanceof TitaniumUIElement){
Rectangle r = (Rectangle)getConstraintFor(request);
if (r != null){
TitaniumUIBoundedElement child = (TitaniumUIBoundedElement) newObject;
if (container instanceof TableView){
TableView view = (TableView) getHost().getModel();
if (child instanceof SearchBar && view.getSearch() == null){
return new AddToTableViewElementCommand(view, child, r, true);
} else if (GUIEditorPlugin.getComponentValidator().isView(child)){
if (r.y <= view.getDimension().height / 2){
if (view.getHeaderView() == null){
return new AddToTableViewElementCommand(view, child, r, true);
}
} else if (view.getFooterView() == null){
return new AddToTableViewElementCommand(view, child, r, false);
}
}
return null;//Can't drop
}
}
}
return super.getCreateCommand(request);
}
/*@Override
protected Object getConstraintFor(CreateRequest request) {
Rectangle r = (Rectangle) super.getConstraintFor(request);
r.x = 0;
return r;
}*/
}
| ShoukriKattan/ForgedUI-Eclipse | com.forgedui.editor/src/com/forgedui/editor/edit/TableViewEditPart.java | Java | mit | 4,096 |
package com.daviancorp.android.data.database;
import android.database.Cursor;
import android.database.CursorWrapper;
import com.daviancorp.android.data.classes.Location;
/**
* A convenience class to wrap a cursor that returns rows from the "locations"
* table. The {@link getLocation()} method will give you a Location instance
* representing the current row.
*/
public class LocationCursor extends CursorWrapper {
public LocationCursor(Cursor c) {
super(c);
}
/**
* Returns a Location object configured for the current row, or null if the
* current row is invalid.
*/
public Location getLocation() {
if (isBeforeFirst() || isAfterLast())
return null;
Location location = new Location();
long locationId = getLong(getColumnIndex(S.COLUMN_LOCATIONS_ID));
String name = getString(getColumnIndex(S.COLUMN_LOCATIONS_NAME));
String fileLocation = getString(getColumnIndex(S.COLUMN_LOCATIONS_MAP));
location.setId(locationId);
location.setName(name);
location.setFileLocation(fileLocation);
return location;
}
} | dbooga/MonsterHunter3UDatabase | MonsterHunter3UDatabase/src/com/daviancorp/android/data/database/LocationCursor.java | Java | mit | 1,054 |
package bp.details;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import bp.model.data.Gateway;
import bp.model.util.BPKeyWords;
import bp.model.util.Controller;
public class GatewayDetails extends ElementDetails {
/**
*
*/
private static final long serialVersionUID = -2243209273015769935L;
public static final String MIN_INPUT = "Minimal input:";
private Gateway gateway = (Gateway) getElement();
private JLabel minInputLb;
private JSpinner minInputSp;
public GatewayDetails(Gateway element) {
super(element);
}
@Override
protected void initComponents() {
super.initComponents();
this.minInputLb = new JLabel(MIN_INPUT);
final SpinnerModel sm = new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1);
this.minInputSp = new JSpinner(sm);
// Set the texts if available
gateway = (Gateway) getElement();
if (gateway.getMinInput() != null)
minInputSp.setValue(gateway.getMinInput());
}
@Override
protected void layoutComponents() {
super.layoutComponents();
createAdvanced();
getAdvanced().add(this.minInputLb);
getAdvanced().add(this.minInputSp);
}
@Override
protected void addActions() {
super.addActions();
this.minInputSp.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent arg0) {
GatewayDetails.this.gateway.updateMinInput((Integer) GatewayDetails.this.minInputSp.getValue(),
Controller.DETAILS);
}
});
}
@Override
protected void dataAttributeChanged(final BPKeyWords keyWord, final Object value) {
super.dataAttributeChanged(keyWord, value);
if (value != null) {
if (keyWord == BPKeyWords.MIN_INPUT) {
this.minInputSp.setValue(value);
}
}
}
}
| farkas-arpad/KROKI-mockup-tool | BusinessProcessModelingTool/src/bp/details/GatewayDetails.java | Java | mit | 2,214 |
package com.cmput402w2016.t1.webapi.handler;
import com.cmput402w2016.t1.data.Segment;
import com.cmput402w2016.t1.webapi.Helper;
import com.cmput402w2016.t1.webapi.WebApi;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.util.Map;
/**
* Handler for the /segment webservice route
*/
public class SegmentHandler implements HttpHandler {
/**
* Handle the web request to the server
*
* @param httpExchange HttpExchange object containing the request
*/
@Override
public void handle(HttpExchange httpExchange) {
// Get & parse query
try {
String requestMethod = httpExchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
String query = httpExchange.getRequestURI().getRawQuery();
Map<String, String> stringStringMap = Helper.queryToMap(query);
if (stringStringMap.containsKey("geohash")) {
String geohash = stringStringMap.get("geohash");
String neighbors = Segment.getClosestSegmentFromGeohash(geohash, WebApi.get_segment_table());
Helper.requestResponse(httpExchange, 200, neighbors);
httpExchange.close();
return;
} else if (stringStringMap.containsKey("lat") && stringStringMap.containsKey("lon")) {
String lat = stringStringMap.get("lat");
String lon = stringStringMap.get("lon");
String neighbors = Segment.getClosestSegmentFromLatLon(lat, lon, WebApi.get_segment_table());
Helper.requestResponse(httpExchange, 200, neighbors);
httpExchange.close();
return;
}
}
Helper.malformedRequestResponse(httpExchange, 400, "Invalid query to the segment api");
httpExchange.close();
} catch (Exception e) {
// Wasn't returned earlier, something must be wrong
e.printStackTrace();
Helper.malformedRequestResponse(httpExchange, 400, e.getMessage());
httpExchange.close();
}
}
}
| cmput402w2016/CMPUT402W16T1 | MapCore/src/main/java/com/cmput402w2016/t1/webapi/handler/SegmentHandler.java | Java | mit | 2,216 |
package com.swfarm.biz.chain.bo;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Random;
import com.swfarm.pub.framework.FormNumberCache;
public class JobExecutionState implements Serializable {
private Long id;
private String jobName;
private String jobInstanceName;
private String saleChannel;
private String accountNumber;
private Timestamp executionTime = new Timestamp(System.currentTimeMillis());
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getJobInstanceName() {
return jobInstanceName;
}
public void setJobInstanceName(String jobInstanceName) {
this.jobInstanceName = jobInstanceName;
}
public String getSaleChannel() {
return saleChannel;
}
public void setSaleChannel(String saleChannel) {
this.saleChannel = saleChannel;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public Timestamp getExecutionTime() {
return executionTime;
}
public void setExecutionTime(Timestamp executionTime) {
this.executionTime = executionTime;
}
public String generateJobInstanceName() {
StringBuffer jobInstanceNameBuffer = new StringBuffer();
jobInstanceNameBuffer.append(this.jobName);
jobInstanceNameBuffer.append(System.currentTimeMillis());
Random random = new Random();
int i1 = FormNumberCache.getRandomInteger(1, 9, random);
int i2 = FormNumberCache.getRandomInteger(1, 9, random);
int i3 = FormNumberCache.getRandomInteger(1, 9, random);
int i4 = FormNumberCache.getRandomInteger(1, 9, random);
jobInstanceNameBuffer.append(i1);
jobInstanceNameBuffer.append(i2);
jobInstanceNameBuffer.append(i3);
jobInstanceNameBuffer.append(i4);
return jobInstanceNameBuffer.toString();
}
public static void main(String[] args) {
}
} | zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/chain/bo/JobExecutionState.java | Java | mit | 2,105 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.avs.implementation;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.avs.fluent.PlacementPoliciesClient;
import com.azure.resourcemanager.avs.fluent.models.PlacementPolicyInner;
import com.azure.resourcemanager.avs.models.PlacementPolicies;
import com.azure.resourcemanager.avs.models.PlacementPolicy;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class PlacementPoliciesImpl implements PlacementPolicies {
@JsonIgnore private final ClientLogger logger = new ClientLogger(PlacementPoliciesImpl.class);
private final PlacementPoliciesClient innerClient;
private final com.azure.resourcemanager.avs.AvsManager serviceManager;
public PlacementPoliciesImpl(
PlacementPoliciesClient innerClient, com.azure.resourcemanager.avs.AvsManager serviceManager) {
this.innerClient = innerClient;
this.serviceManager = serviceManager;
}
public PagedIterable<PlacementPolicy> list(String resourceGroupName, String privateCloudName, String clusterName) {
PagedIterable<PlacementPolicyInner> inner =
this.serviceClient().list(resourceGroupName, privateCloudName, clusterName);
return Utils.mapPage(inner, inner1 -> new PlacementPolicyImpl(inner1, this.manager()));
}
public PagedIterable<PlacementPolicy> list(
String resourceGroupName, String privateCloudName, String clusterName, Context context) {
PagedIterable<PlacementPolicyInner> inner =
this.serviceClient().list(resourceGroupName, privateCloudName, clusterName, context);
return Utils.mapPage(inner, inner1 -> new PlacementPolicyImpl(inner1, this.manager()));
}
public PlacementPolicy get(
String resourceGroupName, String privateCloudName, String clusterName, String placementPolicyName) {
PlacementPolicyInner inner =
this.serviceClient().get(resourceGroupName, privateCloudName, clusterName, placementPolicyName);
if (inner != null) {
return new PlacementPolicyImpl(inner, this.manager());
} else {
return null;
}
}
public Response<PlacementPolicy> getWithResponse(
String resourceGroupName,
String privateCloudName,
String clusterName,
String placementPolicyName,
Context context) {
Response<PlacementPolicyInner> inner =
this
.serviceClient()
.getWithResponse(resourceGroupName, privateCloudName, clusterName, placementPolicyName, context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new PlacementPolicyImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
public void delete(
String resourceGroupName, String privateCloudName, String clusterName, String placementPolicyName) {
this.serviceClient().delete(resourceGroupName, privateCloudName, clusterName, placementPolicyName);
}
public void delete(
String resourceGroupName,
String privateCloudName,
String clusterName,
String placementPolicyName,
Context context) {
this.serviceClient().delete(resourceGroupName, privateCloudName, clusterName, placementPolicyName, context);
}
public PlacementPolicy getById(String id) {
String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
if (resourceGroupName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
}
String privateCloudName = Utils.getValueFromIdByName(id, "privateClouds");
if (privateCloudName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'privateClouds'.", id)));
}
String clusterName = Utils.getValueFromIdByName(id, "clusters");
if (clusterName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'clusters'.", id)));
}
String placementPolicyName = Utils.getValueFromIdByName(id, "placementPolicies");
if (placementPolicyName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format(
"The resource ID '%s' is not valid. Missing path segment 'placementPolicies'.", id)));
}
return this
.getWithResponse(resourceGroupName, privateCloudName, clusterName, placementPolicyName, Context.NONE)
.getValue();
}
public Response<PlacementPolicy> getByIdWithResponse(String id, Context context) {
String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
if (resourceGroupName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
}
String privateCloudName = Utils.getValueFromIdByName(id, "privateClouds");
if (privateCloudName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'privateClouds'.", id)));
}
String clusterName = Utils.getValueFromIdByName(id, "clusters");
if (clusterName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'clusters'.", id)));
}
String placementPolicyName = Utils.getValueFromIdByName(id, "placementPolicies");
if (placementPolicyName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format(
"The resource ID '%s' is not valid. Missing path segment 'placementPolicies'.", id)));
}
return this.getWithResponse(resourceGroupName, privateCloudName, clusterName, placementPolicyName, context);
}
public void deleteById(String id) {
String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
if (resourceGroupName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
}
String privateCloudName = Utils.getValueFromIdByName(id, "privateClouds");
if (privateCloudName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'privateClouds'.", id)));
}
String clusterName = Utils.getValueFromIdByName(id, "clusters");
if (clusterName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'clusters'.", id)));
}
String placementPolicyName = Utils.getValueFromIdByName(id, "placementPolicies");
if (placementPolicyName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format(
"The resource ID '%s' is not valid. Missing path segment 'placementPolicies'.", id)));
}
this.delete(resourceGroupName, privateCloudName, clusterName, placementPolicyName, Context.NONE);
}
public void deleteByIdWithResponse(String id, Context context) {
String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
if (resourceGroupName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
}
String privateCloudName = Utils.getValueFromIdByName(id, "privateClouds");
if (privateCloudName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'privateClouds'.", id)));
}
String clusterName = Utils.getValueFromIdByName(id, "clusters");
if (clusterName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String.format("The resource ID '%s' is not valid. Missing path segment 'clusters'.", id)));
}
String placementPolicyName = Utils.getValueFromIdByName(id, "placementPolicies");
if (placementPolicyName == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
String
.format(
"The resource ID '%s' is not valid. Missing path segment 'placementPolicies'.", id)));
}
this.delete(resourceGroupName, privateCloudName, clusterName, placementPolicyName, context);
}
private PlacementPoliciesClient serviceClient() {
return this.innerClient;
}
private com.azure.resourcemanager.avs.AvsManager manager() {
return this.serviceManager;
}
public PlacementPolicyImpl define(String name) {
return new PlacementPolicyImpl(name, this.manager());
}
}
| Azure/azure-sdk-for-java | sdk/avs/azure-resourcemanager-avs/src/main/java/com/azure/resourcemanager/avs/implementation/PlacementPoliciesImpl.java | Java | mit | 11,094 |
/*
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.webodf;
import android.os.Bundle;
import org.apache.cordova.*;
public class WebODF extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html");
}
}
| brandon-bailey/osdms | assets/webodf/programs/cordova/platforms/android/src/org/webodf/WebODF.java | Java | mit | 1,303 |
/*
* This file is part of jGui API, licensed under the MIT License (MIT).
*
* Copyright (c) 2016 johni0702 <https://github.com/johni0702>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.johni0702.minecraft.gui.element;
import de.johni0702.minecraft.gui.GuiRenderer;
import de.johni0702.minecraft.gui.RenderInfo;
import de.johni0702.minecraft.gui.container.GuiContainer;
import de.johni0702.minecraft.gui.utils.lwjgl.Dimension;
import de.johni0702.minecraft.gui.utils.lwjgl.Point;
import de.johni0702.minecraft.gui.utils.lwjgl.ReadableDimension;
import de.johni0702.minecraft.gui.versions.MCVer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.Identifier;
public abstract class AbstractGuiElement<T extends AbstractGuiElement<T>> implements GuiElement<T> {
protected static final Identifier TEXTURE = new Identifier("jgui", "gui.png");
private final MinecraftClient minecraft = MCVer.getMinecraft();
private GuiContainer container;
private GuiElement tooltip;
private boolean enabled = true;
protected Dimension minSize, maxSize;
/**
* The last size this element was render at layer 0.
* May be {@code null} when this element has not yet been rendered.
*/
private ReadableDimension lastSize;
public AbstractGuiElement() {
}
public AbstractGuiElement(GuiContainer container) {
container.addElements(null, this);
}
protected abstract T getThis();
@Override
public void layout(ReadableDimension size, RenderInfo renderInfo) {
if (size == null) {
if (getContainer() == null) {
throw new RuntimeException("Any top containers must implement layout(null, ...) themselves!");
}
getContainer().layout(size, renderInfo.layer(renderInfo.layer + getLayer()));
return;
}
if (renderInfo.layer == 0) {
lastSize = size;
}
}
@Override
public void draw(GuiRenderer renderer, ReadableDimension size, RenderInfo renderInfo) {
}
@Override
public T setEnabled(boolean enabled) {
this.enabled = enabled;
return getThis();
}
@Override
public T setEnabled() {
return setEnabled(true);
}
@Override
public T setDisabled() {
return setEnabled(false);
}
@Override
public GuiElement getTooltip(RenderInfo renderInfo) {
if (tooltip != null && lastSize != null) {
Point mouse = new Point(renderInfo.mouseX, renderInfo.mouseY);
if (container != null) {
container.convertFor(this, mouse);
}
if (mouse.getX() > 0
&& mouse.getY() > 0
&& mouse.getX() < lastSize.getWidth()
&& mouse.getY() < lastSize.getHeight()) {
return tooltip;
}
}
return null;
}
@Override
public T setTooltip(GuiElement tooltip) {
this.tooltip = tooltip;
return getThis();
}
@Override
public T setContainer(GuiContainer container) {
this.container = container;
return getThis();
}
public T setMinSize(ReadableDimension minSize) {
this.minSize = new Dimension(minSize);
return getThis();
}
public T setMaxSize(ReadableDimension maxSize) {
this.maxSize = new Dimension(maxSize);
return getThis();
}
public T setSize(ReadableDimension size) {
setMinSize(size);
return setMaxSize(size);
}
public T setSize(int width, int height) {
return setSize(new Dimension(width, height));
}
public T setWidth(int width) {
if (minSize == null) {
minSize = new Dimension(width, 0);
} else {
minSize.setWidth(width);
}
if (maxSize == null) {
maxSize = new Dimension(width, Integer.MAX_VALUE);
} else {
maxSize.setWidth(width);
}
return getThis();
}
public T setHeight(int height) {
if (minSize == null) {
minSize = new Dimension(0, height);
} else {
minSize.setHeight(height);
}
if (maxSize == null) {
maxSize = new Dimension(Integer.MAX_VALUE, height);
} else {
maxSize.setHeight(height);
}
return getThis();
}
public int getLayer() {
return 0;
}
@Override
public ReadableDimension getMinSize() {
ReadableDimension calcSize = calcMinSize();
if (minSize == null) {
return calcSize;
} else {
if (minSize.getWidth() >= calcSize.getWidth() && minSize.getHeight() >= calcSize.getHeight()) {
return minSize;
} else {
return new Dimension(
Math.max(calcSize.getWidth(), minSize.getWidth()),
Math.max(calcSize.getHeight(), minSize.getHeight())
);
}
}
}
protected abstract ReadableDimension calcMinSize();
@Override
public ReadableDimension getMaxSize() {
return maxSize == null ? new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE) : maxSize;
}
public MinecraftClient getMinecraft() {
return this.minecraft;
}
public GuiContainer getContainer() {
return this.container;
}
public boolean isEnabled() {
return this.enabled;
}
protected ReadableDimension getLastSize() {
return this.lastSize;
}
}
| ReplayMod/jGui | src/main/java/de/johni0702/minecraft/gui/element/AbstractGuiElement.java | Java | mit | 6,656 |
/*
* Jermit
*
* The MIT License (MIT)
*
* Copyright (C) 2018 Kevin Lamonte
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* @author Kevin Lamonte [[email protected]]
* @version 1
*/
package jermit.protocol.zmodem;
/**
* ZEofHeader represents the end of a file.
*/
class ZEofHeader extends Header {
// ------------------------------------------------------------------------
// Constructors -----------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Public constructor.
*/
public ZEofHeader() {
this(0);
}
/**
* Public constructor.
*
* @param data the data field for this header
*/
public ZEofHeader(final int data) {
super(Type.ZEOF, (byte) 0x0B, "ZEOF", data);
}
// ------------------------------------------------------------------------
// Header -----------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ZEofHeader -------------------------------------------------------------
// ------------------------------------------------------------------------
/**
* Get the file size value.
*
* @return the value
*/
public int getFileSize() {
return data;
}
}
| klamonte/jermit | src/jermit/protocol/zmodem/ZEofHeader.java | Java | mit | 2,504 |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class FormLoader {
public static String connectionString = "jdbc:hsqldb:file:db-data/teamsandplayers";
static Connection con;
public static void main(String[] args) throws Exception {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
} catch (ClassNotFoundException e) {
throw e;
}
MainTeamForm form = new MainTeamForm();
form.setVisible(true);
try {
// will create DB if does not exist
// "SA" is default user with hypersql
con = DriverManager.getConnection(connectionString, "SA", "");
} catch (SQLException e) {
throw e;
} finally {
con.close();
System.out.println("Program complete");
}
}
}
| a-r-d/java-1-class-demos | jframe-actionlistener-access-db-cxn/homework-start/Week13Assignment10/src/FormLoader.java | Java | mit | 788 |
package com.zimbra.cs.versioncheck;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.common.account.Key;
import com.zimbra.common.account.Key.ServerBy;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.AdminConstants;
import com.zimbra.common.soap.SoapFaultException;
import com.zimbra.common.soap.SoapTransport;
import com.zimbra.common.util.CliUtil;
import com.zimbra.cs.account.Config;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.client.LmcSession;
import com.zimbra.cs.client.soap.LmcSoapClientException;
import com.zimbra.cs.client.soap.LmcVersionCheckRequest;
import com.zimbra.cs.client.soap.LmcVersionCheckResponse;
import com.zimbra.cs.util.BuildInfo;
import com.zimbra.cs.util.SoapCLI;
import com.zimbra.common.util.DateUtil;
/**
* @author Greg Solovyev
*/
public class VersionCheckUtil extends SoapCLI {
private static final String OPT_CHECK_VERSION = "c";
private static final String OPT_MANUAL_CHECK_VERSION = "m";
private static final String SHOW_LAST_STATUS = "r";
protected VersionCheckUtil() throws ServiceException {
super();
}
public static void main(String[] args) {
CliUtil.toolSetup();
SoapTransport.setDefaultUserAgent("zmcheckversion", BuildInfo.VERSION);
VersionCheckUtil util = null;
try {
util = new VersionCheckUtil();
} catch (ServiceException e) {
System.err.println(e.getMessage());
System.exit(1);
}
try {
util.setupCommandLineOptions();
CommandLine cl = null;
try {
cl = util.getCommandLine(args);
} catch (ParseException e) {
System.out.println(e.getMessage());
util.usage();
System.exit(1);
}
if (cl == null) {
System.exit(1);
}
if (cl.hasOption(OPT_CHECK_VERSION)) {
//check schedule
Provisioning prov = Provisioning.getInstance();
Config config;
config = prov.getConfig();
String updaterServerId = config.getAttr(Provisioning.A_zimbraVersionCheckServer);
if (updaterServerId != null) {
Server server = prov.get(Key.ServerBy.id, updaterServerId);
if (server != null) {
Server localServer = prov.getLocalServer();
if (localServer!=null) {
if(!localServer.getId().equalsIgnoreCase(server.getId())) {
System.out.println("Wrong server");
System.exit(0);
}
}
}
}
String versionInterval = config.getAttr(Provisioning.A_zimbraVersionCheckInterval);
if(versionInterval == null || versionInterval.length()==0 || versionInterval.equalsIgnoreCase("0")) {
System.out.println("Automatic updates are disabled");
System.exit(0);
} else {
long checkInterval = DateUtil.getTimeIntervalSecs(versionInterval,0);
String lastAttempt = config.getAttr(Provisioning.A_zimbraVersionCheckLastAttempt);
if(lastAttempt != null) {
Date lastChecked = DateUtil.parseGeneralizedTime(config.getAttr(Provisioning.A_zimbraVersionCheckLastAttempt));
Date now = new Date();
if (now.getTime()/1000- lastChecked.getTime()/1000 >= checkInterval) {
util.doVersionCheck();
} else {
System.out.println("Too early");
System.exit(0);
}
} else {
util.doVersionCheck();
}
}
} else if (cl.hasOption(OPT_MANUAL_CHECK_VERSION)) {
util.doVersionCheck();
} else if (cl.hasOption(SHOW_LAST_STATUS)) {
util.doResult();
System.exit(0);
} else {
util.usage();
System.exit(1);
}
} catch (Exception e) {
System.err.println(e.getMessage());
ZimbraLog.extensions.error("Error in versioncheck util", e);
util.usage(null);
System.exit(1);
}
}
private void doVersionCheck() throws SoapFaultException, IOException, ServiceException, LmcSoapClientException {
LmcSession session = auth();
LmcVersionCheckRequest req = new LmcVersionCheckRequest();
req.setAction(AdminConstants.VERSION_CHECK_CHECK);
req.setSession(session);
req.invoke(getServerUrl());
}
private void doResult() throws SoapFaultException, IOException, ServiceException, LmcSoapClientException {
try {
LmcSession session = auth();
LmcVersionCheckRequest req = new LmcVersionCheckRequest();
req.setAction(AdminConstants.VERSION_CHECK_STATUS);
req.setSession(session);
LmcVersionCheckResponse res = (LmcVersionCheckResponse) req.invoke(getServerUrl());
List <VersionUpdate> updates = res.getUpdates();
for(Iterator <VersionUpdate> iter = updates.iterator();iter.hasNext();){
VersionUpdate update = iter.next();
String critical;
if(update.isCritical()) {
critical = "critical";
} else {
critical = "not critical";
}
System.out.println(
String.format("Found a %s update. Update is %s . Update version: %s. For more info visit: %s",
update.getType(),critical,update.getVersion(),update.getUpdateURL())
);
}
} catch (SoapFaultException soape) {
System.out.println("Cought SoapFaultException");
System.out.println(soape.getStackTrace().toString());
throw (soape);
} catch (LmcSoapClientException lmce) {
System.out.println("Cought LmcSoapClientException");
System.out.println(lmce.getStackTrace().toString());
throw (lmce);
} catch (ServiceException se) {
System.out.println("Cought ServiceException");
System.out.println(se.getStackTrace().toString());
throw (se);
} catch (IOException ioe) {
System.out.println("Cought IOException");
System.out.println(ioe.getStackTrace().toString());
throw (ioe);
}
}
protected void setupCommandLineOptions() {
// super.setupCommandLineOptions();
Options options = getOptions();
Options hiddenOptions = getHiddenOptions();
hiddenOptions.addOption(OPT_CHECK_VERSION, "autocheck", false, "Initiate version check request (exits if zimbraVersionCheckInterval==0)");
options.addOption(SHOW_LAST_STATUS, "result", false, "Show results of last version check.");
options.addOption(OPT_MANUAL_CHECK_VERSION, "manual", false, "Initiate version check request.");
}
protected String getCommandUsage() {
return "zmcheckversion <options>";
}
}
| nico01f/z-pec | ZimbraAdminVersionCheck/src/java/com/zimbra/cs/versioncheck/VersionCheckUtil.java | Java | mit | 7,334 |
package br.ufrj.g2matricula.domain;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import br.ufrj.g2matricula.domain.enumeration.MatriculaStatus;
/**
* A Matricula.
*/
@Entity
@Table(name = "matricula")
@Document(indexName = "matricula")
public class Matricula implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private MatriculaStatus status;
@ManyToOne
private Aluno dreAluno;
@ManyToOne
private Curso curso;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public MatriculaStatus getStatus() {
return status;
}
public Matricula status(MatriculaStatus status) {
this.status = status;
return this;
}
public void setStatus(MatriculaStatus status) {
this.status = status;
}
public Aluno getDreAluno() {
return dreAluno;
}
public Matricula dreAluno(Aluno aluno) {
this.dreAluno = aluno;
return this;
}
public void setDreAluno(Aluno aluno) {
this.dreAluno = aluno;
}
public Curso getCurso() {
return curso;
}
public Matricula curso(Curso curso) {
this.curso = curso;
return this;
}
public void setCurso(Curso curso) {
this.curso = curso;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Matricula matricula = (Matricula) o;
if (matricula.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), matricula.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Matricula{" +
"id=" + getId() +
", status='" + getStatus() + "'" +
"}";
}
}
| DamascenoRafael/cos482-qualidade-de-software | www/src/main/java/br/ufrj/g2matricula/domain/Matricula.java | Java | mit | 2,535 |
package com.thilko.springdoc;
@SuppressWarnings("all")
public class CredentialsCode {
Integer age;
double anotherValue;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public double getAnotherValue() {
return anotherValue;
}
public void setAnotherValue(double anotherValue) {
this.anotherValue = anotherValue;
}
}
| thilko/gradle-springdoc-plugin | src/test/java/com/thilko/springdoc/CredentialsCode.java | Java | mit | 435 |
package fr.lteconsulting.pomexplorer.commands;
import fr.lteconsulting.pomexplorer.AppFactory;
import fr.lteconsulting.pomexplorer.Client;
import fr.lteconsulting.pomexplorer.Log;
public class HelpCommand
{
@Help( "gives this message" )
public void main( Client client, Log log )
{
log.html( AppFactory.get().commands().help() );
}
}
| ltearno/pom-explorer | pom-explorer/src/main/java/fr/lteconsulting/pomexplorer/commands/HelpCommand.java | Java | mit | 342 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2020_04_01;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Tags object for patch operations.
*/
public class TagsObject {
/**
* Resource tags.
*/
@JsonProperty(value = "tags")
private Map<String, String> tags;
/**
* Get resource tags.
*
* @return the tags value
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set resource tags.
*
* @param tags the tags value to set
* @return the TagsObject object itself.
*/
public TagsObject withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
}
| selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/network/v2020_04_01/TagsObject.java | Java | mit | 954 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.core.server.network;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.login.server.S00PacketDisconnect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.ServerConfigurationManager;
import net.minecraft.server.network.NetHandlerLoginServer;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
import org.apache.logging.log4j.Logger;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.profile.GameProfile;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.network.RemoteConnection;
import org.spongepowered.api.text.Text;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.interfaces.IMixinNetHandlerLoginServer;
import org.spongepowered.common.text.SpongeTexts;
import java.net.SocketAddress;
import java.util.Optional;
@Mixin(NetHandlerLoginServer.class)
public abstract class MixinNetHandlerLoginServer implements IMixinNetHandlerLoginServer {
@Shadow private static Logger logger;
@Shadow public NetworkManager networkManager;
@Shadow private MinecraftServer server;
@Shadow private com.mojang.authlib.GameProfile loginGameProfile;
@Shadow public abstract String getConnectionInfo();
@Shadow public abstract com.mojang.authlib.GameProfile getOfflineProfile(com.mojang.authlib.GameProfile profile);
@Redirect(method = "tryAcceptPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/ServerConfigurationManager;"
+ "allowUserToConnect(Ljava/net/SocketAddress;Lcom/mojang/authlib/GameProfile;)Ljava/lang/String;"))
public String onAllowUserToConnect(ServerConfigurationManager confMgr, SocketAddress address, com.mojang.authlib.GameProfile profile) {
return null; // We handle disconnecting
}
private void closeConnection(IChatComponent reason) {
try {
logger.info("Disconnecting " + this.getConnectionInfo() + ": " + reason.getUnformattedText());
this.networkManager.sendPacket(new S00PacketDisconnect(reason));
this.networkManager.closeChannel(reason);
} catch (Exception exception) {
logger.error("Error whilst disconnecting player", exception);
}
}
private void disconnectClient(Optional<Text> disconnectMessage) {
IChatComponent reason = null;
if (disconnectMessage.isPresent()) {
reason = SpongeTexts.toComponent(disconnectMessage.get());
} else {
reason = new ChatComponentTranslation("disconnect.disconnected");
}
this.closeConnection(reason);
}
@Override
public boolean fireAuthEvent() {
Optional<Text> disconnectMessage = Optional.of(Text.of("You are not allowed to log in to this server."));
ClientConnectionEvent.Auth event = SpongeEventFactory.createClientConnectionEventAuth(Cause.of(NamedCause.source(this.loginGameProfile)),
disconnectMessage, disconnectMessage, (RemoteConnection) this.networkManager, (GameProfile) this.loginGameProfile);
SpongeImpl.postEvent(event);
if (event.isCancelled()) {
this.disconnectClient(event.getMessage());
}
return event.isCancelled();
}
@Inject(method = "processLoginStart", at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/NetHandlerLoginServer;"
+ "currentLoginState:Lnet/minecraft/server/network/NetHandlerLoginServer$LoginState;",
opcode = Opcodes.PUTFIELD, ordinal = 1), cancellable = true)
public void fireAuthEventOffline(CallbackInfo ci) {
// Move this check up here, so that the UUID isn't null when we fire the event
if (!this.loginGameProfile.isComplete()) {
this.loginGameProfile = this.getOfflineProfile(this.loginGameProfile);
}
if (this.fireAuthEvent()) {
ci.cancel();
}
}
}
| kashike/SpongeCommon | src/main/java/org/spongepowered/common/mixin/core/server/network/MixinNetHandlerLoginServer.java | Java | mit | 5,729 |
// This file is automatically generated.
package adila.db;
/*
* Motorola Cliq-XT
*
* DEVICE: zeppelin
* MODEL: MB501
*/
final class zeppelin_mb501 {
public static final String DATA = "Motorola|Cliq-XT|";
}
| karim/adila | database/src/main/java/adila/db/zeppelin_mb501.java | Java | mit | 217 |
package util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Taken from
* http://www.javaworld.com/article/2077578/learn-java/java-tip-76--an-alternative-to-the-deep-copy-technique.html
*
* @author David Miller (maybe)
*/
public class ObjectCloner
{
// so that nobody can accidentally create an ObjectCloner object
private ObjectCloner() {
}
// returns a deep copy of an object
static public Object deepCopy(Object oldObj) throws Exception
{
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try
{
ByteArrayOutputStream bos =
new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
// serialize and pass the object
oos.writeObject(oldObj); // C
oos.flush(); // D
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
// return the new object
return ois.readObject(); // G
} catch (Exception e)
{
System.out.println("Exception in ObjectCloner = " + e);
throw (e);
} finally
{
oos.close();
ois.close();
}
}
} | mokonzi131/gatech-colorwar | CS 2340 Agent Simulation/src/util/ObjectCloner.java | Java | mit | 1,184 |
import java.awt.*;
public class ListFonts
{
public static void main(String[] args)
{
String[] fontNames = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
for (int i = 0; i < fontNames.length; i++)
System.out.println(fontNames[i]);
}
}
| vivekprocoder/teaching | java/lecture 14/ListFonts.java | Java | mit | 336 |
package boun.swe573.accessbadger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ABHelloWorld {
@RequestMapping("/welcome")
public String helloWorld() {
String message = "<br><div style='text-align:center;'>"
+ "<h3>********** Hello World **********</div><br><br>";
return message;
}
}
| alihaluk/swe573main | src/boun/swe573/accessbadger/ABHelloWorld.java | Java | mit | 393 |
package gradebookdata;
/**
* Represents one row of the course table in the GradeBook database
*
* @author Eric Carlton
*
*/
public class Course {
private String name;
private int weight;
private int ID;
/**
* Create a course with all fields filled
*
* @param name
* name of course
* @param weight
* credit hours ( or weight ) of course
* @param ID
* course_ID in course table
*/
public Course(String name, int weight, int ID) {
this.name = name;
this.weight = weight;
this.ID = ID;
}
/**
* Create a generic course
*/
public Course() {
this("no name", 0, -1);
}
public String getName() {
return name;
}
public Integer getWeight() {
return weight;
}
public Integer getID() {
return ID;
}
/**
* Returns a string formatted as:
* course_name
* course_weight hour(s)
*/
@Override
public String toString() {
String result = name + "\n" + weight;
if (weight == 1)
result = result + " hour";
else
result = result + " hours";
return result;
}
}
| Eric-Carlton/GradeBook | GradeBook/src/gradebookdata/Course.java | Java | mit | 1,062 |
package com.orbital.lead.controller.Activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.orbital.lead.R;
import com.orbital.lead.controller.RecyclerViewAdapter.RecyclerDividerItemDecoration;
import com.orbital.lead.controller.RecyclerViewAdapter.RecyclerProjectListAdapter;
import com.orbital.lead.controller.RecyclerViewAdapter.RecyclerTagListAdapter;
import com.orbital.lead.model.Constant;
import com.orbital.lead.model.EnumDialogEditJournalType;
import com.orbital.lead.model.EnumOpenPictureActivityType;
import com.orbital.lead.model.Journal;
import com.orbital.lead.model.Project;
import com.orbital.lead.model.ProjectList;
import com.orbital.lead.model.Tag;
import com.orbital.lead.model.TagList;
public class AddNewSpecificJournalActivity extends BaseActivity {
private final String TAG = this.getClass().getSimpleName();
private View mToolbarView;
private TextView mToolbarTitle;
private TextView mTextJournalDate;
private TextView mTextTag;
private TextView mTextProject;
private EditText mEditTextTitle;
private EditText mEditTextContent;
private AlertDialog mDialogSave;
private Journal newJournal;
private TagList newTagList;
private ProjectList newProjectList;
private Project newProject;
private DatePickerDialog datePickerDialog;
private DatePickerDialog.OnDateSetListener datePickerListener;
private RecyclerView mRecyclerViewTagList;
private RecyclerView mRecyclerViewProjectList;
private RecyclerView.Adapter mRecyclerDialogTagAdapter;
private RecyclerView.Adapter mRecyclerDialogProjectAdapter;
//private String newJournalID;
//private String newAlbumID;
private int mYear;
private int mMonth;
private int mDay;
private boolean toggleRefresh = false;
private boolean isSaved = false;
private boolean discard = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_add_new_specific_journal, getBaseFrameLayout());
this.initToolbar();
this.initToolbarTitle();
this.setToolbarTitle(Constant.TITLE_ADD_NEW_JOURNAL);
this.pushToolbarToActionbar();
this.restoreCustomActionbar();
this.restoreDrawerHeaderValues();
this.initJournalReceiver();
this.retrieveNewJournalAlbumID();
this.initNewJournal();
this.initTextTitle();
this.initTextContent();
this.initTextJournalDate();
this.initTextTag();
this.initTextProject();
this.initNewTagList();
this.initNewProject();
this.initOnDateSetListener();
this.initTagSet();
this.retrievePreferenceTagSet();
this.newProjectList = new ProjectList();
this.newProjectList.setList(this.getCurrentUser().getProjectList());
Bundle getBundleExtra = getIntent().getExtras();
if (getBundleExtra != null) {
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!getNavigationDrawerFragment().isDrawerOpen()) {
getMenuInflater().inflate(R.menu.menu_add_new_specific_journal, menu);
this.restoreCustomActionbar();
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case android.R.id.home: // save the current new journal
//onBackPressed();
this.uploadNewJournal();
return true;
case R.id.action_image:
getLogic().displayPictureActivity(this, EnumOpenPictureActivityType.OPEN_FRAGMENT_LIST_PICTURES,
this.getNewJournal().getAlbum(), this.getNewJournal().getJournalID());
return true;
}
return false;
}
@Override
public void setToolbarTitle(String title){
this.mToolbarTitle.setText(title);
}
@Override
public void onBackPressed() {
if(!this.getIsSaved() && !this.getDiscard()) { // save and not discard
this.showSaveDialog();
return;
}else{ //if discard and don't save, delete album and return to previous activity
this.deleteAlbum();
}
Intent intent = new Intent();
intent.putExtra(Constant.BUNDLE_PARAM_JOURNAL_LIST_TOGGLE_REFRESH, this.getToggleRefresh());
setResult(Activity.RESULT_OK, intent);
finish();
super.onBackPressed();
}
private void restoreCustomActionbar(){
// disable the home button and onClick to open navigation drawer
// enable the back arrow button
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_done);
}
public void initToolbar() {
this.mToolbarView = findViewById(R.id.custom_specific_journal_toolbar);
((Toolbar) this.mToolbarView).setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//onBackPressed();
getLogging().debug(TAG, "mToolbarView setNavigationOnClickListener onClick");
}
});
}
public void refreshRecyclerDialogTagAdapter(){
if(this.mRecyclerDialogTagAdapter != null) {
this.mRecyclerDialogTagAdapter.notifyDataSetChanged();
}
}
public void setToggleRefresh(boolean val) {
this.toggleRefresh = val;
}
public void setIsSaved(boolean val) {
this.isSaved = val;
}
public void setDiscard(boolean val) {
this.discard = val;
}
private void initToolbarTitle() {
this.mToolbarTitle = (TextView) findViewById(R.id.toolbar_text_title);
}
private View getToolbar() {
return this.mToolbarView;
}
private void pushToolbarToActionbar() {
setSupportActionBar((Toolbar) this.getToolbar());
}
private void retrieveNewJournalAlbumID() {
this.getLogic().getNewJournalAlbumID(this, this.getCurrentUser().getUserID());
}
private void initNewJournal() {
this.newJournal = new Journal();
}
private void initTextTitle() {
this.mEditTextTitle = (EditText) findViewById(R.id.edit_text_title);
}
private void initTextContent(){
this.mEditTextContent = (EditText) findViewById(R.id.edit_text_content);
}
private void initTextJournalDate() {
this.mTextJournalDate = (TextView) findViewById(R.id.text_journal_date);
this.mTextJournalDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDatePickerDialog();
}
});
}
private void initOnDateSetListener() {
this.datePickerListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
String databaseFormatDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
setTextJournalDate(convertToDisplayDate(databaseFormatDate));
}
};
}
private void initTextTag() {
this.mTextTag = (TextView) findViewById(R.id.text_journal_tag);
this.mTextTag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTagDialog(getTagSet().getTagList());
}
});
}
private void initTextProject() {
this.mTextProject = (TextView) findViewById(R.id.text_journal_project);
this.mTextProject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showProjectDialog(getCurrentUser().getProjectList());
}
});
}
private void initNewTagList() {
this.newTagList = new TagList();
}
private void initNewProject() {
this.newProject = new Project();
}
private void initDialogTagRecyclerView(View v){
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
this.mRecyclerViewTagList = (RecyclerView) v.findViewById(R.id.recycler_edit_tag);
this.mRecyclerViewTagList.setLayoutManager(layoutManager);
this.mRecyclerViewTagList.setHasFixedSize(false);
this.mRecyclerViewTagList.addItemDecoration(new RecyclerDividerItemDecoration(this, RecyclerDividerItemDecoration.VERTICAL_LIST));
this.mRecyclerViewTagList.setAdapter(this.getRecyclerDialogTagAdapter());
}
private void initDialogProjectRecyclerView(View v){
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
this.mRecyclerViewProjectList = (RecyclerView) v.findViewById(R.id.recycler_edit_project);
this.mRecyclerViewProjectList.setLayoutManager(layoutManager);
this.mRecyclerViewProjectList.setHasFixedSize(false);
this.mRecyclerViewProjectList.addItemDecoration(new RecyclerDividerItemDecoration(this, RecyclerDividerItemDecoration.VERTICAL_LIST));
this.mRecyclerViewProjectList.setAdapter(this.getRecyclerDialogProjectAdapter());
}
private void initRecyclerDialogTagAdapter(TagList currentUsedTagList){
getLogging().debug(TAG, "initRecyclerDialogTagAdapter");
this.mRecyclerDialogTagAdapter = new RecyclerTagListAdapter(currentUsedTagList);
/*
((RecyclerTagListAdapter) mRecyclerDialogTagAdapter).setOnItemClickListener(new RecyclerTagListAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
getLogging().debug(TAG, "initRecyclerDialogTagAdapter onItemClick position -> " + position);
}
});
*/
}
private void initRecyclerProjectAdapter(ProjectList list){
getLogging().debug(TAG, "initRecyclerProjectAdapter");
if(this.newProject != null) {
this.mRecyclerDialogProjectAdapter = new RecyclerProjectListAdapter(list, this.newProject.getProjectID());
}else{
this.mRecyclerDialogProjectAdapter = new RecyclerProjectListAdapter(list, "");
}
}
private RecyclerView.Adapter getRecyclerDialogTagAdapter(){
return this.mRecyclerDialogTagAdapter;
}
private RecyclerView.Adapter getRecyclerDialogProjectAdapter(){
return this.mRecyclerDialogProjectAdapter;
}
public void setNewJournalID(String id) {
this.getLogging().debug(TAG, "setNewJournalID id => " + id);
this.getNewJournal().setJournalID(id);
}
public void setNewAlbumID(String id) {
this.getLogging().debug(TAG, "setNewAlbumID id => " + id);
this.getNewJournal().getAlbum().setAlbumID(id);
}
public void setJournal(Journal j){
this.newJournal = j;
}
private void setEditTextTitle(String value){
this.mEditTextTitle.setText(value);
}
private void setEditTextContent(String value){
this.mEditTextContent.setText(value);
}
private void setTextJournalDate(String value) {
this.mTextJournalDate.setText(value);
}
private void setTextTag(String value){
this.mTextTag.setText(value);
}
private void setTextProject(String value){
this.mTextProject.setText(value);
}
private void setNewProject(Project project) {
this.newProject = project;
}
private String getEditTextTitle() {
return this.mEditTextTitle.getText().toString();
}
private String getTextJournalDate() {
return this.mTextJournalDate.getText().toString();
}
private String getTextTags() {
return this.mTextTag.getText().toString();
}
private String getTextProject() {
return this.mTextProject.getText().toString();
}
private String getEditTextContent() {
return this.mEditTextContent.getText().toString();
}
private TagList getTagList() {
return this.newTagList;
}
private boolean getToggleRefresh() {
return this.toggleRefresh;
}
private boolean getIsSaved() {
return this.isSaved;
}
private boolean getDiscard() {
return this.discard;
}
private Journal getNewJournal() {
return this.newJournal;
}
private void updateNewTagList(TagList list) {
this.newTagList.replaceWithTagList(list);
}
/*=============== DIALOGS ==========*/
private void showDatePickerDialog(){
this.datePickerDialog = new DatePickerDialog(this,
this.getDatePickerListener(),
this.mYear,
this.mMonth,
this.mDay);
this.datePickerDialog.show();
}
private DatePickerDialog.OnDateSetListener getDatePickerListener(){
return this.datePickerListener;
}
private void showTagDialog(TagList list){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_tag, null);
this.initRecyclerDialogTagAdapter(list);
this.initDialogTagRecyclerView(dialogView);
ImageView addNewTag = (ImageView) dialogView.findViewById(R.id.image_toolbar_add_new_tag);
addNewTag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getLogic().showAddTagProjectDialog(AddNewSpecificJournalActivity.this, EnumDialogEditJournalType.ADD_TAG, "");
}
});
builder.setView(dialogView)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
TagList list = ((RecyclerTagListAdapter) getRecyclerDialogTagAdapter()).getTagList();
updateNewTagList(list); // update new tag list
for (Tag t : newTagList.getList()) {
getLogging().debug(TAG, "after update newTagList t.getName() => " + t.getName() + " checked => " + t.getIsChecked());
}
setTextTag(newTagList.getCheckedToString()); // update the tag text, show only all checked tags
}
});
builder.create().show();
}
private void showProjectDialog(ProjectList projectList){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_project, null);
this.initRecyclerProjectAdapter(projectList);
this.initDialogProjectRecyclerView(dialogView);
ImageView addNewProject = (ImageView) dialogView.findViewById(R.id.image_toolbar_add_new_project);
addNewProject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getLogic().showAddTagProjectDialog(AddNewSpecificJournalActivity.this, EnumDialogEditJournalType.ADD_PROJECT, "");
}
});
builder.setView(dialogView)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Project selectedProject = ((RecyclerProjectListAdapter) getRecyclerDialogProjectAdapter()).getSelectedProject();
newProject = selectedProject;
newProjectList.resetList();
if (selectedProject != null) { // sometimes user will not choose a project
newProjectList.updateProject(selectedProject);
}
setTextProject(selectedProject != null ? selectedProject.getName() : "");
setNewProject(selectedProject); // update the new project
}
});
builder.create().show();
}
private void showSaveDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_save_layout, null);
builder.setView(dialogView)
.setPositiveButton(R.string.dialog_save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
getLogging().debug(TAG, "showSaveDialog Save");
uploadNewJournal();
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
getLogging().debug(TAG, "showSaveDialog Cancel");
mDialogSave.dismiss();
}
})
.setNeutralButton(R.string.dialog_discard, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
getLogging().debug(TAG, "showSaveDialog Discard");
setDiscard(true);
setToggleRefresh(false);
setIsSaved(false);
onBackPressed();
}
});
this.mDialogSave = builder.create();
this.mDialogSave.setCanceledOnTouchOutside(false);
this.mDialogSave.setCancelable(true);
this.mDialogSave.show();
}
private void uploadNewJournal() {
if(!this.isValidJournal()) {
this.getLogging().debug(TAG, "uploadNewJournal it is not a valid new journal");
return;
}
this.getNewJournal().setJournalID(this.getNewJournal().getJournalID());
this.getNewJournal().setTitle(this.getEditTextTitle());
this.getNewJournal().setContent(this.getEditTextContent());
this.getNewJournal().setJournalDate(this.convertToDatabaseDate(this.getTextJournalDate()));
this.getNewJournal().setTagList(this.newTagList);
this.getNewJournal().setProject(this.newProject);
String detail = this.getParser().uploadNewJournalToJson(this.getNewJournal());
this.getLogging().debug(TAG, "uploadNewJournal detail => " + detail);
this.getLogic().insertNewJournal(this,
this.getCurrentUser().getUserID(),
this.getNewJournal().getJournalID(),
this.getNewJournal().getAlbum().getAlbumID(),
detail);
}
private void deleteAlbum() {
this.getLogic().deleteAlbum(this, this.getNewJournal().getAlbum().getAlbumID());
}
private boolean isValidJournal() {
// Check title and content
if(getParser().isStringEmpty(this.getEditTextTitle()) &&
getParser().isStringEmpty(this.getEditTextContent())) {
return false; // if both empty, means it is not suitable to be uploaded as a new journal
}
return true;
}
}
| orbitaljt/LEAD | Android/Lead/app/src/main/java/com/orbital/lead/controller/Activity/AddNewSpecificJournalActivity.java | Java | mit | 20,434 |
/*
* (C) Copyright 2015 Richard Greenlees
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* 1) The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package com.jumi.scene.objects;
/**
*
* @author RGreenlees
*/
public class JUMISkinDeformer {
String name;
public JUMISubDeformer[] deformers = new JUMISubDeformer[0];
public JUMISkinDeformer(String inName) {
name = inName;
}
public String toString() {
String result = "Skin Deformer " + name + ":";
for (int i = 0; i < deformers.length; i++) {
result = result + "\n\t" + deformers[i].name;
}
return result;
}
public JUMISubDeformer getSubDeformerByIndex(int index) {
if (index >= deformers.length) {
return null;
}
return deformers[index];
}
public JUMISubDeformer getSubDeformerByName(String inName) {
for (JUMISubDeformer a : deformers) {
if (a.name.equals(inName)) {
return a;
}
}
return null;
}
}
| RGreenlees/JUMI-Java-Model-Importer | src/com/jumi/scene/objects/JUMISkinDeformer.java | Java | mit | 1,888 |
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int[] map = new int[128];
int count = 0, start = 0, end = 0, d = 0;
while (end < s.length()) {
if (map[s.charAt(end++)]++ == 0) count++;
while (count > 2) if(map[s.charAt(start++)]-- == 1) count--;
d = Math.max(d, end - start);
}
return d;
}
}
| zhugejunwei/Algorithms-in-Java-Swift-CPP | String/159. Longest Substring with At Most Two Distinct Characters.java | Java | mit | 411 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 MrInformatic.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package game.saver.remote.gamemaps;
import game.saver.GameData;
import game.saver.Quarry;
import game.saver.gamemaps.GameDoubleMap;
import game.saver.gamemaps.GameFloatMap;
import game.saver.remote.RemoteClassMap;
import game.saver.remote.Remoteable;
import java.util.LinkedList;
import java.util.Map;
/**
*
* @author MrInformatic
*/
public class RemoteGameDoubleMap<T extends GameData> extends GameDoubleMap<T> implements Remoteable{
private int id;
private Quarry quarry;
private RemoteClassMap remoteClassMap;
public RemoteGameDoubleMap(Quarry quarry,RemoteClassMap remoteClassMap){
this.quarry = quarry;
this.remoteClassMap = remoteClassMap;
}
@Override
public T put(Double key, T value) {
LinkedList<GameData> gameDatas = getUnaddedGameData(value);
T type = super.put(key,value);
sendPut(key, value, gameDatas);
return type;
}
@Override
public T remove(Object key) {
quarry.writeByte((byte)1);
quarry.writeDouble((Double)key);
return super.remove(key);
}
@Override
public void putAll(Map<? extends Double, ? extends T> m) {
LinkedList<GameData>[] gameDatases = new LinkedList[m.size()];
int i=0;
for(T ms : m.values()){
gameDatases[i] = getUnaddedGameData(ms);
i++;
}
super.putAll(m);
i=0;
for(Map.Entry<? extends Double, ? extends T> ms : m.entrySet()){
sendPut(ms.getKey(),ms.getValue(),gameDatases[i]);
i++;
}
}
@Override
public void clear() {
quarry.writeByte((byte)2);
super.clear();
}
private void sendPut(Double key,T value,LinkedList<GameData> unaddedGameData){
for(GameData gameData : unaddedGameData){
remoteClassMap.addClass(gameData.getClass());
}
quarry.writeInt(id);
quarry.writeByte((byte)0);
quarry.writeDouble(key);
quarry.writeInt(unaddedGameData.size());
for(GameData gameData : unaddedGameData){
quarry.writeInt(gameData.getId());
quarry.writeInt(remoteClassMap.getClassId(gameData.getClass()));
quarry.write(gameData);
}
for(GameData gameData : unaddedGameData){
gameData.writeChilds(quarry);
}
quarry.writeInt(-1);
}
private LinkedList<GameData> getUnaddedGameData(GameData gameData){
LinkedList<GameData> result = new LinkedList<>();
getUnaddedGameData(result,gameData);
return result;
}
private LinkedList<GameData> getUnaddedGameData(LinkedList<GameData> list,GameData gameData){
if(gameData.getId()==-1){
list.add(gameData);
}
for(GameData gameData1 : gameData.getChilds()){
getUnaddedGameData(list,gameData1);
}
return list;
}
@Override
public void update() {
try {
switch(quarry.readByte()){
case 0:
double key = quarry.readDouble();
LinkedList<GameData> gameDatas = new LinkedList<>();
int length = quarry.readInt();
for(int i=0;i<length;i++){
int id = quarry.readInt();
T value = (T)quarry.read(remoteClassMap.getClassbyId(quarry.readInt()));
gameDatas.add(value);
graph.set(id,value);
}
for(GameData gameData : gameDatas){
gameData.readChilds(quarry,graph);
}
break;
case 1:
remove(quarry.readDouble());
break;
case 2:
clear();
break;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void setId(int id){
this.id = id;
}
}
| MrInformatic/GameSaver | src/main/java/game/saver/remote/gamemaps/RemoteGameDoubleMap.java | Java | mit | 5,186 |
package com.example;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class ServletContainerInitializerImpl implements ServletContainerInitializer {
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
final AnnotationConfigWebApplicationContext wac = new AnnotationConfigWebApplicationContext();
wac.register(MvcConfig.class);
wac.refresh();
final DispatcherServlet servlet = new DispatcherServlet(wac);
final ServletRegistration.Dynamic reg = ctx.addServlet("dispatcher", servlet);
reg.addMapping("/*");
}
}
| backpaper0/sandbox | springmvc-study-no-xml/src/main/java/com/example/ServletContainerInitializerImpl.java | Java | mit | 923 |
package org.blendee.jdbc;
/**
* プレースホルダを持つ SQL 文と、プレースホルダにセットする値を持つものを表すインターフェイスです。
* @author 千葉 哲嗣
*/
public interface ComposedSQL extends ChainPreparedStatementComplementer {
/**
* このインスタンスが持つ SQL 文を返します。
* @return SQL 文
*/
String sql();
/**
* {@link PreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。
* @param complementer 入れ替える {@link PreparedStatementComplementer}
* @return 同じ SQL を持つ、別のインスタンス
*/
default ComposedSQL reproduce(PreparedStatementComplementer complementer) {
var sql = sql();
return new ComposedSQL() {
@Override
public String sql() {
return sql;
}
@Override
public int complement(int done, BPreparedStatement statement) {
complementer.complement(statement);
return Integer.MIN_VALUE;
}
};
}
/**
* {@link ChainPreparedStatementComplementer} を入れ替えた新しい {@link ComposedSQL} を生成します。
* @param complementer 入れ替える {@link ChainPreparedStatementComplementer}
* @return 同じ SQL を持つ、別のインスタンス
*/
default ComposedSQL reproduce(ChainPreparedStatementComplementer complementer) {
var sql = sql();
return new ComposedSQL() {
@Override
public String sql() {
return sql;
}
@Override
public int complement(int done, BPreparedStatement statement) {
return complementer.complement(done, statement);
}
};
}
}
| blendee/blendee | src/main/java/org/blendee/jdbc/ComposedSQL.java | Java | mit | 1,611 |
package com.github.sixro.minihabits.core.infrastructure.domain;
import java.util.*;
import com.badlogic.gdx.Preferences;
import com.github.sixro.minihabits.core.domain.*;
public class PreferencesBasedRepository implements Repository {
private final Preferences prefs;
public PreferencesBasedRepository(Preferences prefs) {
super();
this.prefs = prefs;
}
@Override
public Set<MiniHabit> findAll() {
String text = prefs.getString("mini_habits");
if (text == null || text.trim().isEmpty())
return new LinkedHashSet<MiniHabit>();
return newMiniHabits(text);
}
@Override
public void add(MiniHabit miniHabit) {
Set<MiniHabit> list = findAll();
list.add(miniHabit);
prefs.putString("mini_habits", asString(list));
prefs.flush();
}
@Override
public void update(Collection<MiniHabit> list) {
Set<MiniHabit> currentList = findAll();
currentList.removeAll(list);
currentList.addAll(list);
prefs.putString("mini_habits", asString(currentList));
prefs.flush();
}
@Override
public void updateProgressDate(DateAtMidnight aDate) {
prefs.putLong("last_feedback_timestamp", aDate.getTime());
prefs.flush();
}
@Override
public DateAtMidnight lastFeedbackDate() {
long timestamp = prefs.getLong("last_feedback_timestamp");
if (timestamp == 0L)
return null;
return DateAtMidnight.from(timestamp);
}
private Set<MiniHabit> newMiniHabits(String text) {
String[] parts = text.split(",");
Set<MiniHabit> ret = new LinkedHashSet<MiniHabit>();
for (String part: parts)
ret.add(newMiniHabit(part));
return ret;
}
private MiniHabit newMiniHabit(String part) {
int indexOfColon = part.indexOf(':');
String label = part.substring(0, indexOfColon);
Integer daysInProgress = Integer.parseInt(part.substring(indexOfColon +1));
MiniHabit habit = new MiniHabit(label, daysInProgress);
return habit;
}
private String asString(Collection<MiniHabit> list) {
StringBuilder b = new StringBuilder();
int i = 0;
for (MiniHabit each: list) {
b.append(each.label() + ":" + each.daysInProgress());
if (i < list.size()-1)
b.append(',');
i++;
}
return b.toString();
}
}
| sixro/minihabits | core/src/main/java/com/github/sixro/minihabits/core/infrastructure/domain/PreferencesBasedRepository.java | Java | mit | 2,241 |
// John Meyer
// CSE 271 F
// Dr. Angel Bravo
import java.util.Scanner;
import java.io.*;
/**
* Copies a file with line numbers prefixed to every line
*/
public class Lab2InputOutput {
public static void main(String[] args) throws Exception {
// Define variables
Scanner keyboardReader = new Scanner(System.in);
String inputFileName;
String outputFileName;
// Check arguments
if (args.length == 0) {
System.out.println("Usage: java Lab2InputOutput /path/to/file");
return;
}
inputFileName = args[0];
// Find input file
File inputFile = new File(inputFileName);
Scanner fileInput = new Scanner(inputFile);
// Get output file name
System.out.print("Output File Name: ");
outputFileName = keyboardReader.next();
File outputFile = new File(outputFileName);
// Start copying
PrintWriter fileOutput = new PrintWriter(outputFile);
String lineContent;
for (int lineNumber = 1; fileInput.hasNext(); lineNumber++) {
lineContent = fileInput.nextLine();
fileOutput.printf("/* %d */ %s%n", lineNumber, lineContent);
}
fileInput.close();
fileOutput.close();
} // end method main
} // end class Lab2InputOutput
| 0x326/academic-code-portfolio | 2016-2021 Miami University/CSE 271 Introduction to Object-Oriented Programming/Lab02/src/main/java/Lab2InputOutput.java | Java | mit | 1,334 |
package generated.zcsclient.mail;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for messagePartHitInfo complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="messagePartHitInfo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="e" type="{urn:zimbraMail}emailInfo" minOccurs="0"/>
* <element name="su" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="sf" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="s" type="{http://www.w3.org/2001/XMLSchema}long" />
* <attribute name="d" type="{http://www.w3.org/2001/XMLSchema}long" />
* <attribute name="cid" type="{http://www.w3.org/2001/XMLSchema}int" />
* <attribute name="mid" type="{http://www.w3.org/2001/XMLSchema}int" />
* <attribute name="ct" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="part" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "messagePartHitInfo", propOrder = {
"e",
"su"
})
public class testMessagePartHitInfo {
protected testEmailInfo e;
protected String su;
@XmlAttribute(name = "id")
protected String id;
@XmlAttribute(name = "sf")
protected String sf;
@XmlAttribute(name = "s")
protected Long s;
@XmlAttribute(name = "d")
protected Long d;
@XmlAttribute(name = "cid")
protected Integer cid;
@XmlAttribute(name = "mid")
protected Integer mid;
@XmlAttribute(name = "ct")
protected String ct;
@XmlAttribute(name = "name")
protected String name;
@XmlAttribute(name = "part")
protected String part;
/**
* Gets the value of the e property.
*
* @return
* possible object is
* {@link testEmailInfo }
*
*/
public testEmailInfo getE() {
return e;
}
/**
* Sets the value of the e property.
*
* @param value
* allowed object is
* {@link testEmailInfo }
*
*/
public void setE(testEmailInfo value) {
this.e = value;
}
/**
* Gets the value of the su property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSu() {
return su;
}
/**
* Sets the value of the su property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSu(String value) {
this.su = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the sf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSf() {
return sf;
}
/**
* Sets the value of the sf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSf(String value) {
this.sf = value;
}
/**
* Gets the value of the s property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getS() {
return s;
}
/**
* Sets the value of the s property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setS(Long value) {
this.s = value;
}
/**
* Gets the value of the d property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getD() {
return d;
}
/**
* Sets the value of the d property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setD(Long value) {
this.d = value;
}
/**
* Gets the value of the cid property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getCid() {
return cid;
}
/**
* Sets the value of the cid property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setCid(Integer value) {
this.cid = value;
}
/**
* Gets the value of the mid property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getMid() {
return mid;
}
/**
* Sets the value of the mid property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setMid(Integer value) {
this.mid = value;
}
/**
* Gets the value of the ct property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCt() {
return ct;
}
/**
* Sets the value of the ct property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCt(String value) {
this.ct = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the part property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPart() {
return part;
}
/**
* Sets the value of the part property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPart(String value) {
this.part = value;
}
}
| nico01f/z-pec | ZimbraSoap/src/wsdl-test/generated/zcsclient/mail/testMessagePartHitInfo.java | Java | mit | 7,074 |
package bits;
/**
* Created by krzysztofkaczor on 3/10/15.
*/
public class ExclusiveOrOperator implements BinaryOperator
{
@Override
public BitArray combine(BitArray operand1, BitArray operand2) {
if(operand1.size() != operand2.size()) {
throw new IllegalArgumentException("ExclusiveOrOperator operands must have same size");
}
int size = operand1.size();
BitArray result = new BitArray(size);
for (int i = 0;i < size;i++) {
boolean a = operand1.get(i);
boolean b = operand2.get(i);
result.set(i, a != b );
}
return result;
}
}
| krzkaczor/IDEA | src/main/java/bits/ExclusiveOrOperator.java | Java | mit | 651 |
package net.comfreeze.lib;
import android.app.AlarmManager;
import android.app.Application;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.location.LocationManager;
import android.media.AudioManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import net.comfreeze.lib.audio.SoundManager;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.TimeZone;
abstract public class CFZApplication extends Application {
public static final String TAG = "CFZApplication";
public static final String PACKAGE = "com.rastermedia";
public static final String KEY_DEBUG = "debug";
public static final String KEY_SYNC_PREFEX = "sync_";
public static SharedPreferences preferences = null;
protected static Context context = null;
protected static CFZApplication instance;
public static LocalBroadcastManager broadcast;
public static boolean silent = true;
@Override
public void onCreate() {
if (!silent)
Log.d(TAG, "Initializing");
instance = this;
setContext();
setPreferences();
broadcast = LocalBroadcastManager.getInstance(context);
super.onCreate();
}
@Override
public void onLowMemory() {
if (!silent)
Log.d(TAG, "Low memory!");
super.onLowMemory();
}
@Override
public void onTerminate() {
unsetContext();
if (!silent)
Log.d(TAG, "Terminating");
super.onTerminate();
}
abstract public void setPreferences();
abstract public void setContext();
abstract public void unsetContext();
abstract public String getProductionKey();
public static CFZApplication getInstance(Class<?> className) {
// log("Returning current application instance");
if (instance == null) {
synchronized (className) {
if (instance == null)
try {
instance = (CFZApplication) className.newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
return instance;
}
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String dir : children) {
if (!dir.equals("lib")) {
deleteDir(new File(appDir, dir));
}
}
}
preferences.edit().clear().commit();
}
private static boolean deleteDir(File dir) {
if (dir != null) {
if (!silent)
Log.d(PACKAGE, "Deleting: " + dir.getAbsolutePath());
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
return false;
}
}
return dir.delete();
}
return false;
}
public static int dipsToPixel(float value, float scale) {
return (int) (value * scale + 0.5f);
}
public static long timezoneOffset() {
Calendar calendar = Calendar.getInstance();
return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET));
}
public static long timezoneOffset(String timezone) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timezone));
return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET));
}
public static Resources res() {
return context.getResources();
}
public static LocationManager getLocationManager(Context context) {
return (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public static AlarmManager getAlarmManager(Context context) {
return (AlarmManager) context.getSystemService(ALARM_SERVICE);
}
public static NotificationManager getNotificationManager(Context context) {
return (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
}
public static AudioManager getAudioManager(Context context) {
return (AudioManager) context.getSystemService(AUDIO_SERVICE);
}
public static SoundManager getSoundManager(CFZApplication application) {
return (SoundManager) SoundManager.instance(application);
}
public static void setSyncDate(String key, long date) {
preferences.edit().putLong(KEY_SYNC_PREFEX + key, date).commit();
}
public static long getSyncDate(String key) {
return preferences.getLong(KEY_SYNC_PREFEX + key, -1L);
}
public static boolean needSync(String key, long limit) {
return (System.currentTimeMillis() - getSyncDate(key) > limit);
}
public static String hash(final String algorithm, final String s) {
try {
// Create specified hash
MessageDigest digest = java.security.MessageDigest.getInstance(algorithm);
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create hex string
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public boolean isProduction(Context context) {
boolean result = false;
try {
ComponentName component = new ComponentName(context, instance.getClass());
PackageInfo info = context.getPackageManager().getPackageInfo(component.getPackageName(), PackageManager.GET_SIGNATURES);
Signature[] sigs = info.signatures;
for (int i = 0; i < sigs.length; i++)
if (!silent)
Log.d(TAG, "Signing key: " + sigs[i].toCharsString());
String targetKey = getProductionKey();
if (null == targetKey)
targetKey = "";
if (targetKey.equals(sigs[0].toCharsString())) {
result = true;
if (!silent)
Log.d(TAG, "Signed with production key");
} else {
if (!silent)
Log.d(TAG, "Not signed with production key");
}
} catch (PackageManager.NameNotFoundException e) {
if (!silent)
Log.e(TAG, "Package exception", e);
}
return result;
}
public static class LOG {
// Without Throwables
public static void v(String tag, String message) {
if (!silent) Log.v(tag, message);
}
public static void d(String tag, String message) {
if (!silent) Log.d(tag, message);
}
public static void i(String tag, String message) {
if (!silent) Log.i(tag, message);
}
public static void w(String tag, String message) {
if (!silent) Log.w(tag, message);
}
public static void e(String tag, String message) {
if (!silent) Log.e(tag, message);
}
public static void wtf(String tag, String message) {
if (!silent) Log.wtf(tag, message);
}
// With Throwables
public static void v(String tag, String message, Throwable t) {
if (!silent) Log.v(tag, message, t);
}
public static void d(String tag, String message, Throwable t) {
if (!silent) Log.d(tag, message, t);
}
public static void i(String tag, String message, Throwable t) {
if (!silent) Log.i(tag, message, t);
}
public static void w(String tag, String message, Throwable t) {
if (!silent) Log.w(tag, message, t);
}
public static void e(String tag, String message, Throwable t) {
if (!silent) Log.e(tag, message, t);
}
public static void wtf(String tag, String message, Throwable t) {
if (!silent) Log.wtf(tag, message, t);
}
}
}
| comfreeze/android-tools | CFZLib/src/main/java/net/comfreeze/lib/CFZApplication.java | Java | mit | 8,991 |
package com.example.mesh;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EndpointControlResource {
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#capabilities">https://relay.bluejeans.com/docs/mesh.html#capabilities</a>
*/
@GET
@Path("{ipAddress}/capabilities")
public Map<String, Boolean> capabilities(@PathParam("ipAddress") final String ipAddress,
@QueryParam("port") final Integer port,
@QueryParam("name") final String name) {
System.out.println("Received capabilities request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" port = " + port);
System.out.println(" name = " + name);
final Map<String, Boolean> capabilities = new HashMap<>();
capabilities.put("JOIN", true);
capabilities.put("HANGUP", true);
capabilities.put("STATUS", true);
capabilities.put("MUTEMICROPHONE", true);
return capabilities;
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#status">https://relay.bluejeans.com/docs/mesh.html#status</a>
*/
@GET
@Path("{ipAddress}/status")
public Map<String, Boolean> status(@PathParam("ipAddress") final String ipAddress, @QueryParam("port") final Integer port,
@QueryParam("name") final String name) {
System.out.println("Received status request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" port = " + port);
System.out.println(" name = " + name);
final Map<String, Boolean> status = new HashMap<>();
status.put("callActive", false);
status.put("microphoneMuted", false);
return status;
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#join">https://relay.bluejeans.com/docs/mesh.html#join</a>
*/
@POST
@Path("{ipAddress}/join")
public void join(@PathParam("ipAddress") final String ipAddress, @QueryParam("dialString") final String dialString,
@QueryParam("meetingId") final String meetingId, @QueryParam("passcode") final String passcode,
@QueryParam("bridgeAddress") final String bridgeAddress, final Endpoint endpoint) {
System.out.println("Received join request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" dialString = " + dialString);
System.out.println(" meetingId = " + meetingId);
System.out.println(" passcode = " + passcode);
System.out.println(" bridgeAddress = " + bridgeAddress);
System.out.println(" endpoint = " + endpoint);
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#hangup">https://relay.bluejeans.com/docs/mesh.html#hangup</a>
*/
@POST
@Path("{ipAddress}/hangup")
public void hangup(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received hangup request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#mutemicrophone">https://relay.bluejeans.com/docs/mesh.html#mutemicrophone</a>
*/
@POST
@Path("{ipAddress}/mutemicrophone")
public void muteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received mutemicrophone request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
/**
* @see <a href="https://relay.bluejeans.com/docs/mesh.html#mutemicrophone">https://relay.bluejeans.com/docs/mesh.html#mutemicrophone</a>
*/
@POST
@Path("{ipAddress}/unmutemicrophone")
public void unmuteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received unmutemicrophone request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
}
| Aldaviva/relay-mesh-example-java | src/main/java/com/example/mesh/EndpointControlResource.java | Java | mit | 4,452 |
/*
* Encog(tm) Core v3.1 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2012 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.plugin.system;
import org.encog.EncogError;
import org.encog.engine.network.activation.ActivationFunction;
import org.encog.ml.MLMethod;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.factory.MLTrainFactory;
import org.encog.ml.factory.train.AnnealFactory;
import org.encog.ml.factory.train.BackPropFactory;
import org.encog.ml.factory.train.ClusterSOMFactory;
import org.encog.ml.factory.train.GeneticFactory;
import org.encog.ml.factory.train.LMAFactory;
import org.encog.ml.factory.train.ManhattanFactory;
import org.encog.ml.factory.train.NeighborhoodSOMFactory;
import org.encog.ml.factory.train.NelderMeadFactory;
import org.encog.ml.factory.train.PNNTrainFactory;
import org.encog.ml.factory.train.PSOFactory;
import org.encog.ml.factory.train.QuickPropFactory;
import org.encog.ml.factory.train.RBFSVDFactory;
import org.encog.ml.factory.train.RPROPFactory;
import org.encog.ml.factory.train.SCGFactory;
import org.encog.ml.factory.train.SVMFactory;
import org.encog.ml.factory.train.SVMSearchFactory;
import org.encog.ml.factory.train.TrainBayesianFactory;
import org.encog.ml.train.MLTrain;
import org.encog.plugin.EncogPluginBase;
import org.encog.plugin.EncogPluginService1;
public class SystemTrainingPlugin implements EncogPluginService1 {
/**
* The factory for K2
*/
private final TrainBayesianFactory bayesianFactory = new TrainBayesianFactory();
/**
* The factory for backprop.
*/
private final BackPropFactory backpropFactory = new BackPropFactory();
/**
* The factory for LMA.
*/
private final LMAFactory lmaFactory = new LMAFactory();
/**
* The factory for RPROP.
*/
private final RPROPFactory rpropFactory = new RPROPFactory();
/**
* THe factory for basic SVM.
*/
private final SVMFactory svmFactory = new SVMFactory();
/**
* The factory for SVM-Search.
*/
private final SVMSearchFactory svmSearchFactory = new SVMSearchFactory();
/**
* The factory for SCG.
*/
private final SCGFactory scgFactory = new SCGFactory();
/**
* The factory for simulated annealing.
*/
private final AnnealFactory annealFactory = new AnnealFactory();
/**
* Nelder Mead Factory.
*/
private final NelderMeadFactory nmFactory = new NelderMeadFactory();
/**
* The factory for neighborhood SOM.
*/
private final NeighborhoodSOMFactory neighborhoodFactory
= new NeighborhoodSOMFactory();
/**
* The factory for SOM cluster.
*/
private final ClusterSOMFactory somClusterFactory = new ClusterSOMFactory();
/**
* The factory for genetic.
*/
private final GeneticFactory geneticFactory = new GeneticFactory();
/**
* The factory for Manhattan networks.
*/
private final ManhattanFactory manhattanFactory = new ManhattanFactory();
/**
* Factory for SVD.
*/
private final RBFSVDFactory svdFactory = new RBFSVDFactory();
/**
* Factory for PNN.
*/
private final PNNTrainFactory pnnFactory = new PNNTrainFactory();
/**
* Factory for quickprop.
*/
private final QuickPropFactory qpropFactory = new QuickPropFactory();
private final PSOFactory psoFactory = new PSOFactory();
/**
* {@inheritDoc}
*/
@Override
public final String getPluginDescription() {
return "This plugin provides the built in training " +
"methods for Encog.";
}
/**
* {@inheritDoc}
*/
@Override
public final String getPluginName() {
return "HRI-System-Training";
}
/**
* @return This is a type-1 plugin.
*/
@Override
public final int getPluginType() {
return 1;
}
/**
* This plugin does not support activation functions, so it will
* always return null.
* @return Null, because this plugin does not support activation functions.
*/
@Override
public ActivationFunction createActivationFunction(String name) {
return null;
}
@Override
public MLMethod createMethod(String methodType, String architecture,
int input, int output) {
// TODO Auto-generated method stub
return null;
}
@Override
public MLTrain createTraining(MLMethod method, MLDataSet training,
String type, String args) {
String args2 = args;
if (args2 == null) {
args2 = "";
}
if (MLTrainFactory.TYPE_RPROP.equalsIgnoreCase(type)) {
return this.rpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_BACKPROP.equalsIgnoreCase(type)) {
return this.backpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SCG.equalsIgnoreCase(type)) {
return this.scgFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_LMA.equalsIgnoreCase(type)) {
return this.lmaFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVM.equalsIgnoreCase(type)) {
return this.svmFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVM_SEARCH.equalsIgnoreCase(type)) {
return this.svmSearchFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SOM_NEIGHBORHOOD.equalsIgnoreCase(
type)) {
return this.neighborhoodFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_ANNEAL.equalsIgnoreCase(type)) {
return this.annealFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_GENETIC.equalsIgnoreCase(type)) {
return this.geneticFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SOM_CLUSTER.equalsIgnoreCase(type)) {
return this.somClusterFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_MANHATTAN.equalsIgnoreCase(type)) {
return this.manhattanFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_SVD.equalsIgnoreCase(type)) {
return this.svdFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_PNN.equalsIgnoreCase(type)) {
return this.pnnFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_QPROP.equalsIgnoreCase(type)) {
return this.qpropFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_BAYESIAN.equals(type) ) {
return this.bayesianFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_NELDER_MEAD.equals(type) ) {
return this.nmFactory.create(method, training, args2);
} else if (MLTrainFactory.TYPE_PSO.equals(type) ) {
return this.psoFactory.create(method, training, args2);
}
else {
throw new EncogError("Unknown training type: " + type);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getPluginServiceType() {
return EncogPluginBase.TYPE_SERVICE;
}
}
| larhoy/SentimentProjectV2 | SentimentAnalysisV2/encog-core-3.1.0/src/main/java/org/encog/plugin/system/SystemTrainingPlugin.java | Java | mit | 7,358 |
package controllers;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Date;
import models.Usuario;
import play.Play;
import play.mvc.*;
import play.data.validation.*;
import play.libs.*;
import play.utils.*;
public class Secure extends Controller {
@Before(unless={"login", "authenticate", "logout"})
static void checkAccess() throws Throwable {
// Authent
if(!session.contains("username")) {
flash.put("url", "GET".equals(request.method) ? request.url : Play.ctxPath + "/"); // seems a good default
login();
}
// Checks
Check check = getActionAnnotation(Check.class);
if(check != null) {
check(check);
}
check = getControllerInheritedAnnotation(Check.class);
if(check != null) {
check(check);
}
}
private static void check(Check check) throws Throwable {
for(String profile : check.value()) {
boolean hasProfile = (Boolean)Security.invoke("check", profile);
if(!hasProfile) {
Security.invoke("onCheckFailed", profile);
}
}
}
// ~~~ Login
public static void login() throws Throwable {
Http.Cookie remember = request.cookies.get("rememberme");
if(remember != null) {
int firstIndex = remember.value.indexOf("-");
int lastIndex = remember.value.lastIndexOf("-");
if (lastIndex > firstIndex) {
String sign = remember.value.substring(0, firstIndex);
String restOfCookie = remember.value.substring(firstIndex + 1);
String username = remember.value.substring(firstIndex + 1, lastIndex);
String time = remember.value.substring(lastIndex + 1);
Date expirationDate = new Date(Long.parseLong(time)); // surround with try/catch?
Date now = new Date();
if (expirationDate == null || expirationDate.before(now)) {
logout();
}
if(Crypto.sign(restOfCookie).equals(sign)) {
session.put("username", username);
redirectToOriginalURL();
}
}
}
flash.keep("url");
render();
}
public static void authenticate(@Required String username, String password, boolean remember) throws Throwable {
// Check tokens
//Boolean allowed = false;
Usuario usuario = Usuario.find("usuario = ? and clave = ?", username, password).first();
if(usuario != null){
//session.put("nombreCompleto", usuario.nombreCompleto);
//session.put("idUsuario", usuario.id);
//if(usuario.tienda != null){
//session.put("idTienda", usuario.id);
//}
//allowed = true;
} else {
flash.keep("url");
flash.error("secure.error");
params.flash();
login();
}
/*try {
// This is the deprecated method name
allowed = (Boolean)Security.invoke("authenticate", username, password);
} catch (UnsupportedOperationException e ) {
// This is the official method name
allowed = (Boolean)Security.invoke("authenticate", username, password);
}*/
/*if(validation.hasErrors() || !allowed) {
flash.keep("url");
flash.error("secure.error");
params.flash();
login();
}*/
// Mark user as connected
session.put("username", username);
// Remember if needed
if(remember) {
Date expiration = new Date();
String duration = "30d"; // maybe make this override-able
expiration.setTime(expiration.getTime() + Time.parseDuration(duration));
response.setCookie("rememberme", Crypto.sign(username + "-" + expiration.getTime()) + "-" + username + "-" + expiration.getTime(), duration);
}
// Redirect to the original URL (or /)
redirectToOriginalURL();
}
public static void logout() throws Throwable {
Security.invoke("onDisconnect");
session.clear();
response.removeCookie("rememberme");
Security.invoke("onDisconnected");
flash.success("secure.logout");
login();
}
// ~~~ Utils
static void redirectToOriginalURL() throws Throwable {
Security.invoke("onAuthenticated");
String url = flash.get("url");
if(url == null) {
url = Play.ctxPath + "/";
}
redirect(url);
}
public static class Security extends Controller {
/**
* @Deprecated
*
* @param username
* @param password
* @return
*/
static boolean authentify(String username, String password) {
throw new UnsupportedOperationException();
}
/**
* This method is called during the authentication process. This is where you check if
* the user is allowed to log in into the system. This is the actual authentication process
* against a third party system (most of the time a DB).
*
* @param username
* @param password
* @return true if the authentication process succeeded
*/
static boolean authenticate(String username, String password) {
return true;
}
/**
* This method checks that a profile is allowed to view this page/method. This method is called prior
* to the method's controller annotated with the @Check method.
*
* @param profile
* @return true if you are allowed to execute this controller method.
*/
static boolean check(String profile) {
return true;
}
/**
* This method returns the current connected username
* @return
*/
static String connected() {
return session.get("username");
}
/**
* Indicate if a user is currently connected
* @return true if the user is connected
*/
static boolean isConnected() {
return session.contains("username");
}
/**
* This method is called after a successful authentication.
* You need to override this method if you with to perform specific actions (eg. Record the time the user signed in)
*/
static void onAuthenticated() {
}
/**
* This method is called before a user tries to sign off.
* You need to override this method if you wish to perform specific actions (eg. Record the name of the user who signed off)
*/
static void onDisconnect() {
}
/**
* This method is called after a successful sign off.
* You need to override this method if you wish to perform specific actions (eg. Record the time the user signed off)
*/
static void onDisconnected() {
}
/**
* This method is called if a check does not succeed. By default it shows the not allowed page (the controller forbidden method).
* @param profile
*/
static void onCheckFailed(String profile) {
forbidden();
}
private static Object invoke(String m, Object... args) throws Throwable {
try {
return Java.invokeChildOrStatic(Security.class, m, args);
} catch(InvocationTargetException e) {
throw e.getTargetException();
}
}
}
}
| marti1125/Project_Store | app/controllers/Secure.java | Java | mit | 7,739 |
/**
*
*/
package org.edtoktay.dynamic.compiler;
/**
* @author deniz.toktay
*
*/
public interface ExampleInterface {
void addObject(String arg1, String arg2);
Object getObject(String arg1);
}
| edtoktay/DynamicCompiler | Example/src/main/java/org/edtoktay/dynamic/compiler/ExampleInterface.java | Java | mit | 200 |
package org.squirrel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.squirrel.managers.PrisonerControllor;
import org.squirrel.managers.inputManager;
import org.squirrel.objects.Player;
import org.squirrel.ui.Hud;
import org.squirrel.world.World;
public class Game extends JPanel implements ActionListener{
private static final long serialVersionUID = -8805039320208612585L;
public static String name = JOptionPane.showInputDialog(null,"What is your name?","Welcome to Prison Survival", JOptionPane.QUESTION_MESSAGE);
Timer gameLoop;
Player player;
PrisonerControllor prict;
Hud hud;
World world1;
public Game(){
setFocusable(true);
gameLoop = new Timer(10, this);
gameLoop.start();
player = new Player(300, 300);
prict = new PrisonerControllor();
hud = new Hud();
world1 = new World();
addKeyListener(new inputManager(player));
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
//Camera
int offsetMaxX = 1600 - 800;
int offsetMaxY = 1200 - 600;
int offsetMinX = 0;
int offsetMinY = 0;
int camX = player.getxPos() - 800 /2;
int camY = player.getyPos() - 600 /2;
//if (camX > offsetMaxX){
// camX = offsetMaxX;
//}
//else if (camX < offsetMinX){
// camX = offsetMinX;
//}
//if (camY > offsetMaxY){
// camY = offsetMaxY;
//}
//else if (camY < offsetMinY){
// camY = offsetMinY;
//}
g2d.translate(-camX, -camY);
// Render everything
world1.draw(g2d);
hud.draw(g2d);
prict.draw(g2d);
player.draw(g2d);
g.translate(camX, camY);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
player.update();
hud.update();
prict.update();
world1.update();
repaint();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
| DemSquirrel/Prison-Survival | src/org/squirrel/Game.java | Java | mit | 1,974 |
package com.xeiam.xchange.cryptotrade.dto;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.xeiam.xchange.cryptotrade.dto.CryptoTradeOrderType.CryptTradeOrderTypeDeserializer;
@JsonDeserialize(using = CryptTradeOrderTypeDeserializer.class)
public enum CryptoTradeOrderType {
Buy, Sell;
static class CryptTradeOrderTypeDeserializer extends JsonDeserializer<CryptoTradeOrderType> {
@Override
public CryptoTradeOrderType deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final ObjectCodec oc = jsonParser.getCodec();
final JsonNode node = oc.readTree(jsonParser);
final String orderType = node.asText();
return CryptoTradeOrderType.valueOf(orderType);
}
}
}
| Achterhoeker/XChange | xchange-cryptotrade/src/main/java/com/xeiam/xchange/cryptotrade/dto/CryptoTradeOrderType.java | Java | mit | 1,150 |
package com.github.aureliano.evtbridge.output.file;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Set;
import org.junit.Test;
import com.github.aureliano.evtbridge.annotation.validation.NotNull;
import com.github.aureliano.evtbridge.annotation.validation.apply.ConstraintViolation;
import com.github.aureliano.evtbridge.annotation.validation.apply.ObjectValidator;
import com.github.aureliano.evtbridge.core.config.OutputConfigTypes;
public class FileOutputConfigTest {
ObjectValidator validator = ObjectValidator.instance();
@Test
public void testGetDefaults() {
FileOutputConfig c = new FileOutputConfig();
assertNull(c.getFile());
assertEquals("UTF-8", c.getEncoding());
assertFalse(c.isAppend());
assertTrue(c.isUseBuffer());
}
@Test
public void testConfiguration() {
FileOutputConfig c = new FileOutputConfig()
.withAppend(true)
.withEncoding("ISO-8859-1")
.withFile("/there/is/not/file");
assertEquals("/there/is/not/file", c.getFile().getPath());
assertEquals("ISO-8859-1", c.getEncoding());
assertTrue(c.isAppend());
}
@Test
public void testClone() {
FileOutputConfig c1 = new FileOutputConfig()
.withAppend(true)
.withUseBuffer(false)
.withEncoding("ISO-8859-1")
.withFile("/there/is/not/file")
.putMetadata("test", "my test");
FileOutputConfig c2 = c1.clone();
assertEquals(c1.getFile(), c2.getFile());
assertEquals(c1.getEncoding(), c2.getEncoding());
assertEquals(c1.isAppend(), c2.isAppend());
assertEquals(c1.isUseBuffer(), c2.isUseBuffer());
assertEquals(c1.getMetadata("test"), c2.getMetadata("test"));
}
@Test
public void testOutputType() {
assertEquals(OutputConfigTypes.FILE_OUTPUT.name(), new FileOutputConfig().id());
}
@Test
public void testValidation() {
FileOutputConfig c = this.createValidConfiguration();
assertTrue(this.validator.validate(c).isEmpty());
this._testValidateFile();
}
private void _testValidateFile() {
FileOutputConfig c = new FileOutputConfig();
Set<ConstraintViolation> violations = this.validator.validate(c);
assertTrue(violations.size() == 1);
assertEquals(NotNull.class, violations.iterator().next().getValidator());
}
private FileOutputConfig createValidConfiguration() {
return new FileOutputConfig().withFile("/path/to/file");
}
} | aureliano/da-mihi-logs | evt-bridge-output/file-output/src/test/java/com/github/aureliano/evtbridge/output/file/FileOutputConfigTest.java | Java | mit | 2,450 |
// THIS CODE IS MACHINE-GENERATED, DO NOT EDIT!
package fallk.jfunktion;
/**
* Represents a predicate (boolean-valued function) of a {@code float}-valued and a generic argument.
* This is the primitive type specialization of
* {@link java.util.function.BiPredicate} for {@code float}/{@code char}.
*
* @see java.util.function.BiPredicate
*/
@FunctionalInterface
public interface FloatObjectPredicate<E> {
/**
* Evaluates this predicate on the given arguments.
*
* @param v1 the {@code float} argument
* @param v2 the generic argument
* @return {@code true} if the input arguments match the predicate,
* otherwise {@code false}
*/
boolean apply(float v1, E v2);
}
| fallk/JFunktion | src/main/java/fallk/jfunktion/FloatObjectPredicate.java | Java | mit | 715 |
package com.carbon108.tilde;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author K Moroz
* @version 1.0
*/
public class PrimaryModelFactoryTest {
private PrimaryModelFactory factory;
@Before
public void setUp() {
factory = new PrimaryModelFactory();
}
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void getIDsGetsAllValidModelIDs() {
Collection<String> factoryIDs = factory.getIDs();
assertEquals(2, factoryIDs.size());
assertEquals(true, factoryIDs.contains(ModelID.LINEAR));
assertEquals(true, factoryIDs.contains(ModelID.CONSTANT));
// check immutability
exception.expect(UnsupportedOperationException.class);
factoryIDs.add("someString");
}
@Test
public void makeValidModelIDGetsModel() {
TildeModel model1 = factory.make(ModelID.LINEAR);
TildeModel model2 = factory.make(ModelID.CONSTANT);
assertEquals(ModelID.LINEAR, model1.getID());
assertEquals(ModelID.CONSTANT, model2.getID());
}
@Test
public void makeInvalidIDGetsNullModel() {
TildeModel m1null = factory.make(null);
TildeModel m1blank = factory.make("");
TildeModel m2invalid = factory.make("invalidModelID");
assertTrue(m1null.isNullModel());
assertTrue(m1blank.isNullModel());
assertTrue(m2invalid.isNullModel());
}
@Test
public void makeAll() {
Collection<TildeModel> models = factory.makeAll();
assertEquals(2, models.size());
assertEquals(true, models.contains(new LinearModel()));
assertEquals(true, models.contains(new ConstantModel()));
}
}
| morozko108/Tilde | src/test/java/com/carbon108/tilde/PrimaryModelFactoryTest.java | Java | mit | 1,725 |
/**
* @copyright Copyright (C) DocuSign, Inc. All rights reserved.
*
* This source code is intended only as a supplement to DocuSign SDK
* and/or on-line documentation.
*
* This sample is designed to demonstrate DocuSign features and is not intended
* for production use. Code and policy for a production application must be
* developed to meet the specific data and security requirements of the
* application.
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*/
package net.docusign.sample;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import net.docusign.api_3_0.APIServiceSoap;
import net.docusign.api_3_0.ArrayOfString2;
import net.docusign.api_3_0.EnvelopePDF;
import net.docusign.api_3_0.EnvelopeStatusFilter;
import net.docusign.api_3_0.FilteredEnvelopeStatuses;
import net.docusign.api_3_0.RequestRecipientTokenAuthenticationAssertion;
import net.docusign.api_3_0.RequestRecipientTokenAuthenticationAssertionAuthenticationMethod;
import net.docusign.api_3_0.RequestRecipientTokenClientURLs;
/**
* Servlet implementation class GetStatusAndDocs
*/
public class GetStatusAndDocs extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetStatusAndDocs() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute(Utils.SESSION_EMBEDTOKEN, "");
HttpSession session = request.getSession();
// Make sure we're logged in
if (session.getAttribute(Utils.SESSION_LOGGEDIN) == null ||
session.getAttribute(Utils.SESSION_LOGGEDIN).equals(false)) {
response.sendRedirect(Utils.CONTROLLER_LOGIN);
}
else {
// Do we have envelope IDs in this session?
if (session.getAttribute(Utils.SESSION_ENVELOPEIDS) != null) {
APIServiceSoap api = Utils.getAPI(request);
// Grab all the envelope IDs in this session
ArrayOfString2 envIDs = new ArrayOfString2();
envIDs.getEnvelopeId().addAll((List<String>) session.getAttribute(Utils.SESSION_ENVELOPEIDS));
// Create a filter so we only retrieve these envelope statuses
EnvelopeStatusFilter filter = new EnvelopeStatusFilter();
filter.setAccountId(session.getAttribute(Utils.SESSION_ACCOUNT_ID).toString());
filter.setEnvelopeIds(envIDs);
try {
// Call requestStatusesEx on these envelopes
FilteredEnvelopeStatuses statuses = api.requestStatusesEx(filter);
session.setAttribute(Utils.SESSION_STATUSES,
statuses.getEnvelopeStatuses().getEnvelopeStatus());
} catch (Exception e) {
}
}
response.sendRedirect(Utils.PAGE_GETSTATUS);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the parameter names
Enumeration paramNames = request.getParameterNames();
// Loop through the parameter names
while (paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
if (paramName.startsWith(Utils.NAME_STARTSIGNING)) {
// We want to start this user signing
startSigning(paramName, request);
response.sendRedirect(Utils.PAGE_GETSTATUS);
} else if (paramName.startsWith(Utils.NAME_DOWNLOAD)) {
// We want to download the specified envelope
downloadEnvelope(paramName, request, response);
}
}
}
protected void downloadEnvelope(String param, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String eid = param.split("\\+")[1];
// Request the PDF of the envelope
APIServiceSoap api = Utils.getAPI(request);
EnvelopePDF pdf = api.requestPDF(eid);
// Start download of the resulting PDF
byte[] documentBytes = pdf.getPDFBytes();
response.setHeader("Content-Disposition", "attachment;filename=Envelope.pdf");
response.setContentLength(documentBytes.length);
response.setContentType("application/pdf");
response.getOutputStream().write(documentBytes);
return;
}
protected void startSigning(String param, HttpServletRequest request) throws ServletException, IOException {
// Parse out envelope id, email, username, client user id
String[] params = param.split("\\&");
String eid = "", cid = "", uname = "", email = "";
for (int i = 0; i < params.length; i++) {
String[] pair = params[i].split("\\+");
if(pair[0].equals("SignDocEnvelope")) {
eid = pair[1];
} else if (pair[0].equals("Email")) {
email = pair[1];
} else if (pair[0].equals("UserName")) {
uname = pair[1];
} else if (pair[0].equals("CID")) {
cid = pair[1];
}
}
// Request the token
try {
getToken(request, eid, email, uname, cid);
} catch (DatatypeConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void getToken(HttpServletRequest request, String eid, String email, String username, String CID) throws DatatypeConfigurationException {
String token = null;
// Create the assertion
RequestRecipientTokenAuthenticationAssertion assertion = new RequestRecipientTokenAuthenticationAssertion();
assertion.setAssertionID(UUID.randomUUID().toString());
// wsdl2java translates this to XMLGregorianCalendar
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(new Date());
assertion.setAuthenticationInstant(DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal));
assertion.setAuthenticationMethod(RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.PASSWORD);
assertion.setSecurityDomain("DocuSign2010Q1Sample");
// Create the URLs that DocuSign will redirect the iframe to after different events
RequestRecipientTokenClientURLs urls = new RequestRecipientTokenClientURLs();
String urlbase = Utils.getCallbackURL(request, Utils.PAGE_POP);
urls.setOnAccessCodeFailed(urlbase + "?event=AccessCodeFailed&uname=" + username);
urls.setOnCancel(urlbase + "?event=Cancel&uname=" + username);
urls.setOnDecline(urlbase + "?event=Decline&uname=" + username);
urls.setOnException(urlbase + "?event=Exception&uname=" + username);
urls.setOnFaxPending(urlbase + "?event=FaxPending&uname=" + username);
urls.setOnIdCheckFailed(urlbase + "?event=IdCheckFailed&uname=" + username);
urls.setOnSessionTimeout(urlbase + "?event=SessionTimeout&uname=" + username);
urls.setOnTTLExpired(urlbase + "?event=TTLExpired&uname=" + username);
urls.setOnViewingComplete(urlbase + "?event=ViewingComplete&uname=" + username);
urls.setOnSigningComplete(urlbase + "?event=SigningComplete&uname=" + username);
// Get the API service and call RequestRecipientToken for this recipient
APIServiceSoap api = Utils.getAPI(request);
token = api.requestRecipientToken(eid,
CID,
username,
email,
assertion,
urls);
// Set the iframe to the token
request.getSession().setAttribute(Utils.SESSION_EMBEDTOKEN, token);
}
}
| docusign/docusign-soap-sdk | Java/DocuSignSample/src/net/docusign/sample/GetStatusAndDocs.java | Java | mit | 8,102 |
package com.pablodomingos.classes.rps.servicos;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import com.pablodomingos.classes.FabricaDeObjetosFake;
public class LoteRpsConsultaTest {
@Test
public void xmlDeveSerGeradoCorretamente() throws IOException{
String xmlTest = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("loteRPSConsulta.xml"));
LoteRpsConsulta consultaLote = new LoteRpsConsulta("AP1057893n16X103sfhF4RPm", FabricaDeObjetosFake.getRpsPrestador());
String xml = consultaLote.converterParaXml();
Assert.assertEquals(xml, xmlTest);
}
}
| pablopdomingos/nfse | nfse-bh/src/test/java/com/pablodomingos/classes/rps/servicos/LoteRpsConsultaTest.java | Java | mit | 696 |
/**
* Copyright 2017, 2018, 2019, 2020 Stephen Powis https://github.com/Crim/pardot-java-client
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.darksci.pardot.api.parser.user;
import com.darksci.pardot.api.parser.JacksonFactory;
import com.darksci.pardot.api.parser.ResponseParser;
import com.darksci.pardot.api.response.user.UserAbilitiesResponse;
import java.io.IOException;
/**
* Handles parsing UserAbilities API responses into POJOs.
*/
public class UserAbilitiesParser implements ResponseParser<UserAbilitiesResponse.Result> {
@Override
public UserAbilitiesResponse.Result parseResponse(final String responseStr) throws IOException {
return JacksonFactory.newInstance().readValue(responseStr, UserAbilitiesResponse.class).getResult();
}
}
| Crim/pardot-java-client | src/main/java/com/darksci/pardot/api/parser/user/UserAbilitiesParser.java | Java | mit | 1,801 |
package data_struct.in_class.d10_02;
/**
* A class to test basic 'Object' methods
*
* @author Eddie Gurnee
* @version 10/02/13
* @see TestingSam
*
*/
public class Sam {
public int mikesplan = 8;
/**
* No argument constructor for the Sam class
*
*/
public Sam() {
}
/**
* Indicates if some other "Sam" object is equal to this one.
*
*/
public boolean equals(Sam otherObject) {
if (otherObject == null) {
System.out.println("check1");
return false;
}
else if (this.getClass() != otherObject.getClass()) {
System.out.println("check2");
return false;
}
else {
System.out.println("if this shows then fuck the police");
Sam otherSam = (Sam)otherObject;
return this.mikesplan == otherSam.mikesplan;
}
}
public int getMikesPlan() {
return mikesplan;
}
} | pegurnee/2013-03-211 | complete/src/data_struct/in_class/d10_02/Sam.java | Java | mit | 817 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.test.annotations.cascade;
import java.util.HashSet;
import org.junit.Test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.fail;
/**
* @author Jeff Schnitzer
* @author Gail Badner
*/
@SuppressWarnings("unchecked")
public class NonNullableCircularDependencyCascadeTest extends BaseCoreFunctionalTestCase {
@Test
public void testIdClassInSuperclass() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Parent p = new Parent();
p.setChildren( new HashSet<Child>() );
Child ch = new Child(p);
p.getChildren().add(ch);
p.setDefaultChild(ch);
try {
s.persist(p);
s.flush();
fail( "should have failed because of transient entities have non-nullable, circular dependency." );
}
catch ( HibernateException ex) {
// expected
}
tx.rollback();
s.close();
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[]{
Child.class,
Parent.class
};
}
}
| HerrB92/obp | OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/test/annotations/cascade/NonNullableCircularDependencyCascadeTest.java | Java | mit | 2,167 |
package softuni.io;
import org.springframework.stereotype.Component;
import java.io.*;
@Component
public class FileParser {
public String readFile(String path) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream is = this.getClass().getResourceAsStream(path);
BufferedReader bfr = new BufferedReader(new InputStreamReader(is))) {
String line = bfr.readLine();
while (line != null) {
stringBuilder.append(line);
line = bfr.readLine();
}
}
return stringBuilder.toString();
}
public void writeFile(String path, String content) throws IOException {
File file = new File(System.getProperty("user.dir") + File.separator + path);
if (!file.exists()) {
file.createNewFile();
}
try (OutputStream os = new FileOutputStream(System.getProperty("user.dir")+ File.separator + path);
BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(os))) {
bfw.write(content);
}
}
}
| yangra/SoftUni | Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/EXAMS/exam/src/main/java/softuni/io/FileParser.java | Java | mit | 1,123 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.comci.bigbib;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bson.types.ObjectId;
import org.codehaus.jackson.annotate.JsonProperty;
import org.jbibtex.BibTeXEntry;
import org.jbibtex.Key;
import org.jbibtex.StringValue;
import org.jbibtex.Value;
/**
*
* @author Sebastian
*/
@XmlRootElement()
@XmlAccessorType(XmlAccessType.NONE)
public class PeristentBibTexEntry extends BibTeXEntry {
private ObjectId id;
public PeristentBibTexEntry(Key type, Key key) {
super(type, key);
}
static Map<String, Key> keyMapping = new HashMap<String, Key>();
static {
keyMapping.put("address", BibTeXEntry.KEY_ADDRESS);
keyMapping.put("annote", BibTeXEntry.KEY_ANNOTE);
keyMapping.put("author", BibTeXEntry.KEY_AUTHOR);
keyMapping.put("booktitle", BibTeXEntry.KEY_BOOKTITLE);
keyMapping.put("chapter", BibTeXEntry.KEY_CHAPTER);
keyMapping.put("crossref", BibTeXEntry.KEY_CROSSREF);
keyMapping.put("doi", BibTeXEntry.KEY_DOI);
keyMapping.put("edition", BibTeXEntry.KEY_EDITION);
keyMapping.put("editor", BibTeXEntry.KEY_EDITOR);
keyMapping.put("eprint", BibTeXEntry.KEY_EPRINT);
keyMapping.put("howpublished", BibTeXEntry.KEY_HOWPUBLISHED);
keyMapping.put("institution", BibTeXEntry.KEY_INSTITUTION);
keyMapping.put("journal", BibTeXEntry.KEY_JOURNAL);
keyMapping.put("key", BibTeXEntry.KEY_KEY);
keyMapping.put("month", BibTeXEntry.KEY_MONTH);
keyMapping.put("note", BibTeXEntry.KEY_NOTE);
keyMapping.put("number", BibTeXEntry.KEY_NUMBER);
keyMapping.put("organization", BibTeXEntry.KEY_ORGANIZATION);
keyMapping.put("pages", BibTeXEntry.KEY_PAGES);
keyMapping.put("publisher", BibTeXEntry.KEY_PUBLISHER);
keyMapping.put("school", BibTeXEntry.KEY_SCHOOL);
keyMapping.put("series", BibTeXEntry.KEY_SERIES);
keyMapping.put("title", BibTeXEntry.KEY_TITLE);
keyMapping.put("type", BibTeXEntry.KEY_TYPE);
keyMapping.put("url", BibTeXEntry.KEY_URL);
keyMapping.put("volume", BibTeXEntry.KEY_VOLUME);
keyMapping.put("year", BibTeXEntry.KEY_YEAR);
}
public PeristentBibTexEntry(DBObject persistentObject) {
super(
new Key((String) persistentObject.get("type")),
new Key((String) persistentObject.get("key"))
);
BasicDBObject fields = (BasicDBObject) persistentObject.get("fields");
id = (ObjectId) persistentObject.get("_id");
for (String key : fields.keySet()) {
if (keyMapping.containsKey(key)) {
this.addField(keyMapping.get(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
} else {
this.addField(new Key(key), new StringValue(fields.getString(key), StringValue.Style.BRACED));
}
}
}
@JsonProperty("id")
@XmlElement(name="id")
public String getStringId() {
return id.toString();
}
@JsonProperty("key")
@XmlElement(name="key")
public String getStringKey() {
return super.getKey().getValue();
}
@JsonProperty("type")
@XmlElement(name="type")
public String getStringType() {
return super.getType().getValue();
}
@JsonProperty("fields")
@XmlElement(name="fields")
public Map<String, String> getStringFields() {
Map<String, String> fields = new HashMap<String, String>();
for (Entry<Key,Value> e : getFields().entrySet()) {
if (e.getKey() != null && e.getValue() != null) {
fields.put(e.getKey().getValue(), e.getValue().toUserString());
}
}
return fields;
}
@Override
public String toString() {
return String.format("[%s:%s] %s: %s (%s)",
this.getType(),
this.getKey(),
this.getField(KEY_AUTHOR).toUserString(),
this.getField(KEY_TITLE).toUserString(),
this.getField(KEY_YEAR).toUserString());
}
}
| maiers/bigbib | src/main/java/de/comci/bigbib/PeristentBibTexEntry.java | Java | mit | 4,524 |
/*
* This file was autogenerated by the GPUdb schema processor.
*
* DO NOT EDIT DIRECTLY.
*/
package com.gpudb.protocol;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.IndexedRecord;
/**
* A set of parameters for {@link
* com.gpudb.GPUdb#filterByValue(FilterByValueRequest)}.
* <p>
* Calculates which objects from a table has a particular value for a
* particular column. The input parameters provide a way to specify either a
* String
* or a Double valued column and a desired value for the column on which the
* filter
* is performed. The operation is synchronous, meaning that a response will not
* be
* returned until all the objects are fully available. The response payload
* provides the count of the resulting set. A new result view which satisfies
* the
* input filter restriction specification is also created with a view name
* passed
* in as part of the input payload. Although this functionality can also be
* accomplished with the standard filter function, it is more efficient.
*/
public class FilterByValueRequest implements IndexedRecord {
private static final Schema schema$ = SchemaBuilder
.record("FilterByValueRequest")
.namespace("com.gpudb")
.fields()
.name("tableName").type().stringType().noDefault()
.name("viewName").type().stringType().noDefault()
.name("isString").type().booleanType().noDefault()
.name("value").type().doubleType().noDefault()
.name("valueStr").type().stringType().noDefault()
.name("columnName").type().stringType().noDefault()
.name("options").type().map().values().stringType().noDefault()
.endRecord();
/**
* This method supports the Avro framework and is not intended to be called
* directly by the user.
*
* @return the schema for the class.
*
*/
public static Schema getClassSchema() {
return schema$;
}
/**
* Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.FilterByValueRequest.Options#COLLECTION_NAME
* COLLECTION_NAME}: [DEPRECATED--please specify the containing schema for
* the view as part of {@code viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to create the schema
* if non-existent] Name of a schema for the newly created view. If the
* schema is non-existent, it will be automatically created.
* </ul>
* The default value is an empty {@link Map}.
* A set of string constants for the parameter {@code options}.
*/
public static final class Options {
/**
* [DEPRECATED--please specify the containing schema for the view as
* part of {@code viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to create the
* schema if non-existent] Name of a schema for the newly created
* view. If the schema is non-existent, it will be automatically
* created.
*/
public static final String COLLECTION_NAME = "collection_name";
private Options() { }
}
private String tableName;
private String viewName;
private boolean isString;
private double value;
private String valueStr;
private String columnName;
private Map<String, String> options;
/**
* Constructs a FilterByValueRequest object with default parameters.
*/
public FilterByValueRequest() {
tableName = "";
viewName = "";
valueStr = "";
columnName = "";
options = new LinkedHashMap<>();
}
/**
* Constructs a FilterByValueRequest object with the specified parameters.
*
* @param tableName Name of an existing table on which to perform the
* calculation, in [schema_name.]table_name format, using
* standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a>.
* @param viewName If provided, then this will be the name of the view
* containing the results, in [schema_name.]view_name
* format, using standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#table-naming-criteria"
* target="_top">table naming criteria</a>. Must not be
* an already existing table or view. The default value
* is ''.
* @param isString Indicates whether the value being searched for is
* string or numeric.
* @param value The value to search for. The default value is 0.
* @param valueStr The string value to search for. The default value is
* ''.
* @param columnName Name of a column on which the filter by value would
* be applied.
* @param options Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.FilterByValueRequest.Options#COLLECTION_NAME
* COLLECTION_NAME}: [DEPRECATED--please specify the
* containing schema for the view as part of {@code
* viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to
* create the schema if non-existent] Name of a schema for
* the newly created view. If the schema is non-existent,
* it will be automatically created.
* </ul>
* The default value is an empty {@link Map}.
*
*/
public FilterByValueRequest(String tableName, String viewName, boolean isString, double value, String valueStr, String columnName, Map<String, String> options) {
this.tableName = (tableName == null) ? "" : tableName;
this.viewName = (viewName == null) ? "" : viewName;
this.isString = isString;
this.value = value;
this.valueStr = (valueStr == null) ? "" : valueStr;
this.columnName = (columnName == null) ? "" : columnName;
this.options = (options == null) ? new LinkedHashMap<String, String>() : options;
}
/**
*
* @return Name of an existing table on which to perform the calculation,
* in [schema_name.]table_name format, using standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a>.
*
*/
public String getTableName() {
return tableName;
}
/**
*
* @param tableName Name of an existing table on which to perform the
* calculation, in [schema_name.]table_name format, using
* standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a>.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setTableName(String tableName) {
this.tableName = (tableName == null) ? "" : tableName;
return this;
}
/**
*
* @return If provided, then this will be the name of the view containing
* the results, in [schema_name.]view_name format, using standard
* <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#table-naming-criteria"
* target="_top">table naming criteria</a>. Must not be an already
* existing table or view. The default value is ''.
*
*/
public String getViewName() {
return viewName;
}
/**
*
* @param viewName If provided, then this will be the name of the view
* containing the results, in [schema_name.]view_name
* format, using standard <a
* href="../../../../../../concepts/tables/#table-name-resolution"
* target="_top">name resolution rules</a> and meeting <a
* href="../../../../../../concepts/tables/#table-naming-criteria"
* target="_top">table naming criteria</a>. Must not be
* an already existing table or view. The default value
* is ''.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setViewName(String viewName) {
this.viewName = (viewName == null) ? "" : viewName;
return this;
}
/**
*
* @return Indicates whether the value being searched for is string or
* numeric.
*
*/
public boolean getIsString() {
return isString;
}
/**
*
* @param isString Indicates whether the value being searched for is
* string or numeric.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setIsString(boolean isString) {
this.isString = isString;
return this;
}
/**
*
* @return The value to search for. The default value is 0.
*
*/
public double getValue() {
return value;
}
/**
*
* @param value The value to search for. The default value is 0.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setValue(double value) {
this.value = value;
return this;
}
/**
*
* @return The string value to search for. The default value is ''.
*
*/
public String getValueStr() {
return valueStr;
}
/**
*
* @param valueStr The string value to search for. The default value is
* ''.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setValueStr(String valueStr) {
this.valueStr = (valueStr == null) ? "" : valueStr;
return this;
}
/**
*
* @return Name of a column on which the filter by value would be applied.
*
*/
public String getColumnName() {
return columnName;
}
/**
*
* @param columnName Name of a column on which the filter by value would
* be applied.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setColumnName(String columnName) {
this.columnName = (columnName == null) ? "" : columnName;
return this;
}
/**
*
* @return Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.FilterByValueRequest.Options#COLLECTION_NAME
* COLLECTION_NAME}: [DEPRECATED--please specify the containing
* schema for the view as part of {@code viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to create the
* schema if non-existent] Name of a schema for the newly created
* view. If the schema is non-existent, it will be automatically
* created.
* </ul>
* The default value is an empty {@link Map}.
*
*/
public Map<String, String> getOptions() {
return options;
}
/**
*
* @param options Optional parameters.
* <ul>
* <li> {@link
* com.gpudb.protocol.FilterByValueRequest.Options#COLLECTION_NAME
* COLLECTION_NAME}: [DEPRECATED--please specify the
* containing schema for the view as part of {@code
* viewName} and use {@link
* com.gpudb.GPUdb#createSchema(CreateSchemaRequest)} to
* create the schema if non-existent] Name of a schema for
* the newly created view. If the schema is non-existent,
* it will be automatically created.
* </ul>
* The default value is an empty {@link Map}.
*
* @return {@code this} to mimic the builder pattern.
*
*/
public FilterByValueRequest setOptions(Map<String, String> options) {
this.options = (options == null) ? new LinkedHashMap<String, String>() : options;
return this;
}
/**
* This method supports the Avro framework and is not intended to be called
* directly by the user.
*
* @return the schema object describing this class.
*
*/
@Override
public Schema getSchema() {
return schema$;
}
/**
* This method supports the Avro framework and is not intended to be called
* directly by the user.
*
* @param index the position of the field to get
*
* @return value of the field with the given index.
*
* @throws IndexOutOfBoundsException
*
*/
@Override
public Object get(int index) {
switch (index) {
case 0:
return this.tableName;
case 1:
return this.viewName;
case 2:
return this.isString;
case 3:
return this.value;
case 4:
return this.valueStr;
case 5:
return this.columnName;
case 6:
return this.options;
default:
throw new IndexOutOfBoundsException("Invalid index specified.");
}
}
/**
* This method supports the Avro framework and is not intended to be called
* directly by the user.
*
* @param index the position of the field to set
* @param value the value to set
*
* @throws IndexOutOfBoundsException
*
*/
@Override
@SuppressWarnings("unchecked")
public void put(int index, Object value) {
switch (index) {
case 0:
this.tableName = (String)value;
break;
case 1:
this.viewName = (String)value;
break;
case 2:
this.isString = (Boolean)value;
break;
case 3:
this.value = (Double)value;
break;
case 4:
this.valueStr = (String)value;
break;
case 5:
this.columnName = (String)value;
break;
case 6:
this.options = (Map<String, String>)value;
break;
default:
throw new IndexOutOfBoundsException("Invalid index specified.");
}
}
@Override
public boolean equals(Object obj) {
if( obj == this ) {
return true;
}
if( (obj == null) || (obj.getClass() != this.getClass()) ) {
return false;
}
FilterByValueRequest that = (FilterByValueRequest)obj;
return ( this.tableName.equals( that.tableName )
&& this.viewName.equals( that.viewName )
&& ( this.isString == that.isString )
&& ( (Double)this.value ).equals( (Double)that.value )
&& this.valueStr.equals( that.valueStr )
&& this.columnName.equals( that.columnName )
&& this.options.equals( that.options ) );
}
@Override
public String toString() {
GenericData gd = GenericData.get();
StringBuilder builder = new StringBuilder();
builder.append( "{" );
builder.append( gd.toString( "tableName" ) );
builder.append( ": " );
builder.append( gd.toString( this.tableName ) );
builder.append( ", " );
builder.append( gd.toString( "viewName" ) );
builder.append( ": " );
builder.append( gd.toString( this.viewName ) );
builder.append( ", " );
builder.append( gd.toString( "isString" ) );
builder.append( ": " );
builder.append( gd.toString( this.isString ) );
builder.append( ", " );
builder.append( gd.toString( "value" ) );
builder.append( ": " );
builder.append( gd.toString( this.value ) );
builder.append( ", " );
builder.append( gd.toString( "valueStr" ) );
builder.append( ": " );
builder.append( gd.toString( this.valueStr ) );
builder.append( ", " );
builder.append( gd.toString( "columnName" ) );
builder.append( ": " );
builder.append( gd.toString( this.columnName ) );
builder.append( ", " );
builder.append( gd.toString( "options" ) );
builder.append( ": " );
builder.append( gd.toString( this.options ) );
builder.append( "}" );
return builder.toString();
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = (31 * hashCode) + this.tableName.hashCode();
hashCode = (31 * hashCode) + this.viewName.hashCode();
hashCode = (31 * hashCode) + ((Boolean)this.isString).hashCode();
hashCode = (31 * hashCode) + ((Double)this.value).hashCode();
hashCode = (31 * hashCode) + this.valueStr.hashCode();
hashCode = (31 * hashCode) + this.columnName.hashCode();
hashCode = (31 * hashCode) + this.options.hashCode();
return hashCode;
}
}
| GPUdb/gpudb-api-java | api/src/main/java/com/gpudb/protocol/FilterByValueRequest.java | Java | mit | 18,189 |
/*
* Copyright 2017 Max Schafer, Ammar Mahdi, Riley Dixon, Steven Weikai Lu, Jiaxiong Yang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.example.lit.habit;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Base64;
import android.util.Log;
import com.example.lit.exception.BitmapTooLargeException;
import com.example.lit.exception.HabitFormatException;
import com.example.lit.saving.Saveable;
import com.example.lit.exception.HabitFormatException;
import io.searchbox.annotations.JestId;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* This class is an abstract habit class
* @author Steven Weikai Lu
*/
public abstract class Habit implements Habitable , Parcelable, Saveable {
private String title;
private SimpleDateFormat format;
private Date date;
public abstract String habitType();
private String user;
private String reason;
private int titleLength = 20;
private int reasonLength = 30;
private List<Calendar> calendars;
private List<Date> dates;
private String encodedImage;
@JestId
private String id;
private Bitmap image;
public String getID(){ return id ;}
public void setID(String id){ this.id = id ;}
public Habit(String title) throws HabitFormatException {
this.setTitle(title);
this.setDate(new Date());
}
public Habit(String title, Date date) throws HabitFormatException{
this.setTitle(title);
this.setDate(date);
}
public Habit(String title, Date date, String reason) throws HabitFormatException {
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
}
/**
* This is the main constructor we are using in AddHabitActivity
*
* @see com.example.lit.activity.AddHabitActivity
* @param title Habit name, should be at most 20 char long.
* @param reason Habit Comment, should be at most 30 char long.
* @param date Set by GPS when creating the habit
* @param calendarList Set by user when creating the habit
* @throws HabitFormatException thrown when title longer than 20 char or reason longer than 30 char
* */
public Habit(String title, Date date, String reason, List<Calendar> calendarList) throws HabitFormatException {
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
this.setCalendars(calendarList);
}
public Habit(String title, Date date, String reason, List<Calendar> calendars, Bitmap image)throws HabitFormatException, BitmapTooLargeException{
this.setTitle(title);
this.setDate(date);
this.setReason(reason);
this.setCalendars(calendars);
this.setImage(image);
}
// TODO: Constructor with JestID
public String getTitle() {
return title;
}
public void setTitle(String title) throws HabitFormatException {
if (title.length() > this.titleLength){
throw new HabitFormatException();
}
this.title = title;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Date getDate() {
return date;
}
/**
* Function takes in a Date object and formats it to dd-MM-yyyy
* @param date
*/
public void setDate(Date date) {
// Format the current time.
SimpleDateFormat format = new SimpleDateFormat ("dd-MM-yyyy");
String dateString = format.format(date);
// Parse the previous string back into a Date.
ParsePosition pos = new ParsePosition(0);
this.date = format.parse(dateString, pos);
}
public String getReason() {
return reason;
}
public void setReason(String reason) throws HabitFormatException {
if (reason.length() < this.reasonLength) {
this.reason = reason;
}
else {
throw new HabitFormatException();
}
}
public List<Calendar> getCalendars() {
return calendars;
}
public void setCalendars(List<Calendar> calendars) {
this.calendars = calendars;
}
public Bitmap getImage() {
if(encodedImage != null) {
byte[] decodedString = Base64.decode(this.encodedImage, Base64.DEFAULT);
this.image = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
return this.image;
}
/**
* Function takes in a Bitmap object and decodes it to a 64Base string
* @param image
* @throws BitmapTooLargeException
*/
public void setImage(Bitmap image) throws BitmapTooLargeException {
if (image == null){
this.image = null;
}
else if (image.getByteCount() > 65536){
throw new BitmapTooLargeException();
}
else {
this.image = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArray = baos.toByteArray();
this.encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
//Log.i("encoded",this.encodedImage);
}
}
@Override
public String toString() {
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
return "Habit Name: " + this.getTitle() + '\n' +
"Started From: " + format.format(this.getDate());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeSerializable(this.format);
dest.writeLong(this.date != null ? this.date.getTime() : -1);
dest.writeString(this.user);
dest.writeString(this.reason);
dest.writeInt(this.titleLength);
dest.writeInt(this.reasonLength);
dest.writeList(this.calendars);
dest.writeList(this.dates);
dest.writeString(this.encodedImage);
dest.writeString(this.id);
dest.writeParcelable(this.image, flags);
}
protected Habit(Parcel in) {
this.title = in.readString();
this.format = (SimpleDateFormat) in.readSerializable();
long tmpDate = in.readLong();
this.date = tmpDate == -1 ? null : new Date(tmpDate);
this.user = in.readString();
this.reason = in.readString();
this.titleLength = in.readInt();
this.reasonLength = in.readInt();
this.calendars = new ArrayList<Calendar>();
in.readList(this.calendars, Calendar.class.getClassLoader());
this.dates = new ArrayList<Date>();
in.readList(this.dates, Date.class.getClassLoader());
this.encodedImage = in.readString();
this.id = in.readString();
this.image = in.readParcelable(Bitmap.class.getClassLoader());
}
}
| CMPUT301F17T06/Lit | app/src/main/java/com/example/lit/habit/Habit.java | Java | mit | 8,243 |
package org.vitrivr.cineast.core.util.audio.pitch.tracking;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.vitrivr.cineast.core.util.audio.pitch.Pitch;
/**
* This is a helper class for pitch tracking. It represents a pitch contour, that is, a candidate for a melody fragment. The contour has a fixed length and each slot in the sequence represents a specific timeframe (e.g. belonging to a FFT bin in the underlying STFT).
* <p>
* The intention behind this class is the simplification of comparison between different pitch contours, either on a frame-by-frame basis but also as an entity. In addition to the actual pitch information, the pitch contour class also provides access to pitch contour statistics related to salience and pitch frequency.
*
* @see PitchTracker
*/
public class PitchContour {
/**
* The minimum frequency in Hz on the (artifical) cent-scale.
*/
private static final float CENT_SCALE_MINIMUM = 55.0f;
/**
* Entity that keeps track of salience related contour statistics.
*/
private SummaryStatistics salienceStatistics = new SummaryStatistics();
/**
* Entity that keeps track of frequency related contour statistics.
*/
private SummaryStatistics frequencyStatistics = new SummaryStatistics();
/**
* Sequence of pitches that form the PitchContour.
*/
private final List<Pitch> contour = new LinkedList<>();
/**
* Indicates that the PitchContour statistics require recalculation.
*/
private boolean dirty = true;
/**
* The start frame-index of the pitch-contour. Marks beginning in time.
*/
private int start;
/**
* The end frame-index of the pitch-contour. Marks ending in time.
*/
private int end;
/**
* Constructor for PitchContour.
*
* @param start Start-index of the contour.
* @param pitch Pitch that belongs to the start-index.
*/
public PitchContour(int start, Pitch pitch) {
this.start = start;
this.end = start;
this.contour.add(pitch);
}
/**
* Sets the pitch at the given index if the index is within the bounds of the PitchContour.
*
* @param p Pitch to append.
*/
public void append(Pitch p) {
this.contour.add(p);
this.end += 1;
this.dirty = true;
}
/**
* Sets the pitch at the given index if the index is within the bounds of the PitchContour.
*
* @param p Pitch to append.
*/
public void prepend(Pitch p) {
this.contour.add(0, p);
this.start -= 1;
this.dirty = true;
}
/**
* Returns the pitch at the given index or null, if the index is out of bounds. Note that even if the index is within bounds, the Pitch can still be null.
*
* @param i Index for which to return a pitch.
*/
public Pitch getPitch(int i) {
if (i >= this.start && i <= this.end) {
return this.contour.get(i - this.start);
} else {
return null;
}
}
/**
* Getter for start.
*
* @return Start frame-index.
*/
public final int getStart() {
return start;
}
/**
* Getter for end.
*
* @return End frame-index.
*/
public final int getEnd() {
return end;
}
/**
* Size of the pitch-contour. This number also includes empty slots.
*
* @return Size of the contour.
*/
public final int size() {
return this.contour.size();
}
/**
* Returns the mean of all pitches in the melody.
*
* @return Pitch mean
*/
public final double pitchMean() {
if (this.dirty) {
this.calculate();
}
return this.frequencyStatistics.getMean();
}
/**
* Returns the standard-deviation of all pitches in the melody.
*
* @return Pitch standard deviation
*/
public final double pitchDeviation() {
if (this.dirty) {
this.calculate();
}
return this.frequencyStatistics.getStandardDeviation();
}
/**
* Returns the mean-salience of all pitches in the contour.
*
* @return Salience mean
*/
public final double salienceMean() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getMean();
}
/**
* Returns the salience standard deviation of all pitches in the contour.
*
* @return Salience standard deviation.
*/
public final double salienceDeviation() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getStandardDeviation();
}
/**
* Returns the sum of all salience values in the pitch contour.
*/
public final double salienceSum() {
if (this.dirty) {
this.calculate();
}
return this.salienceStatistics.getSum();
}
/**
* Calculates the overlap between the given pitch-contours.
*
* @return Size of the overlap between two pitch-contours.
*/
public final int overlap(PitchContour contour) {
return Math.max(0, Math.min(this.end, contour.end) - Math.max(this.start, contour.start));
}
/**
* Determines if two PitchContours overlap and returns true of false.
*
* @return true, if two PitchContours overlap and falseotherwise.
*/
public final boolean overlaps(PitchContour contour) {
return this.overlap(contour) > 0;
}
/**
* Re-calculates the PitchContour statistics.
*/
private void calculate() {
this.salienceStatistics.clear();
this.frequencyStatistics.clear();
for (Pitch pitch : this.contour) {
if (pitch != null) {
this.salienceStatistics.addValue(pitch.getSalience());
this.frequencyStatistics.addValue(pitch.distanceCents(CENT_SCALE_MINIMUM));
}
}
this.dirty = false;
}
}
| vitrivr/cineast | cineast-core/src/main/java/org/vitrivr/cineast/core/util/audio/pitch/tracking/PitchContour.java | Java | mit | 5,638 |
package com.company;
import java.util.Scanner;
public class EvenPowersOf2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int num = 1;
for (int i = 0; i <= n ; i+=2) {
System.out.println(num);
num *= 4;
}
}
}
| ivelin1936/Studing-SoftUni- | Programing Basic/Programming Basics - Exercises/Advanced Loops/src/com/company/EvenPowersOf2.java | Java | mit | 368 |
/*
* Copyright (c) 2020 by Stefan Schubert under the MIT License (MIT).
* See project LICENSE file for the detailed terms and conditions.
*/
package de.bluewhale.sabi.webclient.rest.exceptions;
import de.bluewhale.sabi.exception.ExceptionCode;
import de.bluewhale.sabi.exception.MessageCode;
import de.bluewhale.sabi.exception.TankExceptionCodes;
/**
* MessageCodes that may arise by using the Tank Restservice
*
* @author schubert
*/
public enum TankMessageCodes implements MessageCode {
NO_SUCH_TANK(TankExceptionCodes.TANK_NOT_FOUND_OR_DOES_NOT_BELONG_TO_USER);
// ------------------------------ FIELDS ------------------------------
private TankExceptionCodes exceptionCode;
// --------------------------- CONSTRUCTORS ---------------------------
TankMessageCodes() {
exceptionCode = null;
}
TankMessageCodes(TankExceptionCodes pExceptionCode) {
exceptionCode = pExceptionCode;
}
// --------------------- GETTER / SETTER METHODS ---------------------
@Override
public ExceptionCode getExceptionCode() {
return exceptionCode;
}
}
| StefanSchubert/sabi | sabi-webclient/src/main/java/de/bluewhale/sabi/webclient/rest/exceptions/TankMessageCodes.java | Java | mit | 1,112 |
package okeanos.data.services.entities;
import javax.measure.quantity.Power;
import org.jscience.physics.amount.Amount;
public interface Price {
double getCostAtConsumption(Amount<Power> consumption);
}
| wolfgang-lausenhammer/Okeanos | okeanos.data/src/main/java/okeanos/data/services/entities/Price.java | Java | mit | 207 |
package com.ruenzuo.weatherapp.adapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ruenzuo.weatherapp.R;
import com.ruenzuo.weatherapp.models.City;
/**
* Created by ruenzuo on 08/05/14.
*/
public class CitiesAdapter extends ArrayAdapter<City> {
private int resourceId;
public CitiesAdapter(Context context, int resource) {
super(context, resource);
resourceId = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity)getContext()).getLayoutInflater();
convertView = inflater.inflate(resourceId, null);
}
City country = getItem(position);
TextView txtViewCityName = (TextView) convertView.findViewById(R.id.txtViewCityName);
txtViewCityName.setText(country.getName());
return convertView;
}
} | Ruenzuo/android-facade-example | WeatherApp/src/main/java/com/ruenzuo/weatherapp/adapters/CitiesAdapter.java | Java | mit | 1,106 |
package tehnut.resourceful.crops.compat;
import mcp.mobius.waila.api.*;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.ItemHandlerHelper;
import tehnut.resourceful.crops.block.tile.TileSeedContainer;
import tehnut.resourceful.crops.core.RegistrarResourcefulCrops;
import tehnut.resourceful.crops.core.data.Seed;
import javax.annotation.Nonnull;
import java.util.List;
@WailaPlugin
public class CompatibilityWaila implements IWailaPlugin {
@Override
public void register(IWailaRegistrar registrar) {
final CropProvider cropProvider = new CropProvider();
registrar.registerStackProvider(cropProvider, TileSeedContainer.class);
registrar.registerNBTProvider(cropProvider, TileSeedContainer.class);
}
public static class CropProvider implements IWailaDataProvider {
@Nonnull
@Override
public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) {
Seed seed = RegistrarResourcefulCrops.SEEDS.getValue(new ResourceLocation(accessor.getNBTData().getString("seed")));
if (seed == null)
return accessor.getStack();
if (seed.isNull())
return accessor.getStack();
if (seed.getOutputs().length == 0)
return accessor.getStack();
return ItemHandlerHelper.copyStackWithSize(seed.getOutputs()[0].getItem(), 1);
}
@Nonnull
@Override
public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public List<String> getWailaTail(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
return currenttip;
}
@Nonnull
@Override
public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, BlockPos pos) {
tag.setString("seed", ((TileSeedContainer) te).getSeedKey().toString());
return tag;
}
}
}
| TehNut/ResourcefulCrops | src/main/java/tehnut/resourceful/crops/compat/CompatibilityWaila.java | Java | mit | 2,650 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.text;
import java.util.Map;
public abstract class StrLookup<V> {
public static StrLookup<?> noneLookup() {
return null;
}
public static StrLookup<String> systemPropertiesLookup() {
return null;
}
public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
return null;
}
public abstract String lookup(String key);
}
| github/codeql | java/ql/test/stubs/apache-commons-lang3-3.7/org/apache/commons/lang3/text/StrLookup.java | Java | mit | 1,213 |
package com.rebuy.consul;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ecwid.consul.v1.catalog.model.CatalogService;
import com.rebuy.consul.exceptions.NoServiceFoundException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ConsulServiceTest
{
private ConsulClient clientMock;
private ConsulService service;
private NewService serviceMock;
@Before
public void before()
{
clientMock = mock(ConsulClient.class);
serviceMock = mock(NewService.class);
when(serviceMock.getId()).thenReturn("42");
service = new ConsulService(clientMock, serviceMock);
}
@Test
public void register_should_invoke_client()
{
when(clientMock.agentServiceRegister(Mockito.any())).thenReturn(null);
service.register();
Mockito.verify(clientMock).agentServiceRegister(serviceMock);
}
@Test
public void unregister_should_invoke_client()
{
service.unregister();
Mockito.verify(clientMock).agentServiceSetMaintenance("42", true);
}
@Test(expected = NoServiceFoundException.class)
public void findService_should_throw_exception_if_no_services_are_found()
{
Response<List<CatalogService>> response = new Response<>(new ArrayList<>(), 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
service.getRandomService("service");
Mockito.verify(clientMock).getCatalogService("service", Mockito.any(QueryParams.class));
}
@Test
public void findService_should_invoke_client()
{
List<CatalogService> services = new ArrayList<>();
services.add(mock(CatalogService.class));
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
service.getRandomService("service");
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class));
}
@Test
public void findService_should_return_one_service()
{
List<CatalogService> services = new ArrayList<>();
CatalogService service1 = mock(CatalogService.class);
when(service1.getAddress()).thenReturn("192.168.0.1");
services.add(service1);
CatalogService service2 = mock(CatalogService.class);
when(service2.getAddress()).thenReturn("192.168.0.2");
services.add(service2);
CatalogService service3 = mock(CatalogService.class);
when(service3.getAddress()).thenReturn("192.168.0.3");
services.add(service3);
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
Service catalogService = service.getRandomService("service");
boolean foundMatch = false;
for (CatalogService service : services) {
if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) {
foundMatch = true;
}
}
assertTrue(foundMatch);
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class));
}
@Test
public void findService_should_return_one_service_with_tag()
{
List<CatalogService> services = new ArrayList<>();
CatalogService service1 = mock(CatalogService.class);
when(service1.getAddress()).thenReturn("192.168.0.1");
services.add(service1);
CatalogService service2 = mock(CatalogService.class);
when(service2.getAddress()).thenReturn("192.168.0.2");
services.add(service2);
CatalogService service3 = mock(CatalogService.class);
when(service3.getAddress()).thenReturn("192.168.0.3");
services.add(service3);
Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L);
when(clientMock.getCatalogService(Mockito.anyString(), Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response);
Service catalogService = service.getRandomService("service", "my-tag");
boolean foundMatch = false;
for (CatalogService service : services) {
if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) {
foundMatch = true;
}
}
assertTrue(foundMatch);
Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.eq("my-tag"), Mockito.any(QueryParams.class));
}
}
| rebuy-de/consul-java-client | src/test/java/com/rebuy/consul/ConsulServiceTest.java | Java | mit | 5,239 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class CallableAndFutureTest {
private final ExecutorService executor = Executors.newFixedThreadPool(2);
void start() throws Exception {
final Callable<List<Integer>> task = new Callable<List<Integer>>() {
public List<Integer> call() throws Exception {
// get obj
final List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
Thread.sleep(50);
list.add(i);
}
return list;
}
};
final Future<List<Integer>> future = executor.submit(task);
//do sthing others..
//example: due to show some data..
try {
final List<Integer> list = future.get(); //这个函数还可以接受超时检测http://www.javaeye.com/topic/671314
System.out.println(list);
} catch (final InterruptedException ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
future.cancel(true);
} catch (final ExecutionException ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
throw new ExecutionException(ex);
} finally {
executor.shutdown();
}
}
public static void main(final String args[]) {
try {
new CallableAndFutureTest().start();
} catch (final Exception ex) {
Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| atealxt/work-workspaces | Test_Java/src/test/thread/CallableAndFutureTest.java | Java | mit | 2,091 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.eventhubs.generated;
import com.azure.core.util.Context;
/** Samples for ConsumerGroups ListByEventHub. */
public final class ConsumerGroupsListByEventHubSamples {
/*
* x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/ConsumerGroup/EHConsumerGroupListByEventHub.json
*/
/**
* Sample code: ConsumerGroupsListAll.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void consumerGroupsListAll(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.eventHubs()
.manager()
.serviceClient()
.getConsumerGroups()
.listByEventHub("ArunMonocle", "sdk-Namespace-2661", "sdk-EventHub-6681", null, null, Context.NONE);
}
}
| Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/eventhubs/generated/ConsumerGroupsListByEventHubSamples.java | Java | mit | 1,031 |
package net.talayhan.android.vibeproject.Controller;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.ipaulpro.afilechooser.utils.FileUtils;
import net.talayhan.android.vibeproject.R;
import net.talayhan.android.vibeproject.Util.Constants;
import java.io.File;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class MainActivity extends Activity {
@InjectView(R.id.fileChooser_bt) Button mFileChooser_bt;
@InjectView(R.id.playBack_btn) Button mPlayback_bt;
@InjectView(R.id.chart_bt) Button mChart_bt;
private String videoPath;
private String vidAddress = "https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4";
private SweetAlertDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mFileChooser_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* Progress dialog */
pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Network Type");
pDialog.setContentText("How would you like to watch video?");
pDialog.setConfirmText("Local");
pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
// Local
// Create the ACTION_GET_CONTENT Intent
Intent getContentIntent = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(getContentIntent, "Select a file");
startActivityForResult(intent, Constants.REQUEST_CHOOSER);
sweetAlertDialog.dismissWithAnimation();
}
});
pDialog.setCancelText("Internet");
pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
/* check the device network state */
if (!isOnline()){
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
.setContentText("Your device is now offline!\n" +
"Please open your Network.")
.setTitleText("Open Network Connection")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
showNoConnectionDialog(MainActivity.this);
sweetAlertDialog.dismissWithAnimation();
}
})
.show();
}else {
// Create the intent to start video activity
Intent i = new Intent(MainActivity.this, LocalVideoActivity.class);
i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE, vidAddress);
startActivity(i);
sweetAlertDialog.dismissWithAnimation();
}
}
});
pDialog.setCancelable(true);
pDialog.show();
}
});
mPlayback_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE)
.setContentText("Please first label some video!\n" +
"Later come back here!.")
.setTitleText("Playback")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismissWithAnimation();
}
})
.show();
}
});
mChart_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ChartRecyclerView.class);
startActivityForResult(i, Constants.REQUEST_CHART);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Constants.REQUEST_CHOOSER:
if (resultCode == RESULT_OK) {
final Uri uri = data.getData();
// Get the File path from the Uri
String path = FileUtils.getPath(this, uri);
Toast.makeText(this, "Choosen file: " + path,Toast.LENGTH_LONG).show();
// Alternatively, use FileUtils.getFile(Context, Uri)
if (path != null && FileUtils.isLocal(path)) {
File file = new File(path);
}
// Create the intent to start video activity
Intent i = new Intent(MainActivity.this, LocalVideoActivity.class);
i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE,path);
startActivity(i);
}
break;
}
}
/*
* This method checks network situation, if device is airplane mode or something went wrong on
* network stuff. Method returns false, otherwise return true.
*
* - This function inspired by below link,
* http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts
*
* @return boolean - network state
* * * */
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
/**
* Display a dialog that user has no internet connection
* @param ctx1
*
* Code from: http://osdir.com/ml/Android-Developers/2009-11/msg05044.html
*/
public static void showNoConnectionDialog(Context ctx1) {
final Context ctx = ctx1;
final SweetAlertDialog builder = new SweetAlertDialog(ctx, SweetAlertDialog.SUCCESS_TYPE);
builder.setCancelable(true);
builder.setContentText("Open internet connection");
builder.setTitle("No connection error!");
builder.setConfirmText("Open wirless.");
builder.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
ctx.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
builder.dismissWithAnimation();
}
});
builder.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if (id == R.id.action_search){
openSearch();
return true;
}
return super.onOptionsItemSelected(item);
}
private void openSearch() {
Toast.makeText(this,"Clicked Search button", Toast.LENGTH_SHORT).show();
}
}
| stalayhan/vibeapp | app/src/main/java/net/talayhan/android/vibeproject/Controller/MainActivity.java | Java | mit | 9,208 |
package org.xcolab.client.contest.pojo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.xcolab.client.contest.pojo.tables.pojos.ContestCollectionCard;
@JsonDeserialize(as = ContestCollectionCard.class)
public interface IContestCollectionCard {
Long getId();
void setId(Long id);
Long getParent();
void setParent(Long parent);
Long getBigOntologyTerm();
void setBigOntologyTerm(Long bigOntologyTerm);
Long getSmallOntologyTerm();
void setSmallOntologyTerm(Long smallOntologyTerm);
String getDescription();
void setDescription(String description);
String getShortName();
void setShortName(String shortName);
Boolean isVisible();
void setVisible(Boolean visible);
Integer getSortOrder();
void setSortOrder(Integer sortOrder);
Long getOntologyTermToLoad();
void setOntologyTermToLoad(Long ontologyTermToLoad);
Boolean isOnlyFeatured();
void setOnlyFeatured(Boolean onlyFeatured);
}
| CCI-MIT/XCoLab | microservices/clients/contest-client/src/main/java/org/xcolab/client/contest/pojo/IContestCollectionCard.java | Java | mit | 1,010 |
package utils;
import java.io.*;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ueb01.StringBufferImpl;
/**
* Created with IntelliJ IDEA.
* User: Julian
* Date: 16.10.13
* Time: 13:37
*/
public class Utils {
private static long currentTime;
/**
* http://svn.apache.org/viewvc/camel/trunk/components/camel-test/src/main/java/org/apache/camel/test/AvailablePortFinder.java?view=markup#l130
* Checks to see if a specific port is available.
*
* @param port the port to check for availability
*/
public static boolean available(int port) {
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}
return false;
}
public static void stopwatchStart() {
currentTime = java.lang.System.nanoTime();
}
static ExecutorService pool = null;
public static class SyncTcpResponse {
public final Socket socket;
public final String message;
public boolean isValid() {
return this.socket != null;
}
public SyncTcpResponse(Socket s, String m) {
this.socket = s;
this.message = m;
}
}
public static String getTCPSync(final Socket socket) {
StringBuilder sb = new StringBuilder();
try {
Scanner s = new Scanner(socket.getInputStream());
while (s.hasNext()) {
sb.append(s.next());
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static SyncTcpResponse getTCPSync(final int port) {
ServerSocket server = null;
Socket client = null;
StringBuilder sb = new StringBuilder();
try {
server = new ServerSocket(port);
client = server.accept();
Scanner s = new Scanner(client.getInputStream());
while (s.hasNext()) {
sb.append(s.next());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new SyncTcpResponse(client, sb.toString());
}
public static Future<String> getTCP(final int port) {
if (pool == null) {
pool = Executors.newCachedThreadPool();
}
return pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
ServerSocket server = null;
/*try(ServerSocket socket = new ServerSocket(port)){
Socket client = socket.accept();
Scanner s = new Scanner(client.getInputStream());
StringBuilder sb = new StringBuilder();
while (s.hasNext()){
sb.append(s.next());
}
return sb.toString();
} */
return null;
}
});
}
public static Socket sendTCP(InetAddress address, int port, String message) {
try {
Socket s = new Socket(address, port);
return sendTCP(s, message);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Socket sendTCP(Socket socket, String message) {
PrintWriter out = null;
try {
out = new PrintWriter(socket.getOutputStream());
out.println(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return socket;
}
public static void close() {
if (pool != null) {
pool.shutdown();
}
}
public static String wordFromScanner(Scanner scanner) {
StringBuilder result = new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line);
result.append("\n");
}
return result.toString();
}
public static String[] wordsFromScanner(Scanner scanner) {
List<String> result = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] words = line.split(" ");
for (String word : words) {
if (word.length() > 0)
result.add(wordify(word));
}
}
return Utils.<String>listToArrayStr(result);
}
public static String wordify(String word) {
return word.replace(",", "").replace(".", "").replace("'", "").replace("\"", "")
.replace("...", "").replace("!", "").replace(";", "").replace(":", "").toLowerCase();
}
public static <T> T[] listToArray(List<T> list) {
T[] result = (T[]) new Object[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public static String[] listToArrayStr(List<String> list) {
String[] result = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
public static void stopwatchEnd() {
long current = java.lang.System.nanoTime();
long dif = current - currentTime;
long millis = dif / 1000000;
System.out.println("Millis: {" + millis + "} Nanos: {" + dif + "}");
}
/**
* Method to send a command to a Process
*
* @param p
* @param command
*/
public static void send(Process p, String command) {
OutputStream os = p.getOutputStream();
try {
os.write(command.getBytes());
} catch (IOException e) {
System.out.println("something went wrong... [Utils.send(..) -> " + e.getMessage());
} finally {
try {
os.close();
} catch (IOException e) {
System.out.println("something went wrong while closing... [Utils.send(..) -> " + e.getMessage());
}
}
}
public static void close(Process p) {
try {
p.getOutputStream().close();
p.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* easy exceptionless sleep
*
* @param millis
*/
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("ALP5: Utils::sleep crashed..");
}
}
public static int countCharactersInFile(String fileName) {
BufferedReader br = null;
try {
StringBuilder sb = new StringBuilder();
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
return sb.length();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("shit happens... @Utils.countCharactersInFile");
return -1;
} catch (IOException e) {
e.printStackTrace();
System.out.println("shit happens while reading... @Utils.countCharactersInFile");
} finally {
if (br != null) try {
br.close();
} catch (IOException e) {
e.printStackTrace();
return -2;
}
}
return -3;
}
public static String join(String[] l, String connector) {
StringBuilder sb = new StringBuilder();
for (String s : l) {
if (sb.length() > 0) {
sb.append(connector);
}
sb.append(s);
}
return sb.toString();
}
public static String readFromStream(InputStream is){
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
/**
* Method to receive the output of a Process
*
* @param p
* @return
*/
public static String read(Process p) {
StringBuilder sb = new StringBuilder();
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s = null;
try {
while ((s = reader.readLine()) != null) {
if (s.equals("") || s.equals(" ")) break;
sb.append(s);
}
} catch (IOException e) {
System.out.println("something went wrong... [Utils.read(..) -> " + e.getMessage());
}
return sb.toString();
}
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("yyy");
System.out.println('a' > 'b');
}
/**
* If you want to use your ssh-key-login, you need to generate a pem-File from
* the ssh-private-key and put it into the main folder ( ALP5/ ); You also need
* to define the user with @ (like: [email protected]:...)
*
* @param commandId
* @return
*/
public static Process fork(String commandId) {
String username = null; // HARDCODE ME!
String password = null; // HARDCODE ME!
String host = null;
String command = commandId;
if (commandId.contains(":")) {
String[] temp = commandId.split(":");
if (temp[0].length() > 2) {
// if the host is shorter its probably just a windows drive ('d:// ...')
host = temp[0];
if (host.contains("@")) {
String[] t = host.split("@");
username = t[0];
host = t[1];
}
if (temp.length == 3) {
command = temp[1] + ":" + temp[2]; // to "repair" windows drives...
} else {
command = temp[1];
}
}
}
if (host != null) {
Process remoteP = null;
try {
final Connection conn = new Connection(host);
conn.connect();
boolean isAuth = false;
if (password != null) {
isAuth = conn.authenticateWithPassword(username, password);
}
if (!isAuth) {
File f = new File("private.pem");
isAuth = conn.authenticateWithPublicKey(username, f, "");
if (!isAuth) return null;
}
final Session sess = conn.openSession();
sess.execCommand(command);
remoteP = new Process() {
@Override
public OutputStream getOutputStream() {
return sess.getStdin();
}
@Override
public InputStream getInputStream() {
return sess.getStdout();
}
@Override
public InputStream getErrorStream() {
return sess.getStderr();
}
@Override
public int waitFor() throws InterruptedException {
sess.wait();
return 0;
}
@Override
public int exitValue() {
return 0;
}
@Override
public void destroy() {
sess.close();
conn.close();
}
};
} catch (IOException e) {
System.out.println("shit happens with the ssh connection: @Utils.fork .. " + e.getMessage());
return null;
}
return remoteP;
}
ProcessBuilder b = new ProcessBuilder(command.split(" "));
try {
return b.start();
} catch (IOException e) {
System.out.println("shit happens: @Utils.fork .. " + e.getMessage());
}
return null;
}
}
| justayak/ALP5 | src/utils/Utils.java | Java | mit | 14,112 |
package org.eggermont.hm.cluster;
import cern.colt.matrix.DoubleFactory1D;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
public class ClusterFactory {
private final DoubleMatrix2D x;
private final DoubleMatrix1D blocks;
private final DoubleMatrix1D vMin;
private final DoubleMatrix1D vMax;
private final int ndof;
public ClusterFactory(int d, int nidx, int ndof) {
this.ndof = ndof;
this.blocks = DoubleFactory1D.dense.make(d * nidx);
this.x = blocks.like2D(nidx, d);
this.vMin = DoubleFactory1D.dense.make(d);
this.vMax = DoubleFactory1D.dense.make(d);
}
}
| meggermo/hierarchical-matrices | src/main/java/org/eggermont/hm/cluster/ClusterFactory.java | Java | mit | 669 |
package net.spy.digg.parsers;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import net.spy.digg.Story;
/**
* Parse a stories response.
*/
public class StoriesParser extends TimePagedItemParser<Story> {
@Override
protected String getRootElementName() {
return "stories";
}
@Override
protected void handleDocument(Document doc)
throws SAXException, IOException {
parseCommonFields(doc);
final NodeList nl=doc.getElementsByTagName("story");
for(int i=0; i<nl.getLength(); i++) {
addItem(new StoryImpl(nl.item(i)));
}
}
}
| dustin/java-digg | src/main/java/net/spy/digg/parsers/StoriesParser.java | Java | mit | 621 |
package de.thomas.dreja.ec.musicquiz.gui.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import de.thomas.dreja.ec.musicquiz.R;
import de.thomas.dreja.ec.musicquiz.ctrl.PlaylistResolver.SortOrder;
public class SortOrderSelectionDialog extends DialogFragment {
private SortOrderSelectionListener listener;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String[] items = new String[SortOrder.values().length];
for(int i=0; i<items.length; i++) {
items[i] = SortOrder.values()[i].getName(getResources());
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.sort_by)
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onSortOrderSelected(SortOrder.values()[which]);
}
});
return builder.create();
}
public interface SortOrderSelectionListener {
public void onSortOrderSelected(SortOrder order);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = (SortOrderSelectionListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement SortOrderSelectionListener");
}
}
}
| Nanobot5770/DasMusikQuiz | src/de/thomas/dreja/ec/musicquiz/gui/dialog/SortOrderSelectionDialog.java | Java | mit | 1,823 |
package com.github.fhtw.swp.tutorium.guice;
import com.github.fhtw.swp.tutorium.composite.Leaf;
import com.github.fhtw.swp.tutorium.composite.LeafTypeProvider;
import com.github.fhtw.swp.tutorium.reflection.AnnotatedTypeFinder;
import org.reflections.Configuration;
import javax.inject.Inject;
import java.util.Set;
public class LeafTypeProviderImpl implements LeafTypeProvider {
private final Configuration configuration;
@Inject
public LeafTypeProviderImpl(Configuration configuration) {
this.configuration = configuration;
}
@Override
public Set<Class<?>> getLeafTypes() {
return new AnnotatedTypeFinder(configuration, Leaf.class).getAnnotatedTypes();
}
}
| fhtw-swp-tutorium/java-swp-test-tool | test-console/src/main/java/com/github/fhtw/swp/tutorium/guice/LeafTypeProviderImpl.java | Java | mit | 709 |
class Solution {
public int solution(int[] A) {
int[] temArray = new int[A.length + 2];
for (int i = 0; i < A.length; i++) {
temArray[A[i]] = 1;
}
for (int i = 1; i < temArray.length + 1; i++) {
if(temArray[i] == 0){
return i;
}
}
return A[A.length - 1] + 1;
}
}
| majusko/codility | PermMissingElem.java | Java | mit | 392 |
package org.aikodi.chameleon.support.statement;
import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.element.ElementImpl;
import org.aikodi.chameleon.core.lookup.DeclarationSelector;
import org.aikodi.chameleon.core.lookup.LookupContext;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.lookup.SelectionResult;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.statement.ExceptionSource;
import org.aikodi.chameleon.oo.statement.Statement;
import org.aikodi.chameleon.util.association.Multi;
import java.util.Collections;
import java.util.List;
/**
* A list of statement expressions as used in the initialization clause of a for
* statement. It contains a list of statement expressions.
*
* @author Marko van Dooren
*/
public class StatementExprList extends ElementImpl implements ForInit, ExceptionSource {
public StatementExprList() {
}
/**
* STATEMENT EXPRESSIONS
*/
private Multi<StatementExpression> _statementExpressions = new Multi<StatementExpression>(this);
public void addStatement(StatementExpression statement) {
add(_statementExpressions, statement);
}
public void removeStatement(StatementExpression statement) {
remove(_statementExpressions, statement);
}
public List<StatementExpression> statements() {
return _statementExpressions.getOtherEnds();
}
@Override
public StatementExprList cloneSelf() {
return new StatementExprList();
}
public int getIndexOf(Statement statement) {
return statements().indexOf(statement) + 1;
}
public int getNbStatements() {
return statements().size();
}
@Override
public List<? extends Declaration> locallyDeclaredDeclarations() throws LookupException {
return declarations();
}
@Override
public List<? extends Declaration> declarations() throws LookupException {
return Collections.EMPTY_LIST;
}
@Override
public LookupContext localContext() throws LookupException {
return language().lookupFactory().createLocalLookupStrategy(this);
}
@Override
public <D extends Declaration> List<? extends SelectionResult<D>> declarations(DeclarationSelector<D> selector)
throws LookupException {
return Collections.emptyList();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
}
| markovandooren/chameleon | src/org/aikodi/chameleon/support/statement/StatementExprList.java | Java | mit | 2,449 |
package cn.libery.calendar.MaterialCalendar;
import android.content.Context;
import java.util.Collection;
import java.util.HashSet;
import cn.libery.calendar.MaterialCalendar.spans.DotSpan;
/**
* Decorate several days with a dot
*/
public class EventDecorator implements DayViewDecorator {
private int color;
private HashSet<CalendarDay> dates;
public EventDecorator(int color, Collection<CalendarDay> dates) {
this.color = color;
this.dates = new HashSet<>(dates);
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return dates.contains(day);
}
@Override
public void decorate(DayViewFacade view, Context context) {
view.addSpan(new DotSpan(4, color));
}
}
| Thewhitelight/Calendar | app/src/main/java/cn/libery/calendar/MaterialCalendar/EventDecorator.java | Java | mit | 752 |
package br.com.k19.android.cap3;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frame);
}
}
| andersonsilvade/workspacejava | Workspaceandroid/MainActivity/src/br/com/k19/android/cap3/MainActivity.java | Java | mit | 280 |
package com.mikescamell.sharedelementtransitions.recycler_view.recycler_view_to_viewpager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.mikescamell.sharedelementtransitions.R;
public class RecyclerViewToViewPagerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_to_fragment);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, RecyclerViewFragment.newInstance())
.commit();
}
}
| mikescamell/shared-element-transitions | app/src/main/java/com/mikescamell/sharedelementtransitions/recycler_view/recycler_view_to_viewpager/RecyclerViewToViewPagerActivity.java | Java | mit | 652 |