repo_name stringlengths 7 104 | file_path stringlengths 11 238 | context list | import_statement stringlengths 103 6.85k | code stringlengths 60 38.4k | next_line stringlengths 10 824 | gold_snippet_index int32 0 8 |
|---|---|---|---|---|---|---|
calrissian/flowmix | src/main/java/org/calrissian/flowmix/example/JoinExample.java | [
"public class ExampleRunner {\n\n FlowProvider provider;\n\n public ExampleRunner(FlowProvider provider) {\n this.provider = provider;\n }\n\n public void run() {\n\n StormTopology topology = new FlowmixBuilder()\n .setFlowLoader(new SimpleFlowLoaderSpout(provider.getFlows(), 60000))\n .setE... | import com.google.common.collect.Iterables;
import org.calrissian.flowmix.example.support.ExampleRunner;
import org.calrissian.flowmix.example.support.FlowProvider;
import org.calrissian.flowmix.api.Flow;
import org.calrissian.flowmix.api.Policy;
import org.calrissian.flowmix.api.builder.FlowBuilder;
import org.calrissian.flowmix.api.Function;
import org.calrissian.mango.domain.event.BaseEvent;
import org.calrissian.mango.domain.event.Event;
import org.calrissian.mango.domain.Tuple;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList; | /*
* Copyright (C) 2014 The Calrissian Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.calrissian.flowmix.example;
/**
* A stream join example. The events for the left hand of the join (stream1) are collected into a window and the
* right hand side is joined against the left hand side (that is, the tuples are merged with the right hand side).
*/
public class JoinExample implements FlowProvider {
@Override
public List<Flow> getFlows() {
Flow flow = new FlowBuilder()
.id("flow")
.flowDefs()
.stream("stream1")
.each().function(new Function() {
@Override
public List<Event> execute(Event event) {
Event newEvent = new BaseEvent(event.getId(), event.getTimestamp());
newEvent.putAll(Iterables.concat(event.getTuples()));
newEvent.put(new Tuple("stream", "stream1"));
return singletonList(newEvent);
}
}).end()
.endStream(false, "stream3") // send ALL results to stream2 and not to standard output
.stream("stream2") // don't read any events from standard input
.each().function(new Function() {
@Override
public List<Event> execute(Event event) {
Event newEvent = new BaseEvent(event.getId(), event.getTimestamp());
newEvent.putAll(Iterables.concat(event.getTuples()));
newEvent.put(new Tuple("stream", "stream2"));
return singletonList(newEvent);
}
}).end()
.endStream(false, "stream3")
.stream("stream3", false)
.join("stream1", "stream2").evict(Policy.TIME, 5).end()
.endStream()
.endDefs()
.createFlow();
return asList(new Flow[]{flow});
}
public static void main(String args[]) { | new ExampleRunner(new JoinExample()).run(); | 0 |
xdrop/jRand | jrand-core/src/main/java/me/xdrop/jrand/generators/location/StreetGenerator.java | [
"public abstract class Generator<T> {\n\n private Rand randGen;\n\n public Generator() {\n this.randGen = new Rand();\n }\n\n public Rand random() {\n return this.randGen;\n }\n\n public abstract T gen();\n\n public String repeat(int times) {\n StringBuilder sb = new String... | import me.xdrop.jrand.Generator;
import me.xdrop.jrand.annotation.Facade;
import me.xdrop.jrand.data.AssetLoader;
import me.xdrop.jrand.data.Assets;
import me.xdrop.jrand.generators.basics.NaturalGenerator;
import me.xdrop.jrand.generators.text.WordGenerator;
import me.xdrop.jrand.model.location.StreetSuffix;
import me.xdrop.jrand.model.location.StreetSuffixMapper;
import me.xdrop.jrand.utils.Choose;
import java.util.ArrayList;
import java.util.List; | package me.xdrop.jrand.generators.location;
@Facade(accessor = "street")
public class StreetGenerator extends Generator<String> {
protected WordGenerator wordGenerator;
protected NaturalGenerator nat;
protected String country;
protected boolean shortSuffix; | protected List<StreetSuffix> ukStreetSuffixes; | 5 |
TechzoneMC/NPCLib | nms-v1_7_R4/src/main/java/net/techcable/npclib/nms/versions/v1_7_R4/NMS.java | [
"public interface HumanNPC extends LivingNPC {\r\n\r\n /**\r\n * Return this npc's skin\r\n * <p/>\r\n * A value of null represents a steve skin\r\n *\r\n * @return this npc's skin\r\n */\r\n public UUID getSkin();\r\n\r\n /**\r\n * Set the npc's skin\r\n * <p/>\r\n * A ... | import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import net.minecraft.server.v1_7_R4.EntityLiving;
import net.minecraft.server.v1_7_R4.EntityPlayer;
import net.minecraft.server.v1_7_R4.MinecraftServer;
import net.minecraft.server.v1_7_R4.Packet;
import net.minecraft.server.v1_7_R4.WorldServer;
import net.minecraft.util.com.mojang.authlib.GameProfile;
import net.techcable.npclib.HumanNPC;
import net.techcable.npclib.LivingNPC;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.IHumanNPCHook;
import net.techcable.npclib.nms.ILivingNPCHook;
import net.techcable.npclib.nms.versions.v1_7_R4.entity.EntityNPCPlayer;
import net.techcable.npclib.utils.NPCLog;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_7_R4.CraftServer;
import org.bukkit.craftbukkit.v1_7_R4.CraftWorld;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftLivingEntity;
import org.bukkit.craftbukkit.v1_7_R4.entity.CraftPlayer;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; | package net.techcable.npclib.nms.versions.v1_7_R4;
public class NMS implements net.techcable.npclib.nms.NMS {
private static NMS instance;
public NMS() {
if (instance == null) instance = this;
}
public static NMS getInstance() {
return instance;
}
@Override
public IHumanNPCHook spawnHumanNPC(Location toSpawn, HumanNPC npc) {
return new HumanNPCHook(npc, toSpawn);
}
@Override
public void onJoin(Player joined, Collection<? extends NPC> npcs) {
for (NPC npc : npcs) {
if (!(npc instanceof HumanNPC)) continue;
HumanNPCHook hook = getHandle((HumanNPC) npc);
if (hook == null) continue;
hook.onJoin(joined);
}
}
// UTILS
public static final String NO_CRAFTBUKKIT_MSG = "Non-CraftBukkit implementations are unsupported";
public static EntityPlayer getHandle(Player player) {
if (!(player instanceof CraftPlayer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
return ((CraftPlayer) player).getHandle();
}
public static EntityLiving getHandle(LivingEntity player) {
if (!(player instanceof CraftLivingEntity)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
return ((CraftLivingEntity) player).getHandle();
}
public static MinecraftServer getServer() {
Server server = Bukkit.getServer();
if (!(server instanceof CraftServer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
return ((CraftServer) server).getServer();
}
public static WorldServer getHandle(World world) {
if (!(world instanceof CraftWorld)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
return ((CraftWorld) world).getHandle();
}
public static HumanNPCHook getHandle(HumanNPC npc) {
EntityPlayer player = getHandle(npc.getEntity());
if (player instanceof EntityNPCPlayer) return null;
return ((EntityNPCPlayer) player).getHook();
}
public static void sendToAll(Packet packet) {
for (EntityPlayer p : (List<EntityPlayer>) MinecraftServer.getServer().getPlayerList().players) {
p.playerConnection.sendPacket(packet);
}
}
private static final Cache<UUID, GameProfile> properties = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES)
.build(new CacheLoader<UUID, GameProfile>() {
@Override
public GameProfile load(UUID uuid) throws Exception {
return MinecraftServer.getServer().av().fillProfileProperties(new GameProfile(uuid, null), true);
}
});
public static void setSkin(GameProfile profile, UUID skinId) {
GameProfile skinProfile;
if (Bukkit.getPlayer(skinId) != null) {
skinProfile = getHandle(Bukkit.getPlayer(skinId)).getProfile();
} else {
skinProfile = properties.getUnchecked(skinId);
}
if (skinProfile.getProperties().containsKey("textures")) {
profile.getProperties().removeAll("textures");
profile.getProperties().putAll("textures", skinProfile.getProperties().get("textures"));
} else { | NPCLog.debug("Skin with uuid not found: " + skinId); | 6 |
domkowald/tagrecommender | src/processing/LanguageModelCalculator.java | [
"public class PredictionFileWriter {\r\n\r\n\tprivate static final int OUTPUT_LIMIT = 10;\r\n\t\r\n\tprivate BookmarkReader reader;\r\n\tprivate List<int[]> results;\r\n\r\n\t\r\n\tpublic PredictionFileWriter(BookmarkReader reader, List<int[]> results) {\r\n\t\tthis.reader = reader;\r\n\t\tthis.results = results;\r... | import file.BookmarkReader;
import file.BookmarkSplitter;
import common.DoubleMapComparator;
import common.UserData;
import common.Utilities;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
import com.google.common.primitives.Ints;
import file.PredictionFileWriter;
| /*
TagRecommender:
A framework to implement and evaluate algorithms for the recommendation
of tags.
Copyright (C) 2013 Dominik Kowald
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package processing;
public class LanguageModelCalculator {
private final static int REC_LIMIT = 10;
private BookmarkReader reader;
private double beta;
private boolean userBased;
private boolean resBased;
private List<Map<Integer, Integer>> userMaps;
private List<Double> userDenoms;
private List<Map<Integer, Integer>> resMaps;
private List<Double> resDenoms;
public LanguageModelCalculator(BookmarkReader reader, int trainSize, int beta, boolean userBased, boolean resBased) {
this.reader = reader;
this.beta = (double)beta / 10.0;
this.userBased = userBased;
this.resBased = resBased;
| List<UserData> trainList = this.reader.getUserLines().subList(0, trainSize);
| 4 |
linkedin/Spyglass | spyglass/src/main/java/com/linkedin/android/spyglass/ui/MentionsEditText.java | [
"public class MentionSpan extends ClickableSpan implements Parcelable {\n\n private final Mentionable mention;\n private MentionSpanConfig config;\n\n private boolean isSelected = false;\n private MentionDisplayMode mDisplayMode = MentionDisplayMode.FULL;\n\n public MentionSpan(@NonNull Mentionable m... | import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Editable;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ArrowKeyMovementMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.accessibility.AccessibilityEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.IntRange;
import androidx.annotation.MenuRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.linkedin.android.spyglass.R;
import com.linkedin.android.spyglass.mentions.MentionSpan;
import com.linkedin.android.spyglass.mentions.MentionSpanConfig;
import com.linkedin.android.spyglass.mentions.Mentionable;
import com.linkedin.android.spyglass.mentions.MentionsEditable;
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsVisibilityManager;
import com.linkedin.android.spyglass.tokenization.QueryToken;
import com.linkedin.android.spyglass.tokenization.interfaces.QueryTokenReceiver;
import com.linkedin.android.spyglass.tokenization.interfaces.TokenSource;
import com.linkedin.android.spyglass.tokenization.interfaces.Tokenizer;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright 2015 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.linkedin.android.spyglass.ui;
/**
* Class that overrides {@link EditText} in order to have more control over touch events and selection ranges for use in
* the {@link RichEditorView}.
* <p/>
* <b>XML attributes</b>
* <p/>
* See {@link R.styleable#MentionsEditText Attributes}
*
* @attr ref R.styleable#MentionsEditText_mentionTextColor
* @attr ref R.styleable#MentionsEditText_mentionTextBackgroundColor
* @attr ref R.styleable#MentionsEditText_selectedMentionTextColor
* @attr ref R.styleable#MentionsEditText_selectedMentionTextBackgroundColor
*/
public class MentionsEditText extends EditText implements TokenSource {
private static final String KEY_MENTION_SPANS = "mention_spans";
private static final String KEY_MENTION_SPAN_STARTS = "mention_span_starts";
private Tokenizer mTokenizer; | private QueryTokenReceiver mQueryTokenReceiver; | 6 |
KKorvin/uPods-android | app/src/main/java/com/chickenkiller/upods2/dialogs/DialogFragmentAddMediaItem.java | [
"public class ProfileManager {\n\n public static final String JS_SUBSCRIBED_PODCASTS = \"subscribedPodcasts\";\n public static final String JS_SUBSCRIBED_STATIONS = \"subscribedStations\";\n public static final String JS_RECENT_STATIONS = \"recentStations\";\n\n public static ProfileManager profileManag... | import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.Toast;
import com.chickenkiller.upods2.R;
import com.chickenkiller.upods2.controllers.app.ProfileManager;
import com.chickenkiller.upods2.models.Podcast;
import com.chickenkiller.upods2.models.RadioItem;
import com.chickenkiller.upods2.models.StreamUrl;
import com.chickenkiller.upods2.utils.enums.MediaItemType; | package com.chickenkiller.upods2.dialogs;
/**
* Created by Alon Zilberman on 8/8/15.
*/
public class DialogFragmentAddMediaItem extends DialogFragment {
public static final String TAG = "add_media_item";
private static final int MIN_TITLE_LENGTH = 3;
private MediaItemType mediaItemType;
private EditText etMediaName;
private EditText etMediaUrl;
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mainView = inflater.inflate(R.layout.dialog_fragment_add_media, null);
etMediaName = (EditText) mainView.findViewById(R.id.etMediaName);
etMediaUrl = (EditText) mainView.findViewById(R.id.etMediaUrl);
String title = "LOL123";
if (mediaItemType == MediaItemType.RADIO) {
title = getString(R.string.add_radio_station);
} else if (mediaItemType == MediaItemType.PODCAST) {
title = getString(R.string.add_podcast);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (saveMediaItem()) {
dialog.dismiss();
}
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}).setView(mainView);
return builder.create();
}
public void setMediaItemType(MediaItemType mediaItemType) {
this.mediaItemType = mediaItemType;
}
private boolean saveMediaItem() {
if (etMediaName.getText().toString().length() < MIN_TITLE_LENGTH) {
Toast.makeText(getActivity(), getString(R.string.title_too_short), Toast.LENGTH_SHORT).show();
return false;
} else if (!URLUtil.isValidUrl(etMediaUrl.getText().toString())) {
Toast.makeText(getActivity(), getString(R.string.url_not_correct), Toast.LENGTH_SHORT).show();
return false;
}
if (mediaItemType == MediaItemType.RADIO) {
StreamUrl streamUrl = new StreamUrl(etMediaUrl.getText().toString());
RadioItem radioItem = new RadioItem(etMediaName.getText().toString(), streamUrl, ""); | ProfileManager.getInstance().addSubscribedMediaItem(radioItem); | 0 |
andraus/BluetoothHidEmu | src/andraus/bluetoothhidemu/settings/Settings.java | [
"public class BluetoothHidEmuActivity extends Activity {\n\t\n\tpublic static String TAG = \"BluetoothHidEmu\";\n\t\n private static final int HANDLER_MONITOR_SOCKET = 0;\n private static final int HANDLER_CONNECT = 1;\n private static final int HANDLER_BLUETOOTH_ENABLED = 2;\n\n\tprivate boolean mDisableB... | import java.util.Set;
import andraus.bluetoothhidemu.BluetoothHidEmuActivity;
import andraus.bluetoothhidemu.R;
import andraus.bluetoothhidemu.spoof.Spoof;
import andraus.bluetoothhidemu.spoof.Spoof.SpoofMode;
import andraus.bluetoothhidemu.util.DoLog;
import andraus.bluetoothhidemu.view.BluetoothDeviceView;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager; |
super.onActivityResult(requestCode, resultCode, data);
}
/**
* getEmulationMode
*
* @param context
* @return
*/
public static SpoofMode getPrefEmulationMode(Context context) {
int value = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_EMULATION_MODE, "-1"));
return Spoof.fromInt(value);
}
/**
* getLastConnectedDevice
*
* @param context
* @return
*/
public static String getLastConnectedDevice(Context context) {
String value = PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_LAST_DEVICE, null);
return value;
}
/**
* setLastDevice
*
* @param context
* @param value
*/
public static void setLastDevice(Context context, String value) {
savePref(context, PREF_LAST_DEVICE, value);
}
/**
* Returns emulation mode for the specified device
*
* @param context
* @param device
* @return
*/
public static SpoofMode getEmulationMode(Context context, BluetoothDevice device) {
SharedPreferences devicesPref = context.getSharedPreferences(Settings.FILE_PREF_DEVICES, Context.MODE_PRIVATE);
SpoofMode mode = Spoof.fromInt(devicesPref.getInt(device.getAddress(), Spoof.intValue(SpoofMode.INVALID)));
return mode;
}
/**
* Store emulation mode for the paired device as a shared preference
*
* @param context
* @param device
*/
public static void storeDeviceEmulationMode(Context context, BluetoothDevice device, SpoofMode spoofMode) {
SharedPreferences devicesPref = context.getSharedPreferences(Settings.FILE_PREF_DEVICES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = devicesPref.edit();
editor.putInt(device.getAddress(), Spoof.intValue(spoofMode));
editor.apply();
}
/**
* savePref
*
* @param context
* @param key
* @param value
*/
private static void savePref(Context context, String key, String value) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.apply();
}
/**
* getEmulationModeSummary
*
* @param modeIndex
*/
public static String getEmulationModeSummary(Context context, int modeIndex) {
String[] modeNames = context.getResources().getStringArray(R.array.emulation_mode_names);
return modeNames[modeIndex];
}
/**
* Toggle state for Bluetooth discoverable item
* @param state
*/
private void setBluetoothDiscoverableCheck(boolean state) {
mBtDiscoverablePreference.setChecked(state);
mBtDiscoverablePreference.setEnabled(!state);
mEmulationModeListPreference.setEnabled(!state);
if (!state) {
mBtDiscoverablePreference.setSummary(getResources().getString(R.string.msg_pref_summary_bluetooth_discoverable_click));
}
}
/**
*
*/
private void populateDeviceList(PreferenceCategory deviceListCategory) {
deviceListCategory.removeAll();
Set<BluetoothDevice> deviceSet = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
for (BluetoothDevice device: deviceSet) {
Preference devicePref = new Preference(this);
devicePref.setTitle(device.getName().equals("") ? device.getAddress() : device.getName());
| BluetoothDeviceView.isBluetoothDevicePs3(device); | 4 |
jaychang0917/SimpleRecyclerView | app/src/main/java/com/jaychang/demo/srv/SwipeToDismissActivity.java | [
"public class BookCell extends SimpleCell<Book, BookCell.ViewHolder>\n implements Updatable<Book> {\n\n private static final String KEY_TITLE = \"KEY_TITLE\";\n private boolean showHandle;\n\n public BookCell(Book item) {\n super(item);\n }\n\n @Override\n protected int getLayoutRes() {\n return R.layo... | import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.jaychang.demo.srv.cell.BookCell;
import com.jaychang.demo.srv.cell.NumberCell;
import com.jaychang.demo.srv.model.Book;
import com.jaychang.demo.srv.util.DataUtils;
import com.jaychang.srv.SimpleCell;
import com.jaychang.srv.SimpleRecyclerView;
import com.jaychang.srv.behavior.SwipeToDismissCallback;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.jaychang.srv.behavior.SwipeDirection.DOWN;
import static com.jaychang.srv.behavior.SwipeDirection.LEFT;
import static com.jaychang.srv.behavior.SwipeDirection.RIGHT;
import static com.jaychang.srv.behavior.SwipeDirection.UP; | package com.jaychang.demo.srv;
public class SwipeToDismissActivity extends BaseActivity {
@BindView(R.id.linearVerRecyclerView)
SimpleRecyclerView linearVerRecyclerView;
@BindView(R.id.linearHorRecyclerView)
SimpleRecyclerView linearHorRecyclerView;
@BindView(R.id.resultView)
TextView resultView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_to_dismiss);
ButterKnife.bind(this);
init();
bindBooks(linearVerRecyclerView);
bindNumbers(linearHorRecyclerView);
}
private void init() { | SwipeToDismissCallback<Book> bookCallback = new SwipeToDismissCallback<Book>() { | 6 |
maofw/anetty_client | src/com/netty/client/context/ApplicationContextClient.java | [
"public class Device {\n\n private Long id;\n private String appKey;\n private String deviceId;\n private String imei;\n private String appPackage;\n private String regId;\n private Integer isOnline;\n\n public Device() {\n }\n\n public Device(Long id) {\n this.id = id;\n }\n... | import io.netty.channel.ChannelHandlerContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.netty.client.android.dao.Device;
import com.netty.client.android.handler.NettyProcessorHandler;
import com.netty.client.android.listener.INettyHandlerListener;
import com.netty.client.android.listener.RegistrationResultListener;
import com.netty.client.android.service.PushDbService;
import com.netty.client.consts.SystemConsts;
import com.netty.client.utils.Md5Util;
import com.xwtec.protoc.CommandProtoc; | package com.netty.client.context;
/**
* 客户端调用
*
* @author maofw
*
*/
public class ApplicationContextClient {
// 设备在线状态
public static final int DEVICE_ONLINE = 1;
public static final int DEVICE_OFFLINE = 0;
// 是否关闭状态
public static boolean isClosed = false;
private ChannelHandlerContext ctx;
private Map<String, Device> deviceInfos = new HashMap<String, Device>();
// 保存handler 回调Listener
@SuppressWarnings("rawtypes") | private Map<String, Map<Integer, INettyHandlerListener>> nettyHandlerListeners = new HashMap<String, Map<Integer, INettyHandlerListener>>(); | 2 |
endercrest/VoidSpawn | src/main/java/com/endercrest/voidspawn/commands/OptionCommand.java | [
"public class DetectorManager {\n\n private static DetectorManager instance = new DetectorManager();\n\n public static DetectorManager getInstance() {\n return instance;\n }\n\n private Detector defaultDetector;\n private HashMap<String, Detector> detectors;\n\n /**\n * Setup the Detect... | import com.endercrest.voidspawn.DetectorManager;
import com.endercrest.voidspawn.ModeManager;
import com.endercrest.voidspawn.VoidSpawn;
import com.endercrest.voidspawn.detectors.Detector;
import com.endercrest.voidspawn.modes.Mode;
import com.endercrest.voidspawn.options.Option;
import com.endercrest.voidspawn.utils.MessageUtil;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; | package com.endercrest.voidspawn.commands;
public class OptionCommand implements SubCommand {
private static final List<String> actionOptions = new ArrayList<>() {{
add("clear");
add("set");
}};
@Override
public boolean onCommand(Player p, String[] args) {
if (args.length == 1) { | p.sendMessage(MessageUtil.colorize(VoidSpawn.prefix + "Specify either '&6set&f' or '&6clear&f'.")); | 2 |
oSoc14/Artoria | app/src/main/java/be/artoria/belfortapp/mixare/plugin/remoteobjects/RemoteDataHandler.java | [
"public class POI {\n\n\n private static final int BOAT = 0;\n private static final int CIVIL = 1;\n private static final int RELIGIOUS = 2;\n private static final int TOWER = 3;\n private static final int THEATRE = 4;\n private static final int CASTLE = 5;\n private static final int... | import be.artoria.belfortapp.mixare.lib.marker.Marker;
import be.artoria.belfortapp.mixare.lib.marker.draw.ParcelableProperty;
import be.artoria.belfortapp.mixare.lib.marker.draw.PrimitiveProperty;
import be.artoria.belfortapp.mixare.lib.service.IDataHandlerService;
import be.artoria.belfortapp.mixare.plugin.PluginLoader;
import be.artoria.belfortapp.mixare.plugin.PluginNotFoundException;
import android.os.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.json.JSONException;
import be.artoria.belfortapp.app.POI;
import be.artoria.belfortapp.mixare.data.DataHandler;
import be.artoria.belfortapp.mixare.data.convert.DataProcessor;
import be.artoria.belfortapp.mixare.lib.marker.InitialMarkerData; | /*
* Copyright (C) 2012- Peer internet solutions & Finalist IT Group
*
* This file is part of be.artoria.belfortapp.mixare.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*/
package be.artoria.belfortapp.mixare.plugin.remoteobjects;
public class RemoteDataHandler extends DataHandler implements DataProcessor {
private String dataHandlerName;
private IDataHandlerService iDataHandlerService;
public String getDataHandlerName() {
return dataHandlerName;
}
public RemoteDataHandler(IDataHandlerService iDataHandlerService) {
this.iDataHandlerService = iDataHandlerService;
}
public void buildDataHandler(){
try {
this.dataHandlerName = iDataHandlerService.build();
} catch (RemoteException e) {
throw new PluginNotFoundException(e);
}
}
public String[] getUrlMatch() {
try {
return iDataHandlerService.getUrlMatch(dataHandlerName);
} catch (RemoteException e) {
throw new PluginNotFoundException(e);
}
}
public String[] getDataMatch() {
try {
return iDataHandlerService.getDataMatch(dataHandlerName);
} catch (RemoteException e) {
throw new PluginNotFoundException(e);
}
}
@Override
public boolean matchesRequiredType(String type) {
//TODO: change the datasource so that it can have more types,
// so that plugins can also have a required type
return true;
}
public List<Marker> load(List<POI> rawData, int taskId, int colour) {
try {
List<InitialMarkerData> initialMarkerData = iDataHandlerService.load(dataHandlerName, "TODO FIX WHAT IS THIS?????", taskId, colour);
return initializeMarkerData(initialMarkerData);
} catch (RemoteException e) {
throw new PluginNotFoundException(e);
}
}
private List<Marker> initializeMarkerData(List<InitialMarkerData> initialMarkerData) throws PluginNotFoundException, RemoteException{
List<Marker> markers = new ArrayList<Marker>();
for(InitialMarkerData i : initialMarkerData){
Marker marker = PluginLoader.getInstance().getMarkerInstance(i.getMarkerName(), (Integer)i.getConstr()[0],
(String)i.getConstr()[1], (Double)i.getConstr()[2], (Double)i.getConstr()[3],
(Double)i.getConstr()[4], (String)i.getConstr()[5], (Integer)i.getConstr()[6], (Integer)i.getConstr()[7]);
fillExtraMarkerParcelableProperties(marker, i.getExtraParcelables());
fillExtraMarkerPrimitiveProperties(marker, i.getExtraPrimitives());
markers.add(marker);
}
return markers;
}
| private Marker fillExtraMarkerParcelableProperties(Marker marker, Map<String, ParcelableProperty> properties){ | 5 |
bencvt/LibShapeDraw | projects/demos/src/main/java/mod_LibShapeDrawDemos.java | [
"public class ApiInfo {\n public static String getName() {\n return getInstance().name;\n }\n public static String getVersion() {\n return getInstance().version;\n }\n public static boolean isVersionAtLeast(String minVersion) {\n if (minVersion == null) {\n throw new I... | import java.awt.Desktop;
import java.net.URI;
import libshapedraw.ApiInfo;
import libshapedraw.LibShapeDraw;
import libshapedraw.event.LSDEventListener;
import libshapedraw.event.LSDGameTickEvent;
import libshapedraw.event.LSDPreRenderEvent;
import libshapedraw.event.LSDRespawnEvent;
import libshapedraw.primitive.Color;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Keyboard; |
/**
* Quick-and-dirty ModLoader mod that loads demos that the user selects.
* <p>
* The demos themselves are actually ModLoader mods too in all but name:
* they're located outside of the root package so that this class can load
* them on demand.
*/
public class mod_LibShapeDrawDemos extends BaseMod implements LSDEventListener {
public static final String SOURCE_URI_DISPLAY = "https://github.com/bencvt/LibShapeDraw";
public static final URI SOURCE_URI = URI.create("https://github.com/bencvt/LibShapeDraw/tree/master/projects/demos/src/main/java/libshapedraw/demos");
public static final int TEXT_ARGB = Color.WHITE.getARGB();
private static class Demo {
public final int key;
public final String name;
public final String[] about;
public final Class<? extends libshapedraw.demos.BaseMod> modClass;
public libshapedraw.demos.BaseMod modInstance;
@SuppressWarnings("unchecked")
public Demo(int key, String className) {
this.key = key;
name = className;
className = "libshapedraw.demos." + className;
try {
modClass = (Class<? extends libshapedraw.demos.BaseMod>) getClass()
.getClassLoader().loadClass(className);
about = ((String) modClass.getField("ABOUT").get(null)).split("\n");
} catch (Exception e) {
throw new RuntimeException("unable to load demo " + String.valueOf(className), e);
}
}
}
private final Demo[] demos = new Demo[] {
new Demo(Keyboard.KEY_0, "mod_LSDDemoBasic"),
new Demo(Keyboard.KEY_1, "mod_LSDDemoBasicCheckInstall"),
new Demo(Keyboard.KEY_2, "mod_LSDDemoEvents"),
new Demo(Keyboard.KEY_3, "mod_LSDDemoEventsFreeDraw"),
new Demo(Keyboard.KEY_4, "mod_LSDDemoLogo"),
new Demo(Keyboard.KEY_5, "mod_LSDDemoShapeCustom"),
new Demo(Keyboard.KEY_6, "mod_LSDDemoTridentBasic"),
new Demo(Keyboard.KEY_7, "mod_LSDDemoTridentDynamic"),
new Demo(Keyboard.KEY_8, "mod_LSDDemoTridentTimeline"),
};
private final LibShapeDraw libShapeDraw = new LibShapeDraw();
private Minecraft minecraft;
private boolean inMenu;
private boolean canOpenUrl;
private LSDRespawnEvent savedFakeRespawnEvent;
@Override
public String getName() { | return ApiInfo.getName() + " Demos"; | 0 |
teiid/teiid-embedded-examples | embedded-caching/src/main/java/org/teiid/example/TranslatorResultsCachingExample.java | [
"public class H2PERFTESTClient {\n \n static final String INSERT_SQL = \"insert into PERFTEST values(?, ?, ?, ?)\";\n \n public static final int KB = 1<<10;\n public static final int MB = 1<<20;\n public static final int GB = 1<<30;\n \n public static final String H2_JDBC_DRIVER = \"org.h2.D... | import static org.teiid.example.H2PERFTESTClient.*;
import static org.teiid.example.TeiidEmbeddedCaching.println;
import static org.teiid.example.TeiidEmbeddedCaching.prompt;
import static org.teiid.example.util.JDBCUtils.executeQueryCount;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.resource.ResourceException;
import javax.sql.DataSource;
import org.teiid.deployers.VirtualDatabaseException;
import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository.ConnectorManagerException;
import org.teiid.example.EmbeddedHelper;
import org.teiid.example.util.JDBCUtils;
import org.teiid.example.util.JDBCUtils.Entity;
import org.teiid.language.Command;
import org.teiid.language.QueryExpression;
import org.teiid.metadata.RuntimeMetadata;
import org.teiid.runtime.EmbeddedConfiguration;
import org.teiid.runtime.EmbeddedServer;
import org.teiid.translator.CacheDirective;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.ResultSetExecution;
import org.teiid.translator.TranslatorException;
import org.teiid.translator.jdbc.h2.H2ExecutionFactory; | /*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teiid.example;
public class TranslatorResultsCachingExample {
static EmbeddedServer server = null;
static Connection conn = null;
static class TestH2ExecutionFactory extends H2ExecutionFactory {
@Override
public ResultSetExecution createResultSetExecution(
QueryExpression command, ExecutionContext executionContext,
RuntimeMetadata metadata, Connection conn)
throws TranslatorException {
CacheDirective cacheDirective = this.getCacheDirective(command, executionContext, metadata);
cacheDirective.setScope(CacheDirective.Scope.VDB);
cacheDirective.setPrefersMemory(true);
cacheDirective.setReadAll(true);
cacheDirective.setTtl(120000L);
cacheDirective.setUpdatable(true);
return super.createResultSetExecution(command, executionContext, metadata, conn);
}
@Override
public CacheDirective getCacheDirective(Command command,
ExecutionContext executionContext, RuntimeMetadata metadata)
throws TranslatorException {
return new CacheDirective();
}
}
static void startup() throws TranslatorException, VirtualDatabaseException, ConnectorManagerException, IOException, SQLException, ResourceException {
server = new EmbeddedServer();
H2ExecutionFactory factory = new TestH2ExecutionFactory();
factory.start();
factory.setSupportsDirectQueryProcedure(true);
server.addTranslator("translator-h2", factory);
DataSource ds = EmbeddedHelper.newDataSource(H2_JDBC_DRIVER, H2_JDBC_URL, H2_JDBC_USER, H2_JDBC_PASS);
server.addConnectionFactory("java:/accounts-ds", ds);
server.start(new EmbeddedConfiguration());
server.deployVDB(TranslatorResultsCachingExample.class.getClassLoader().getResourceAsStream("rsCaching-h2-vdb.xml"));
Properties info = new Properties();
conn = server.getDriver().connect("jdbc:teiid:ResultsCachingH2VDB", info);
}
static void teardown() throws SQLException {
JDBCUtils.close(conn);
server.stop();
}
public static void query(String sql) throws Exception {
startup();
| prompt("Execute '" + sql + "' 10 times, this may need some times"); | 2 |
necr0potenc3/uosl | slclient/src/org/solhost/folko/uosl/slclient/models/GameState.java | [
"public class SLData {\n public static boolean DEBUG_MOVE = false;\n public static final int CHARACHTER_HEIGHT = 10; // height of a character\n private static SLData instance;\n private final String dataPath;\n private SLMap map;\n private SLPalette palette;\n private SLStatics statics;\n pr... | import java.util.List;
import java.util.function.BiConsumer;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.lwjgl.Sys;
import org.solhost.folko.uosl.libuosl.data.SLData;
import org.solhost.folko.uosl.libuosl.data.SLStatic;
import org.solhost.folko.uosl.libuosl.network.SendableItem;
import org.solhost.folko.uosl.libuosl.network.SendableMobile;
import org.solhost.folko.uosl.libuosl.network.SendableObject;
import org.solhost.folko.uosl.libuosl.network.packets.DoubleClickPacket;
import org.solhost.folko.uosl.libuosl.network.packets.LoginPacket;
import org.solhost.folko.uosl.libuosl.network.packets.MoveRequestPacket;
import org.solhost.folko.uosl.libuosl.network.packets.SingleClickPacket;
import org.solhost.folko.uosl.libuosl.network.packets.SpeechRequestPacket;
import org.solhost.folko.uosl.libuosl.types.Direction;
import org.solhost.folko.uosl.libuosl.types.Items;
import org.solhost.folko.uosl.libuosl.types.Point2D;
import org.solhost.folko.uosl.libuosl.types.Point3D; | package org.solhost.folko.uosl.slclient.models;
public class GameState {
public enum State {DISCONNECTED, CONNECTED, LOGGED_IN};
private static final Logger log = Logger.getLogger("slclient.game");
private final ObservableValue<State> state;
private Player player;
private String loginName, loginPassword;
private Connection connection;
private int updateRange = 15;
private final ObjectRegistry objectsInRange;
// Movement
private final int MOVE_DELAY = 150;
private short nextMoveSequence, lastAckedMoveSequence;
private long lastMoveTime;
public GameState() {
state = new ObservableValue<>(State.DISCONNECTED);
objectsInRange = new ObjectRegistry();
log.fine("Game state initialized");
}
public void setLoginDetails(String name, String password) {
this.loginName = name;
this.loginPassword = password;
}
public State getState() {
return state.getValue();
}
public void addStateListener(BiConsumer<State, State> listener) {
state.addObserver(listener);
}
public void removeStateListener(BiConsumer<State, State> listener) {
state.removeObserver(listener);
}
public void onConnect(Connection connection) {
this.connection = connection;
state.setValue(State.CONNECTED);
}
public void onDisconnect() {
this.connection = null;
state.setValue(State.DISCONNECTED);
}
public void tryLogin() {
LoginPacket login = new LoginPacket();
login.setName(loginName);
login.setPassword(loginPassword);
login.setSeed(LoginPacket.LOGIN_BY_NAME);
login.setSerial(LoginPacket.LOGIN_BY_NAME);
login.prepareSend();
connection.sendPacket(login);
}
| public void onLoginSuccess(long serial, int graphic, Point3D location, Direction facing) { | 5 |
ParaskP7/sample-code-posts | app/src/test/java/io/petros/posts/GeneralTestHelper.java | [
"public class Datastore {\n\n private final DatastoreSaveActions datastoreSaveActions;\n private final DatastoreAddActions datastoreAddActions;\n private final DatastoreGetActions datastoreGetActions;\n private final DatastoreUpdateActions datastoreUpdateActions;\n\n public Datastore(final DatastoreS... | import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
import io.petros.posts.datastore.Datastore;
import io.petros.posts.datastore.DatastoreAddActions;
import io.petros.posts.datastore.DatastoreGetActions;
import io.petros.posts.datastore.DatastoreSaveActions;
import io.petros.posts.datastore.DatastoreUpdateActions;
import io.petros.posts.model.Comment;
import io.petros.posts.model.Post;
import io.petros.posts.model.User;
import io.petros.posts.util.rx.RxSchedulers;
import io.reactivex.schedulers.Schedulers;
import static org.mockito.Mockito.when; | package io.petros.posts;
public class GeneralTestHelper {
// RxJava specific fields.
protected RxSchedulers rxSchedulers = getTestRxSchedulers();
protected Throwable observableErrorThrowable = new RuntimeException("Test emulated error!");
// Datastore specific fields.
@Mock protected Datastore datastoreMock;
@Mock protected DatastoreSaveActions datastoreSaveActionsMock;
@Mock protected DatastoreAddActions datastoreAddActionsMock; | @Mock protected DatastoreGetActions datastoreGetActionsMock; | 2 |
NessComputing/components-ness-httpclient | client/src/test/java/com/nesscomputing/httpclient/TestAlwaysTrustServerSSLCert.java | [
"public final class HttpClient implements Closeable\n{\n private final HttpClientFactory httpClientFactory;\n\n /**\n * Creates a new HTTP client with the default implementation (currently Apache HTTPClient 4) and default settings.\n */\n public HttpClient()\n {\n this(new HttpClientDefau... | import javax.net.ssl.SSLPeerUnverifiedException;
import java.io.IOException;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.nesscomputing.httpclient.HttpClient;
import com.nesscomputing.httpclient.HttpClientDefaults;
import com.nesscomputing.httpclient.HttpClientResponseHandler;
import com.nesscomputing.httpclient.response.ContentResponseHandler;
import com.nesscomputing.httpclient.testsupport.GenericTestHandler;
import com.nesscomputing.httpclient.testsupport.LocalHttpService;
import com.nesscomputing.httpclient.testsupport.StringResponseConverter;
import com.nesscomputing.testing.lessio.AllowNetworkAccess; | /**
* Copyright (C) 2012 Ness Computing, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nesscomputing.httpclient;
@AllowNetworkAccess(endpoints={"127.0.0.1:*"})
public class TestAlwaysTrustServerSSLCert {
private HttpClientResponseHandler<String> responseHandler =
new ContentResponseHandler<String>(new StringResponseConverter());
protected HttpClient httpClient = null;
private LocalHttpService localHttpService;
@Before
public void setUp() {
localHttpService = LocalHttpService.forSSLHandler(new GenericTestHandler());
localHttpService.start();
}
@After
public void tearDown() {
Assert.assertNotNull(httpClient);
httpClient.close();
httpClient = null;
}
@Test
public void testWithServerCertVerificationEnabled() throws IOException {
| final HttpClientDefaults defaults = getDefaults(true); | 1 |
jeffprestes/brasilino | android/Brasilino/app/src/main/java/com/paypal/developer/brasilino/PermissionActivity.java | [
"public class CarrinhoApplication extends Application {\n private static final String UNBIND_FLAG = \"UNBIND_FLAG\";\n\n private CandieSQLiteDataSource dataSource;\n private static CarrinhoApplication app;\n\n private RequestQueue queue;\n\n @Override\n public void onCreate() {\n super.onCr... | import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.paypal.developer.brasilino.application.CarrinhoApplication;
import com.paypal.developer.brasilino.database.CandieSQLiteDataSource;
import com.paypal.developer.brasilino.domain.Token;
import com.paypal.developer.brasilino.domain.User;
import com.paypal.developer.brasilino.service.PaymentService;
import com.paypal.developer.brasilino.util.CandiesWebViewClient;
import com.paypal.developer.brasilino.util.Util;
import com.paypal.developer.brasilino.util.WebServerHelper; | package com.paypal.developer.brasilino;
public class PermissionActivity extends ActionBarActivity {
private WebView webContent;
private ProgressBar progress;
private Bundle receivedExtras;
private Token token;
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (receivedExtras != null)
outState.putAll(receivedExtras);
}
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission);
NotificationManagerCompat.from(getApplicationContext()).cancel(Util.NOTIFICATION_ID);
if (savedInstanceState != null)
receivedExtras = savedInstanceState;
| final CandieSQLiteDataSource dataSource = CarrinhoApplication.getDatasource(); | 0 |
gavioto/portecle | src/main/net/sf/portecle/DViewCertificate.java | [
"public static final ResourceBundle RB = ResourceBundle.getBundle(RB_BASENAME);",
"public enum DigestType\n{\n /** MD5 Digest Type */\n\tMD5,\n\t/** SHA-1 Digest Type */\n\tSHA1;\n}",
"public enum SignatureType\n{\n /** MD2 with RSA Signature Type */\n\tMD2withRSA(PKCSObjectIdentifiers.md2WithRSAEncryptio... | import static net.sf.portecle.FPortecle.RB;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import net.sf.portecle.crypto.CryptoException;
import net.sf.portecle.crypto.DigestType;
import net.sf.portecle.crypto.DigestUtil;
import net.sf.portecle.crypto.KeyPairUtil;
import net.sf.portecle.crypto.SignatureType;
import net.sf.portecle.crypto.X509CertUtil;
import net.sf.portecle.gui.SwingHelper;
import net.sf.portecle.gui.crypto.DViewPEM;
import net.sf.portecle.gui.error.DThrowable; | /*
* DViewCertificate.java
* This file is part of Portecle, a multipurpose keystore and certificate tool.
*
* Copyright © 2004 Wayne Grant, waynedgrant@hotmail.com
* 2004-2008 Ville Skyttä, ville.skytta@iki.fi
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.sf.portecle;
/**
* Modal dialog to display the details of one or more X.509 certificates. The details of one certificate are displayed
* at a time with selector buttons allowing the movement to another of the certificates.
*/
class DViewCertificate
extends PortecleJDialog
{
/** Move left selector button */
private JButton m_jbLeft;
/** Move right selector button */
private JButton m_jbRight;
/** Selection status label */
private JLabel m_jlSelector;
/** Certificate version text field */
private JTextField m_jtfVersion;
/** Certificate Subject text field */
private JTextField m_jtfSubject;
/** Certificate Issuer text field */
private JTextField m_jtfIssuer;
/** Certificate Serial Number text field */
private JTextField m_jtfSerialNumber;
/** Certificate Valid From text field */
private JTextField m_jtfValidFrom;
/** Certificate Valid Until text field */
private JTextField m_jtfValidUntil;
/** Certificate Public Key text field */
private JTextField m_jtfPublicKey;
/** Certificate Signature Algorithm text field */
private JTextField m_jtfSignatureAlgorithm;
/** Certificate MD5 Fingerprint text field */
private JTextField m_jtfMD5Fingerprint;
/** Certificate SHA-1 Fingerprint text field */
private JTextField m_jtfSHA1Fingerprint;
/** SSL/TLS connection protocol text field */
private JTextField m_jtfProtocol;
/** SSL/TLS connection cipher suite text field */
private JTextField m_jtfCipherSuite;
/** Button used to display the certificate's extensions */
private JButton m_jbExtensions;
/** Stores certificate(s) to display */
private final X509Certificate[] m_certs;
/** The currently selected certificate */
private int m_iSelCert;
/** SSL/TLS connection protocol */
private final String m_connectionProtocol;
/** SSL/TLS connection cipher suite */
private final String m_connectionCipherSuite;
/**
* Creates new DViewCertificate dialog.
*
* @param parent Parent window
* @param sTitle The dialog title
* @param certs Certificate(s) chain to display
* @throws CryptoException A problem was encountered getting the certificates' details
*/
public DViewCertificate(Window parent, String sTitle, X509Certificate[] certs)
throws CryptoException
{
this(parent, sTitle, certs, null, null);
}
/**
* Creates new DViewCertificate dialog.
*
* @param parent Parent window
* @param sTitle The dialog title
* @param certs Certificate(s) chain to display
* @param connectionProtocol SSL/TLS connection protocol
* @param connectionCipherSuite SSL/TLS connection cipher suite
* @throws CryptoException A problem was encountered getting the certificates' details
*/
public DViewCertificate(Window parent, String sTitle, X509Certificate[] certs, String connectionProtocol,
String connectionCipherSuite)
throws CryptoException
{
super(parent, sTitle, true);
m_certs = certs;
m_connectionProtocol = connectionProtocol;
m_connectionCipherSuite = connectionCipherSuite;
initComponents();
}
/**
* Create, show, and wait for a new DViewCertificate dialog.
*
* @param parent Parent window
* @param url URL, URI or file to load CRL from
*/
public static boolean showAndWait(Window parent, Object url)
{
ArrayList<Exception> exs = new ArrayList<>();
X509Certificate[] certs;
try
{ | certs = X509CertUtil.loadCertificates(NetUtil.toURL(url), exs); | 3 |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/views/hologram/HoloPopup.java | [
"public class SMSException extends DHUtilsException {\n\n private static final long serialVersionUID = 1L;\n\n public SMSException(String message) {\n super(message);\n }\n\n}",
"public class SMSMenu extends Observable implements SMSPersistable, SMSUseLimitable, ConfigurationListener, Comparable<S... | import com.dsh105.holoapi.HoloAPI;
import com.dsh105.holoapi.api.Hologram;
import com.dsh105.holoapi.api.HologramFactory;
import com.dsh105.holoapi.api.touch.Action;
import com.dsh105.holoapi.api.touch.TouchAction;
import com.dsh105.holoapi.api.visibility.Visibility;
import me.desht.dhutils.Debugger;
import me.desht.dhutils.MiscUtil;
import me.desht.scrollingmenusign.SMSException;
import me.desht.scrollingmenusign.SMSMenu;
import me.desht.scrollingmenusign.ScrollingMenuSign;
import me.desht.scrollingmenusign.enums.SMSUserAction;
import me.desht.scrollingmenusign.views.SMSPopup;
import me.desht.scrollingmenusign.views.SMSPrivateHoloView;
import me.desht.scrollingmenusign.views.SMSView;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.LinkedHashMap; | package me.desht.scrollingmenusign.views.hologram;
public class HoloPopup implements SMSPopup {
private static final double POPUP_DISTANCE = 2.5;
private final SMSPrivateHoloView view;
private final Player player;
private Hologram hologram = null;
public HoloPopup(Player player, SMSPrivateHoloView view) {
this.view = view;
this.player = player;
}
@Override
public SMSView getView() {
return view;
}
public Player getPlayer() {
return player;
}
@Override
public void repaint() {
String[] text = HoloUtil.buildText(view, player, (Integer) view.getAttribute(SMSPrivateHoloView.LINES));
if (text.length != hologram.getLines().length) {
popdown(); // force a new hologram to be created with the new size
}
if (hologram == null) {
hologram = buildHologram(player, text);
} else {
// hologram.updateLines(text);
HoloAPI.getManager().setLineContent(hologram, text);
}
}
@Override
public boolean isPoppedUp() {
return hologram != null;
}
@Override
public void popup() {
String[] text = HoloUtil.buildText(view, player, (Integer) view.getAttribute(SMSPrivateHoloView.LINES));
hologram = buildHologram(player, text);
}
@Override
public void popdown() {
if (hologram != null) {
HoloAPI.getManager().stopTracking(hologram);
hologram = null;
}
}
public Hologram getHologram() {
return hologram;
}
private Hologram buildHologram(Player player, String[] text) {
Debugger.getInstance().debug("creating new private hologram for " + view.getName() + "/" + player.getName());
Hologram h = new HologramFactory(ScrollingMenuSign.getInstance())
.withLocation(getHologramPosition(player))
.withText(text)
.withSimplicity(true)
.withVisibility(new HologramVisibility(player))
.build();
h.addTouchAction(new SMSHoloTouchAction(player, view));
h.setTouchEnabled(true);
return h;
}
private Location getHologramPosition(Player player) {
return player.getEyeLocation().add(player.getLocation().getDirection().multiply(POPUP_DISTANCE));
}
private class HologramVisibility implements Visibility {
private final Player player;
public HologramVisibility(Player player) {
this.player = player;
}
@Override
public boolean isVisibleTo(Player player, String s) {
return this.player.equals(player);
}
@Override
public String getSaveKey() {
return null;
}
@Override
public LinkedHashMap<String, Object> getDataToSave() {
return null;
}
}
private class SMSHoloTouchAction implements TouchAction {
private final SMSPrivateHoloView view;
private final Player player;
private SMSHoloTouchAction(Player player, SMSPrivateHoloView view) {
this.view = view;
this.player = player;
}
@Override
public void onTouch(Player player, Action action) {
if (player.equals(this.player)) {
Debugger.getInstance().debug("Hologram action: player=" + player.getName() + " action=" + action + " view = " + view.getName()); | SMSUserAction ua = getAction(player, action); | 3 |
Zahlii/Advanced-Youtube-Downloader | Advanced-Youtube-Download/src/de/zahlii/youtube/download/step/StepConvert.java | [
"public class QueueEntry extends Thread {\r\n\r\n\tprivate static boolean enableGracenote;\r\n\r\n\tprivate static boolean enableSilence;\r\n\r\n\tprivate static boolean enableVolume;\r\n\r\n\tpublic static void setEnableGracenote(final boolean enableGracenote) {\r\n\t\tQueueEntry.enableGracenote = enableGracenote;... | import java.io.File;
import java.util.ArrayList;
import java.util.List;
import de.zahlii.youtube.download.QueueEntry;
import de.zahlii.youtube.download.basic.ConfigManager;
import de.zahlii.youtube.download.basic.ConfigManager.ConfigKey;
import de.zahlii.youtube.download.basic.Logging;
import de.zahlii.youtube.download.cli.CLI;
| package de.zahlii.youtube.download.step;
public class StepConvert extends Step {
public StepConvert(final QueueEntry entry) {
super(entry, new StepDescriptor("FileConvert", "Converts the downloaded file while applying the defined filters and effects on it"));
}
@Override
public void doStep() {
// not necessary
final boolean hasSilenceStart = entry.getStepInfo().containsKey("silence.start") && (boolean) entry.getStepInfo().get("silence.start");
final boolean hasSilenceEnd = entry.getStepInfo().containsKey("silence.end") && (boolean) entry.getStepInfo().get("silence.end");
final boolean sameFile = entry.getDownloadTempFile().getName().equals(entry.getConvertTempFile().getName());
final boolean hasVolume = entry.getStepInfo().containsKey("volume.level");
if (!hasSilenceStart && !hasSilenceEnd && sameFile && !hasVolume) {
| Logging.log("Skipping conversion");
| 3 |
mpostelnicu/wicket-spring-jpa-bootstrap-boilerplate | web/src/main/java/org/sample/web/pages/lists/AbstractListPage.java | [
"public final class WebConstants {\r\n\tpublic static final int PAGE_SIZE=10;\r\n}\r",
"public class SortableJpaRepositoryDataProvider<T extends AbstractPersistable<Long>>\r\n\t\textends SortableDataProvider<T, String> {\r\n\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tprotected JpaRepository<T,... | import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.extensions.ajax.markup.html.repeater.data.table.AjaxFallbackDefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sample.web.app.WebConstants;
import org.sample.web.components.providers.datatable.SortableJpaRepositoryDataProvider;
import org.sample.web.exceptions.NullEditPageClassException;
import org.sample.web.exceptions.NullJpaRepositoryException;
import org.sample.web.pages.HeaderFooter;
import org.sample.web.pages.edits.AbstractEditPage;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.domain.AbstractPersistable;
import org.springframework.data.jpa.repository.JpaRepository;
| /**
*
*/
package org.sample.web.pages.lists;
/**
* @author mpostelnicu
*
*/
public abstract class AbstractListPage<T extends AbstractPersistable<Long>> extends HeaderFooter {
private class ActionPanel extends Panel {
private static final long serialVersionUID = 1L;
/**
* @param id
* component id
* @param model
* model for contact
*/
public ActionPanel(String id, IModel<T> model) {
super(id, model);
add(new Link<T>("edit") {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
@Override
public void onClick() {
setEditResponsePage((T) ActionPanel.this.getDefaultModelObject());
}
});
}
}
protected void setEditResponsePage(T entity) {
PageParameters pageParameters = new PageParameters();
if(entity!=null) pageParameters.set(AbstractEditPage.PARAM_ID,entity.getId());
setResponsePage(editPageClass, pageParameters);
}
protected Class<? extends AbstractEditPage<T>> editPageClass;
private static final long serialVersionUID = 1L;
protected AjaxFallbackDefaultDataTable<T, String> dataTable;
protected List<IColumn<T, String>> columns;
@SpringBean
protected Environment environment;
protected JpaRepository<T, Long> jpaRepository;
public AbstractListPage() {
add(createPageTitleTag("list.title"));
add(createPageHeading("list.heading"));
add(createPageMessage("list.message"));
columns = new ArrayList<IColumn<T, String>>();
columns.add(new PropertyColumn<T, String>(new Model<String>("ID"), "id"));
add(new Link<T>("new") {
private static final long serialVersionUID = 1L;
@Override
public void onClick() {
setEditResponsePage(null);
}
});
}
@Override
protected void onInitialize() {
super.onInitialize();
if (jpaRepository == null)
throw new NullJpaRepositoryException();
if (editPageClass == null)
| throw new NullEditPageClassException();
| 2 |
pasqualesalza/elephant56 | elephant56/src/main/java/it/unisa/elephant56/user/sample/operators/initialisation/SequenceIndividualRandomInitialisation.java | [
"public class IndividualWrapper<IndividualType extends Individual, FitnessValueType extends FitnessValue>\r\n implements Comparable<IndividualWrapper<IndividualType, FitnessValueType>>, Cloneable {\r\n\r\n private IndividualType individual;\r\n private FitnessValueType fitnessValue;\r\n private Bool... | import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import it.unisa.elephant56.core.common.IndividualWrapper;
import it.unisa.elephant56.core.common.Properties;
import it.unisa.elephant56.user.common.FitnessValue;
import it.unisa.elephant56.user.operators.Initialisation;
import it.unisa.elephant56.user.sample.common.individual.SequenceIndividual;
| package it.unisa.elephant56.user.sample.operators.initialisation;
/**
* Defines an initialisation function that generates sequence individual specifying the set of possible elements.
* <p>
* It needs some properties to be set in the properties object.
*
* @param <IndividualType>
* @param <FitnessValueType>
*/
@SuppressWarnings("rawtypes")
public abstract class SequenceIndividualRandomInitialisation<IndividualType extends SequenceIndividual,
FitnessValueType extends FitnessValue, ElementType>
extends Initialisation<IndividualType, FitnessValueType> {
/**
* Defines if the size is a fixed or a maximum value.
*/
public final static String BOOLEAN_IS_NUMBER_OF_ELEMENTS_RANDOM =
"random_sequence_individual_initialisation.configuration.is_number_of_elements_random.boolean";
public final static String INT_NUMBER_OF_ELEMENTS =
"random_sequence_individual_initialisation.configuration.number_of_elements.int";
public final static String BOOLEAN_REPEAT_ELEMENTS =
"random_sequence_individual_initialisation.configuration.repeat_elements.boolean";
public final static String LONG_RANDOM_SEED =
"random_sequence_individual_initialisation.configuration.random_seed.long";
public final static String BOOLEAN_ADD_ISLAND_NUMBER_TO_RANDOM_SEED =
"random_sequence_individual_initialisation.add_island_number_to_random_seed.boolean";
private static final long DEFAULT_RANDOM_SEED = 0;
private boolean isRandomNumberOfElements;
private Integer numberOfElements;
private boolean repeatElements;
protected Random random;
public SequenceIndividualRandomInitialisation(
Integer islandNumber, Integer totalNumberOfIslands, Properties userProperties, Configuration configuration, Integer populationSize
) {
super(islandNumber, totalNumberOfIslands, userProperties, configuration, populationSize);
this.isRandomNumberOfElements = userProperties.getBoolean(BOOLEAN_IS_NUMBER_OF_ELEMENTS_RANDOM, false);
this.numberOfElements = userProperties.getInt(INT_NUMBER_OF_ELEMENTS, 0);
this.repeatElements = userProperties.getBoolean(BOOLEAN_REPEAT_ELEMENTS, true);
// Creates the random object.
long randomSeed = this.getUserProperties().getLong(LONG_RANDOM_SEED, DEFAULT_RANDOM_SEED);
boolean addIslandNumberToRandomSeed = this.getUserProperties().getBoolean(BOOLEAN_ADD_ISLAND_NUMBER_TO_RANDOM_SEED, false);
long finalRandomSeed = (addIslandNumberToRandomSeed) ? (randomSeed + this.getIslandNumber()) : randomSeed;
this.random = new Random(finalRandomSeed);
}
/**
* Returns the possible elements that an individual can contain.
*
* @return the list of possible elements
*/
protected abstract List<ElementType> getPossibleElements();
/**
* Returns the class of the sequence individual.
*
* @return the class of the sequence individual
*/
protected abstract Class<IndividualType> getSequenceIndividualClass();
@SuppressWarnings("unchecked")
@Override
| public IndividualWrapper<IndividualType, FitnessValueType> generateNextIndividual(int id) {
| 0 |
akjava/html5gwt | src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java | [
"public interface SpeechSynthesisBoundaryListener {\r\npublic void onBoundary(SpeechSynthesisEvent event);\r\n}\r",
"public interface SpeechSynthesisEndListener {\r\npublic void onEnd(SpeechSynthesisEvent event);\r\n}\r",
"public interface SpeechSynthesisErrorListener {\r\npublic void onError(SpeechSynthesisEve... | import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener;
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener;
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener;
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener;
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener;
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener;
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener;
import com.google.gwt.core.client.JavaScriptObject;
| package com.akjava.gwt.html5.client.speechsynthesis;
//TODO support event
public class SpeechSynthesisUtterance extends JavaScriptObject{
protected SpeechSynthesisUtterance(){}
public static final native SpeechSynthesisUtterance create()/*-{
return new $wnd.SpeechSynthesisUtterance();
}-*/;
public static final native SpeechSynthesisUtterance create(String text)/*-{
return new $wnd.SpeechSynthesisUtterance(text);
}-*/;
public final native void setText(String text)/*-{
this.text=text;
}-*/;
public final native void setLang(String lang)/*-{
this.lang=lang;
}-*/;
public final native void setVoiceURI(String voiceURI)/*-{
this.voiceURI=voiceURI;
}-*/;
public final native void setVolume(double volume)/*-{
this.volume=volume;
}-*/;
public final native void setRate(double rate)/*-{
this.rate=rate;
}-*/;
public final native void setPitch(double pitch)/*-{
this.pitch=pitch;
}-*/;
public final native void setVoice(Voice voice)/*-{
this.voice=voice;
}-*/;
public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{
this.onend=function (event) {
listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event);
};
}-*/;
public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{
this.onstart=function (event) {
listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event);
};
}-*/;
public final native void setOnBoundary(SpeechSynthesisBoundaryListener listener)/*-{
this.onboundary=function (event) {
listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener::onBoundary(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event);
};
}-*/;
| public final native void setOnError(SpeechSynthesisErrorListener listener)/*-{
| 2 |
Rowandjj/yitu | Yitu/src/cn/edu/chd/yitu/DrawActivity.java | [
"public class BitmapLruCacheHelper\r\n{\r\n\tprivate static final String TAG = \"BitmapLruCacheHelper\";\r\n\tprivate static BitmapLruCacheHelper instance = new BitmapLruCacheHelper();\r\n\tLruCache<String, Bitmap> cache = null;\r\n\t//µ¥Àý\r\n\tprivate BitmapLruCacheHelper()\r\n\t{\r\n\t\tint maxSize = (int) (Runt... | import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
import cn.edu.chd.utils.BitmapLruCacheHelper;
import cn.edu.chd.utils.BitmapUtils;
import cn.edu.chd.utils.YiUtils;
import cn.edu.chd.values.ApplicationValues;
import cn.edu.chd.view.PaintPreview;
import cn.edu.chd.view.YiDrawView;
import cn.edu.chd.view.YiRotateMenu;
import cn.edu.chd.view.YiRotateMenu.OnMenuItemClickListener;
import com.polites.android.GestureImageView;
| package cn.edu.chd.yitu;
/**
*
*»Í¼
*/
public class DrawActivity extends Activity implements android.view.View.OnClickListener,OnSeekBarChangeListener
{
private static final String TAG = "DrawActivity";
/**
* »²¼¿í
*/
private int canvas_width;
/**
* »²¼¸ß
*/
private int canvas_height;
private YiDrawView dv_canvas = null;
/**
* ¹¦Äܲ˵¥
*/
private YiRotateMenu mRotateMenu = null;
/**
* ÎÞ¼«ä¯ÀÀ°´Å¥
*/
private ImageView iv_browser = null;
/**
* ͼԪ¸´Öư´Å¥
*/
private ImageView iv_copy = null;
/**
* ͼԪճÌù°´Å¥
*/
private ImageView iv_paste = null;
/**
*ͼԪ·Å´ó
*/
private ImageView iv_tuyuan_large = null;
/**
* ͼԪËõС
*/
private ImageView iv_tuyuan_small = null;
/**
* ͼԪ×óÐý
*/
private ImageView iv_tuyuan_rotate_left = null;
/**
* ͼԪÓÒÐý
*/
private ImageView iv_tuyuan_rotate_right = null;
private FrameLayout fl_change = null;
private GestureImageView mGestureImageView = null;
/**
* µ±Ç°Ä£Ê½(»æÍ¼/ÎÞ¼«ä¯ÀÀ¡¢Ëõ·Å)
*/
private boolean isPaintMode = true;
/**
* Îļþ±£´æÎ»ÖÃ
*/
private File file = new File(YiUtils.getPath(),YiUtils.getCurrentDate()+".jpg");
/**
* ±³¾°Í¼
*/
private Bitmap background_pic = null;
/**
* ÆÁÄ»¿í¸ß
*/
private int screenWidth;
private int screenHeight;
/**
* ±³¾°Í¼Æ¬µÄλÖÃ
*/
private String bgPath = null;
private PopupWindow mPopupWindow_pen = null;
private PopupWindow mPoputWindow_color = null;
/*ÑÕÉ«°´Å¥*/
private ImageView iv_color1 = null;
private ImageView iv_color2 = null;
private ImageView iv_color3 = null;
private ImageView iv_color4 = null;
private ImageView iv_color5 = null;
private ImageView iv_color6 = null;
private ImageView iv_color7 = null;
private ImageView iv_color8 = null;
private ImageView iv_color9 = null;
/*»±Ê°´Å¥*/
private ImageView iv_pen1 = null;
private ImageView iv_pen2 = null;
private ImageView iv_pen3 = null;
private ImageView iv_pen4 = null;
/*ͼԪ*/
private ImageView tuyuan_bezier = null;
private ImageView tuyuan_shouhui = null;
private ImageView tuyuan_cicle = null;
private ImageView tuyuan_line = null;
private ImageView tuyuan_polygon = null;
private ImageView tuyuan_square = null;
private ImageView tuyuan_zhexian = null;
private PaintPreview ppView = null;
/*¿ØÖÆ»±Ê´óСÓë͸Ã÷¶È*/
private SeekBar sb_pen_size = null;
private SeekBar sb_pen_alpha = null;
/*ÑÕÉ«µÄARGBÖµ*/
private static final int[] colors = {
0xFFDE5510,0xFF21AAE7,
0xFFA51410,0xFF008242,
0xFFFF415A,0xFFFFBA00,
0xFF9C71EF,0xFF638A08,
0xFF000000
};
/**
* ´«¸ÐÆ÷¹ÜÀí
*/
public SensorManager mSensorManager = null;
/**
* ´«¸ÐÆ÷»Øµ÷½Ó¿Ú
*/
public SensorEventListener mSensorListener = null;
/**
* ¼ÓËÙ¶È´«¸ÐÆ÷
*/
public Sensor mAccSensor = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_draw);
bgPath = getIntent().getStringExtra(ApplicationValues.Base.IMAGE_STORE_PATH);
initConfiguration();
initComponent();
initPenAndTuyuanWindow();
initColorWindow();
initSensor();
}
@Override
protected void onResume()
{
super.onResume();
//×¢²á´«¸ÐÆ÷»Øµ÷ʼþ
mSensorManager.registerListener(mSensorListener, mAccSensor, SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop()
{
super.onStop();
//½â°ó´«¸ÐÆ÷
mSensorManager.unregisterListener(mSensorListener, mAccSensor);
}
@Override
protected void onDestroy()
{
//Ïú»Ùbitmap
super.onDestroy();
if(background_pic != null)
{
background_pic.recycle();
background_pic = null;
}
//ɾ³ýÁÙʱÎļþ
String type = getIntent().getStringExtra(ApplicationValues.Base.PREVIEW_TYPE);
if(ApplicationValues.Base.TYPE_CAMERA.equals(type))
{
new File(bgPath).delete();
}
}
/**
* ³õʼ»¯´«¸ÐÆ÷
*/
private void initSensor()
{
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorListener = new SensorEventListener()
{
@Override
public void onSensorChanged(SensorEvent event)
{
float[] values = event.values;
float x = Math.abs(values[0]);
// float y = Math.abs(values[1]);
// float z = Math.abs(values[2]);
float value = 9;
// if(x>=value || y>=value || z>=value+9.8)
if(x>=value)
{
dv_canvas.setShaked(true);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
};
}
/**
* ¿Ø¼þ¼°½çÃæµÄ³õʼ»¯
*/
private void initComponent()
{
dv_canvas = (YiDrawView) findViewById(R.id.dv_canvas);
mRotateMenu = (YiRotateMenu) findViewById(R.id.rotate_menu);
iv_browser = (ImageView) findViewById(R.id.iv_browser);
iv_browser.setOnClickListener(this);
iv_copy = (ImageView) findViewById(R.id.iv_copy);
iv_copy.setOnClickListener(this);
iv_paste = (ImageView) findViewById(R.id.iv_paste);
iv_paste.setOnClickListener(this);
iv_tuyuan_large = (ImageView) findViewById(R.id.iv_tuyuan_large);
iv_tuyuan_large.setOnClickListener(this);
iv_tuyuan_small = (ImageView) findViewById(R.id.iv_tuyuan_small);
iv_tuyuan_small.setOnClickListener(this);
iv_tuyuan_rotate_left = (ImageView) findViewById(R.id.iv_tuyuan_ratate_left);
iv_tuyuan_rotate_left.setOnClickListener(this);
iv_tuyuan_rotate_right = (ImageView) findViewById(R.id.iv_tuyuan_rotate_right);
iv_tuyuan_rotate_right.setOnClickListener(this);
fl_change = (FrameLayout) findViewById(R.id.fl_change);
//Ϊ²Ëµ¥ÉèÖõã»÷ʼþ
| mRotateMenu.setOnMenuItemClickListener(new OnMenuItemClickListener()
| 7 |
mziccard/secureit | src/main/java/me/ziccard/secureit/async/upload/BluetoothPeriodicPositionUploaderTask.java | [
"public class SecureItPreferences {\n\t\n\tprivate SharedPreferences appSharedPrefs;\n private Editor prefsEditor;\n \n public static final String LOW = \"Low\";\n public static final String MEDIUM = \"Medium\";\n public static final String HIGH = \"High\";\n \n public static final String FRONT... | import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import me.ziccard.secureit.SecureItPreferences;
import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket;
import me.ziccard.secureit.config.Remote;
import me.ziccard.secureit.messages.BluetoothMessage;
import me.ziccard.secureit.messages.KeyRequest;
import me.ziccard.secureit.messages.MessageBuilder;
import me.ziccard.secureit.messages.MessageType;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast; | /*
* Copyright (c) 2013-2015 Marco Ziccardi, Luca Bonato
* Licensed under the MIT license.
*/
package me.ziccard.secureit.async.upload;
public class BluetoothPeriodicPositionUploaderTask extends AsyncTask<Void, Void, Void> {
private Context context;
/**
* Boolean true iff last thread iterations position has been sent
*/
private boolean dataSent = false;
private SecureItPreferences prefs;
/**
* Adapter for bluetooth services
*/
private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
/**
* Creates a BroadcastReceiver for ACTION_FOUND and ACTION_DISCOVERY_FINISHED
*/
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
private ArrayList<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
Log.i("BluetoothPeriodicPositionUploaderTask", "Discovered "+device.getName());
CharSequence text = "Discovered "+device.getName();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
// When ending the discovery
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
for (BluetoothDevice device : devices){
Log.i("DISCOVERY", "FINISHED");
try {
BluetoothSocket tmp = null;
tmp = device.createInsecureRfcommSocketToServiceRecord(Remote.BLUETOOTH_UUID);
if (tmp != null) {
Log.i("BluetoothPeriodicPositionUploaderTask", "Trying to connect to " + device.getName());
adapter.cancelDiscovery();
tmp.connect();
Log.i("BluetoothPeriodicPositionUploaderTask", "Connected to " + device.getName());
ObjectBluetoothSocket socket = new ObjectBluetoothSocket(tmp);
| MessageBuilder builder = new MessageBuilder(); | 5 |
iobeam/iobeam-client-java | src/test/java/com/iobeam/api/client/SendCallbackTest.java | [
"public class DataStore implements Serializable {\n\n public static final class MismatchedLengthException extends RuntimeException {\n\n public MismatchedLengthException() {\n super(\"Number of columns and values are not the same.\");\n }\n }\n\n public static final class UnknownFi... | import com.iobeam.api.resource.DataStore;
import com.iobeam.api.resource.DataPoint;
import com.iobeam.api.resource.Import;
import com.iobeam.api.resource.ImportBatch;
import com.iobeam.api.service.ImportService;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue; | package com.iobeam.api.client;
public class SendCallbackTest {
private static final long PROJECT_ID = 0;
private static final String DEVICE_ID = "fake_device_identifier";
private static final DataPoint dp1 = new DataPoint(1, 1);
| private ImportService.Submit getSubmitReq() { | 4 |
daquexian/chaoli-forum-for-android-2 | app/src/main/java/com/daquexian/chaoli/forum/network/ChaoliService.java | [
"public class ConversationListResult {\n public List<Conversation> getResults() {\n return results;\n }\n\n public void setResults(List<Conversation> results) {\n this.results = results;\n }\n\n List<Conversation> results;\n}",
"public class HistoryResult {\n public List<HistoryIte... | import com.daquexian.chaoli.forum.model.ConversationListResult;
import com.daquexian.chaoli.forum.model.HistoryResult;
import com.daquexian.chaoli.forum.model.NotificationList;
import com.daquexian.chaoli.forum.model.PostListResult;
import com.daquexian.chaoli.forum.model.Question;
import com.daquexian.chaoli.forum.model.User;
import com.daquexian.chaoli.forum.model.UserIdAndTokenResult;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable; | package com.daquexian.chaoli.forum.network;
/**
* Created by jianhao on 16-8-25.
*/
public interface ChaoliService {
@GET("index.php/conversation/index.json/{conversationId}/p{page}") | Call<PostListResult> listPosts(@Path("conversationId") int conversationId, @Path("page") int page); | 3 |
karsany/obridge | obridge-main/src/main/java/org/obridge/generators/EntityObjectGenerator.java | [
"public class OBridgeConfiguration {\n\n public static final boolean GENERATE_SOURCE_FOR_PLSQL_TYPES = false;\n public static final boolean ADD_ASSERT = false;\n\n private String jdbcUrl;\n private String sourceRoot;\n private String rootPackageName;\n private Packages packages;\n private Loggi... | import org.obridge.util.CodeFormatter;
import org.obridge.util.DataSourceProvider;
import org.obridge.util.MustacheRunner;
import org.obridge.util.OBridgeException;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.obridge.context.OBridgeConfiguration;
import org.obridge.dao.TypeDao;
import org.obridge.mappers.PojoMapper;
import org.obridge.model.data.TypeAttribute;
import org.obridge.model.generator.Pojo; | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ferenc Karsany
*
* 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.obridge.generators;
/**
* Created by fkarsany on 2015.01.28..
*/
public final class EntityObjectGenerator {
private EntityObjectGenerator() {
}
public static void generate(OBridgeConfiguration c) {
try {
String packageName = c.getRootPackageName() + "." + c.getPackages().getEntityObjects();
String outputDir = c.getSourceRoot() + "/" + packageName.replace(".", "/") + "/";
TypeDao typeDao = new TypeDao(DataSourceProvider.getDataSource(c.getJdbcUrl()));
List<String> types = typeDao.getTypeList(c);
for (String typeName : types) {
generateEntityObject(packageName, outputDir, typeName, typeDao.getTypeAttributes(typeName, c.getSourceOwner()));
}
if (types.size() == 0) {
generateEntityObject(packageName, outputDir, "Dummy", new ArrayList<>());
}
if (OBridgeConfiguration.GENERATE_SOURCE_FOR_PLSQL_TYPES) {
List<String> embeddedTypes = typeDao.getEmbeddedTypeList(c.getSourceOwner());
for (String typeName : embeddedTypes) {
generateEntityObject(packageName, outputDir, typeName, typeDao.getEmbeddedTypeAttributes(typeName, c.getSourceOwner()));
}
}
} catch (PropertyVetoException | IOException e) {
throw new OBridgeException(e);
}
}
private static void generateEntityObject(String packageName, String outputDir, String typeName, List<TypeAttribute> typeAttributes) throws IOException { | Pojo pojo = PojoMapper.typeToPojo(typeName, typeAttributes); | 2 |
KursX/Parallator | src/com/kursx/parallator/menu/BookMenu.java | [
"public class BookDialogController implements Initializable {\n\n private Stage stage;\n private Main main;\n private List<Chapter> chapters;\n private final String thumbnailName = \"thumbnail.jpg\";\n public static final ObservableList<String> langs = FXCollections.observableArrayList(\n ... | import com.google.gson.Gson;
import com.kursx.parallator.*;
import com.kursx.parallator.controller.BookDialogController;
import com.kursx.parallator.controller.Fb2DialogController;
import com.kursx.parallator.controller.MainController;
import com.kursx.parallator.export.CSVExporter;
import com.kursx.parallator.export.HtmlExporter;
import com.kursx.parallator.export.OfflineExporter;
import com.kursx.parallator.export.SB2Exporter;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.swing.*;
import java.io.File;
import java.io.IOException; | package com.kursx.parallator.menu;
public class BookMenu {
public final Menu menu;
public BookMenu(MainController rootController, Stage rootStage, Main main) throws IOException {
menu = new Menu("Книга");
Menu imp = new Menu("Импорт");
Menu exp = new Menu("Экспорт");
MenuItem info = new MenuItem("Описание");
MenuItem json = new MenuItem("JSON");
MenuItem fb2 = new MenuItem("FB2");
MenuItem csv = new MenuItem("CSV");
MenuItem sb2 = new MenuItem("SB2");
MenuItem studyEnglishWords = new MenuItem("studyenglishwords.com");
MenuItem html = new MenuItem("HTML");
MenuItem offline = new MenuItem("Оффлайн перевод");
imp.getItems().addAll(fb2, json, studyEnglishWords);
exp.getItems().addAll(csv, html, sb2, offline);
menu.getItems().addAll(imp, exp, info);
studyEnglishWords.setOnAction(event -> {
final File file = Helper.showFileChooser(rootStage.getScene(),
new FileChooser.ExtensionFilter("HTML(en+ru)", "*.html"));
if (file == null) return;
rootController.startProgress("Подождите, идет импорт html");
new Thread(() -> {
File jsonFile = StudyEnglishWords.INSTANCE.parse(file);
parseJson(rootController, jsonFile);
}).start();
});
json.setOnAction(event -> {
final File file = Helper.showFileChooser(rootStage.getScene(),
new FileChooser.ExtensionFilter("fb2", "*.json"));
if (file == null) return;
parseJson(rootController, file);
});
csv.setOnAction(event -> {
final int progress = rootController.startProgress("Подождите, идет создание offline");
new Thread(() -> {
BookConverter.convert(rootController, rootStage, new CSVExporter());
rootController.stopProgress(progress);
}).start();
});
offline.setOnAction(event -> {
final int progress = rootController.startProgress("Подождите, идет создание оффлайн перевода");
new Thread(() -> {
BookConverter.convert(rootController, rootStage, new OfflineExporter());
rootController.stopProgress(progress);
}).start();
});
html.setOnAction(event -> {
final int progress = rootController.startProgress("Подождите, идет создание html");
new Thread(() -> {
BookConverter.convert(rootController, rootStage, new HtmlExporter());
rootController.stopProgress(progress);
}).start();
});
sb2.setOnAction(event -> {
final int progress = rootController.startProgress("Подождите, идет создание sb2");
new Thread(() -> { | boolean showBookInfo = !BookConverter.convert(rootController, rootStage, new SB2Exporter()); | 6 |
MX-Futhark/hook-any-text | src/main/java/gui/views/MainWindow.java | [
"public class MainWindowActions {\n\n\tprivate MainWindow mainWindow;\n\n\tprivate FileFilter hatFileFilter = new FileFilter() {\n\n\t\t@Override\n\t\tpublic String getDescription() {\n\t\t\treturn \"Hook Any Text profile (.hat)\";\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean accept(File f) {\n\t\t\treturn f.isDirec... | import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import gui.actions.MainWindowActions;
import gui.utils.GUIErrorHandler;
import gui.utils.Images;
import gui.views.components.HidableOKCancelDialog;
import hextostring.HexProcessor;
import hextostring.history.History;
import main.MainOptions; | package gui.views;
/**
* The main window of the GUI.
*
* @author Maxime PIA
*/
@SuppressWarnings("serial")
public class MainWindow extends JFrame implements Observer {
private MainWindowActions acts = new MainWindowActions(this);
private MainOptions opts;
private HexProcessor hp;
private JTextArea convertedStringsArea = new JTextArea("Welcome to HAT!");
public MainWindow(HexProcessor hp, MainOptions opts,
History observedHistory, boolean deserializationWarning) {
super("Hook Any Text");
setSize(640, 240);
setIconImage(Images.DEFAULT_ICON.getImage());
this.opts = opts;
this.hp = hp;
observedHistory.addObserver(this);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
appendMenuBar(observedHistory);
appendFrameContent();
acts.setCloseAction(new HidableOKCancelDialog(
HidableOKCancelDialog.CLOSE_CONFIRM,
this,
HidableOKCancelDialog.CLOSE_CONFIRM_MESSAGE,
opts.getGUIOptions()
));
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException
| NoSuchMethodException | SecurityException e) {
| new GUIErrorHandler(e); | 1 |
nebula-plugins/gradle-metrics-plugin | src/main/java/nebula/plugin/metrics/AbstractMetricsPlugin.java | [
"public final class GradleBuildMetricsCollector extends BuildAdapter implements ProjectEvaluationListener, TaskExecutionListener, DependencyResolutionListener {\n\n private static final long TIMEOUT_MS = 5000;\n\n private final Logger logger = MetricsLoggerFactory.getLogger(GradleBuildMetricsCollector.class);... | import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import groovy.lang.Closure;
import nebula.plugin.metrics.collector.GradleBuildMetricsCollector;
import nebula.plugin.metrics.collector.GradleTestSuiteCollector;
import nebula.plugin.metrics.dispatcher.*;
import nebula.plugin.metrics.model.BuildMetrics;
import nebula.plugin.metrics.time.BuildStartedTime;
import nebula.plugin.metrics.time.Clock;
import nebula.plugin.metrics.time.MonotonicClock;
import org.gradle.BuildResult;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.invocation.BuildInvocationDetails;
import org.gradle.api.invocation.Gradle;
import org.gradle.api.tasks.testing.Test;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package nebula.plugin.metrics;
public abstract class AbstractMetricsPlugin<T> implements Plugin<T> {
public static String METRICS_ENABLED_PROPERTY = "metrics.enabled";
private MetricsDispatcher dispatcher = new UninitializedMetricsDispatcher(); | private final Clock clock = new MonotonicClock(); | 5 |
ibek/issue-keeper | issue-keeper-junit/src/test/java/qa/tools/ikeeper/test/query/CacheReadMultipleJirasTest.java | [
"public class CacheClient implements ITrackerClient {\n\n private final CacheConnector issueConnector;\n\n private List<ITrackerClient> clients;\n\n public CacheClient(ITrackerClient... clients) {\n this(CacheConnector.DEFAULT_CACHE_FILE_PATH, clients);\n }\n\n public CacheClient(String cacheF... | import org.assertj.core.api.Assertions;
import org.junit.*;
import org.junit.rules.TestRule;
import qa.tools.ikeeper.annotation.Jira;
import qa.tools.ikeeper.client.CacheClient;
import qa.tools.ikeeper.client.JiraClient;
import qa.tools.ikeeper.client.connector.CacheConnector;
import qa.tools.ikeeper.interceptor.QueryInterceptor;
import qa.tools.ikeeper.test.IKeeperJUnitConnector;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List; | package qa.tools.ikeeper.test.query;
public class CacheReadMultipleJirasTest {
private static final List<String> executed = new ArrayList<String>();
@AfterClass
public static void checkExecutions() {
Assertions.assertThat(executed).hasSize(1);
Assertions.assertThat(executed).contains("runVerifiedIssueTest");
}
private static final String QUERY = "KEY=${id} OR KEY=${anotherIssue} AND STATUS != CLOSED AND STATUS != RESOLVED";
@Rule
public TestRule issueKeeper;
public CacheReadMultipleJirasTest() {
System.setProperty("anotherIssue", "JBPM-4606");
issueKeeper = new IKeeperJUnitConnector(new QueryInterceptor(), new CacheClient(
new JiraClient("https://issues.jboss.org", QUERY)
));
}
@BeforeClass
public static void prepareCache() {
try { | PrintWriter out = new PrintWriter(CacheConnector.DEFAULT_CACHE_FILE_PATH); | 2 |
I8C/sonar-flow-plugin | sonar-flow-plugin/src/main/java/be/i8c/codequality/sonar/plugins/sag/webmethods/flow/squid/FlowAstScanner.java | [
"public enum FlowMetric implements MetricDef {\r\n\r\n FLOWS, \r\n INVOKES, \r\n SEQUENCES, \r\n LOOPS, \r\n BRANCHES, \r\n MAPS, \r\n LINES, \r\n FILES, \r\n LINES_OF_CODE, \r\n COMPLEXITY, \r\n COMMENT_LINES, \r\n STATEMENTS, \r\n DEPENDENCIES, \r\n IS_TOP_LEVEL;\r\n\r\n public boolean aggregateIfT... | import be.i8c.codequality.sonar.plugins.sag.webmethods.flow.metric.FlowMetric;
import be.i8c.codequality.sonar.plugins.sag.webmethods.flow.metric.MetricList;
import be.i8c.codequality.sonar.plugins.sag.webmethods.flow.sslr.FlowConfiguration;
import be.i8c.codequality.sonar.plugins.sag.webmethods.flow.sslr.FlowParser;
import be.i8c.codequality.sonar.plugins.sag.webmethods.flow.visitor.check.type.FlowCheck;
import com.google.common.base.Charsets;
import com.sonar.sslr.api.Grammar;
import com.sonar.sslr.impl.Parser;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.squidbridge.AstScanner;
import org.sonar.squidbridge.AstScanner.Builder;
import org.sonar.squidbridge.SquidAstVisitor;
import org.sonar.squidbridge.SquidAstVisitorContextImpl;
import org.sonar.squidbridge.api.SourceCode;
import org.sonar.squidbridge.api.SourceFile;
import org.sonar.squidbridge.api.SourceProject;
import org.sonar.squidbridge.indexer.QueryByType;
| /*
* i8c
* Copyright (C) 2016 i8c NV
* mailto:contact AT i8c DOT be
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package be.i8c.codequality.sonar.plugins.sag.webmethods.flow.squid;
/**
* This class will set the visitors that will be called on inspection.
*
* @author DEWANST
*/
public class FlowAstScanner {
static final Logger logger = LoggerFactory.getLogger(FlowAstScanner.class);
private FlowAstScanner() {
}
/**
* Creates the AstScanner. It will set flow and metric checks, next to the default ones.
*
* @param conf
* Configuration
* @param checks
* Additional checks to set
* @param metrics
* Additional metrics to set
* @return
*/
public static AstScanner<Grammar> create(FlowConfiguration conf, Collection<FlowCheck> checks,
@Nullable List<SquidAstVisitor<Grammar>> metrics) {
final SquidAstVisitorContextImpl<Grammar> context = new SquidAstVisitorContextImpl<Grammar>(
new SourceProject("Flow Project"));
final Parser<Grammar> parser = FlowParser.create(conf);
AstScanner.Builder<Grammar> builder = AstScanner.<Grammar>builder(context)
.setBaseParser(parser);
/* Required commentAnalyzer */
builder.setCommentAnalyser(new CommentAnalyser());
/* Metrics */
ArrayList<SquidAstVisitor<Grammar>> metricList = new ArrayList<SquidAstVisitor<Grammar>>();
| metricList.addAll(MetricList.getFlowVisitors());
| 1 |
android-cjj/MousePaint | app/src/main/java/com/cjj/mousepaint/fragment/MouseComicFragment.java | [
"public class CallbackListener<T> extends BaseListener<T>{\n\n @Override\n public void onError(Exception e) {\n\n }\n\n @Override\n public void onSuccess(T result) {\n\n }\n\n @Override\n public void onStringResult(String result) {\n\n }\n\n @Override\n public void onDownloadFinish(... | import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.cjj.listener.CallbackListener;
import com.cjj.mousepaint.DetialActivity;
import com.cjj.mousepaint.R;
import com.cjj.mousepaint.adapter.CategoryDetialAdapter;
import com.cjj.mousepaint.customview.NormalListView;
import com.cjj.mousepaint.dao.AppDao;
import com.cjj.mousepaint.events.RefreshEvent;
import com.cjj.mousepaint.events.RefreshFinishEvent;
import com.cjj.mousepaint.events.ViewPagerHeightEvent;
import com.cjj.mousepaint.model.CategoryModel;
import com.cjj.view.ViewSelectorLayout;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus; | package com.cjj.mousepaint.fragment;
/**
* Created by Administrator on 2015/11/4.
*/
public class MouseComicFragment extends BaseFragment implements AdapterView.OnItemClickListener{
private boolean isInit = false;
private boolean isHaveLoadData = false;
private int PageIndex = 0;
private CategoryDetialAdapter mAdapter;
private List<CategoryModel.ReturnEntity.ListEntity> mList;
@Bind(R.id.lv_hot)
NormalListView lv_hot;
@Bind(R.id.pb)
ProgressBar pb;
private boolean isLoadMore = false;
public static MouseComicFragment newInstance() {
MouseComicFragment fragment = new MouseComicFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_hot_book, null);
ButterKnife.bind(this, v);
isInit = true;
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
EventBus.getDefault().unregister(this);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lazyLoad();
}
@Override
protected void lazyLoad() {
if (!isInit || !isVisible||isHaveLoadData) {
return;
}
getCategoryData();
lv_hot.setOnItemClickListener(this);
lv_hot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Log.i("tag", "mouse=" + lv_hot.getMeasuredHeight()); | EventBus.getDefault().post(new ViewPagerHeightEvent("mouse", lv_hot.getMeasuredHeight())); | 7 |
IPEldorado/RemoteResources | src/com/eldorado/remoteresources/ui/wizard/AddHostPage.java | [
"public class Client {\n\n\tprivate static final String DEFAULT_LOGCAT_PATH = RemoteResourcesConfiguration\n\t\t\t.getRemoteResourcesDir() != null ? RemoteResourcesConfiguration\n\t\t\t.getRemoteResourcesDir() + File.separator + \"logs\" : System\n\t\t\t.getProperty(\"user.home\");\n\n\tprivate File logFilePath;\n\... | import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import com.eldorado.remoteresources.android.client.connection.Client;
import com.eldorado.remoteresources.android.client.connection.ClientConnectionManager;
import com.eldorado.remoteresources.i18n.RemoteResourcesLocalization;
import com.eldorado.remoteresources.i18n.RemoteResourcesMessages;
import com.eldorado.remoteresources.ui.actions.IPValidator;
import com.eldorado.remoteresources.ui.model.Host;
import com.eldorado.remoteresources.ui.model.PersistentDeviceModel;
import com.eldorado.remoteresources.ui.wizard.IWizard.WizardStatus; | constraints = new GridBagConstraints();
constraints.gridy = 5;
constraints.insets = new Insets(2, 0, 2, 2);
layout.addLayoutComponent(existsHostComboBoxLabel, constraints);
constraints = new GridBagConstraints();
constraints.gridy = 5;
constraints.weightx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(2, 0, 2, 2);
layout.addLayoutComponent(existsHostCombo, constraints);
add(existsHostComboBoxLabel);
add(existsHostCombo);
existsHostComboBoxLabel.setEnabled(false);
existsHostCombo.setEnabled(false);
if (getModel().getHosts().size() == 0) {
registredHostRadio.setEnabled(false);
newHostRadio.setEnabled(false);
existsHostComboBoxLabel.setEnabled(false);
existsHostCombo.setEnabled(false);
}
}
private String[] registredHosts(Collection<Host> listHosts, int amountHosts) {
Iterator<Host> cHosts = listHosts.iterator();
String[] vetHosts = new String[amountHosts];
int pos = 0;
while (cHosts.hasNext()) {
Host h = cHosts.next();
vetHosts[pos] = h.getName() + HYPHEN + h.getHostname() + COLON
+ String.valueOf(h.getPort());
pos++;
}
return vetHosts;
}
private class ValidatorListener implements DocumentListener {
@Override
public void insertUpdate(DocumentEvent e) {
validatePage();
}
@Override
public void removeUpdate(DocumentEvent e) {
validatePage();
}
@Override
public void changedUpdate(DocumentEvent e) {
validatePage();
}
}
private class UnchangedNicknameNickname implements DocumentListener {
@Override
public void insertUpdate(DocumentEvent e) {
changeNickname();
}
@Override
public void removeUpdate(DocumentEvent e) {
changeNickname();
}
@Override
public void changedUpdate(DocumentEvent e) {
changeNickname();
}
}
protected void changeNickname() {
if (!isChangedNickname) {
remoteNameText.setText(remoteHostText.getText() + COLON
+ remotePortText.getText());
}
}
@Override
protected void validatePage() {
String name = null;
String host = null;
String port = null;
String errorMessage = null;
WizardStatus level = WizardStatus.OK;
if (newHostRadio.isSelected()) {
name = remoteNameText.getText().trim();
host = remoteHostText.getText().trim();
port = remotePortText.getText().trim();
if (host.trim().isEmpty()) {
errorMessage = RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.AddHostPage_Error_EmptyHostname);
level = WizardStatus.ERROR;
}
if (isExistingHost(name)) {
errorMessage = RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.AddHostPage_Error_ExistingHostNickname);
level = WizardStatus.ERROR;
}
if ((errorMessage == null)
&& (!isPositiveNumber(port) || port.trim().isEmpty())) {
errorMessage = RemoteResourcesLocalization
.getMessage(RemoteResourcesMessages.AddHostPage_Error_InvalidPort);
level = WizardStatus.ERROR;
}
if (errorMessage == null) { | if (!IPValidator.isIPFormat(host)) { | 4 |
ThomasDaheim/ownNoteEditor | ownNoteEditor/src/test/java/tf/ownnote/ui/main/TestTagTreeLookAndFeel.java | [
"public class OwnNoteEditorParameters {\n // this is a singleton for everyones use\n // http://www.javaworld.com/article/2073352/core-java/simply-singleton.html\n private final static OwnNoteEditorParameters INSTANCE = new OwnNoteEditorParameters();\n\n // list of command line parameters we can understa... | import java.awt.MouseInfo;
import java.awt.Point;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit.ApplicationTest;
import tf.ownnote.ui.helper.OwnNoteEditorParameters;
import tf.ownnote.ui.helper.OwnNoteEditorPreferences;
import tf.ownnote.ui.notes.Note;
import tf.ownnote.ui.notes.TestNoteData;
import tf.ownnote.ui.tags.TagData;
import tf.ownnote.ui.tags.TagManager;
import tf.ownnote.ui.tags.TagTextFieldTreeCell; | /*
* Copyright (c) 2014ff Thomas Feuster
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tf.ownnote.ui.main;
/**
*
* @author Thomas Feuster <thomas@feuster.com>
*/
public class TestTagTreeLookAndFeel extends ApplicationTest {
private static double SCALING = 0.85;
private enum CheckMode {
TAG_CHILDREN,
TABLE_ELEMENTS,
BOTH;
public static boolean doCheckTagChildren(final CheckMode mode) {
return (TAG_CHILDREN.equals(mode) || BOTH.equals(mode));
}
public static boolean doCheckTableElements(final CheckMode mode) {
return (TABLE_ELEMENTS.equals(mode) || BOTH.equals(mode));
}
}
private Stage myStage;
private OwnNoteEditorManager myApp;
@Override
public void start(Stage stage) throws Exception {
myStage = stage;
myApp = new OwnNoteEditorManager();
// TODO: set command line parameters to avoid tweaking stored values
myApp.start(myStage);
/* Do not forget to put the GUI in front of windows. Otherwise, the robots may interact with another
window, the one in front of all the windows... */
myStage.toFront();
// TF, 20170205: under gradle in netbeans toFront() still leves the window in the background...
myStage.requestFocus();
}
private final TestNoteData myTestdata = new TestNoteData();
private String currentPath;
private Path testpath;
private String lastGroupName;
private String lastNoteName;
| private OwnNoteEditorParameters.LookAndFeel currentLookAndFeel; | 0 |
pugwoo/nimble-orm | src/main/java/com/pugwoo/dbhelper/impl/part/P3_UpdateOp.java | [
"public class DBHelperInterceptor {\n\n\t/**\n\t * select前执行。不会拦截getCount计算总数和getAllKey只查询key这2个接口。\n\t * @param clazz 查询的对象\n\t * @param sql 查询的完整sql\n\t * @param args 查询的完整参数。理论上,拦截器就有可能修改args里面的object的值的,请小心。不建议修改args的值。\n\t * @return 返回true,则查询继续; 返回false将终止查询并抛出NotAllowQueryException\n\t */\n\tpublic boolean b... | import com.pugwoo.dbhelper.DBHelperInterceptor;
import com.pugwoo.dbhelper.exception.CasVersionNotMatchException;
import com.pugwoo.dbhelper.exception.NotAllowQueryException;
import com.pugwoo.dbhelper.exception.NullKeyValueException;
import com.pugwoo.dbhelper.json.NimbleOrmJSON;
import com.pugwoo.dbhelper.sql.SQLUtils;
import com.pugwoo.dbhelper.utils.DOInfoReader;
import com.pugwoo.dbhelper.utils.PreHandleObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List; | package com.pugwoo.dbhelper.impl.part;
public abstract class P3_UpdateOp extends P2_InsertOp {
/////////////// 拦截器
private void doInterceptBeforeUpdate(List<Object> tList, String setSql, List<Object> setSqlArgs) {
for (DBHelperInterceptor interceptor : interceptors) {
boolean isContinue = interceptor.beforeUpdate(tList, setSql, setSqlArgs);
if (!isContinue) {
throw new NotAllowQueryException("interceptor class:" + interceptor.getClass());
}
}
}
private void doInterceptBeforeUpdate(Class<?> clazz, String sql,
List<String> customsSets, List<Object> customsParams, List<Object> args) {
for (DBHelperInterceptor interceptor : interceptors) {
boolean isContinue = interceptor.beforeUpdateAll(clazz, sql, customsSets, customsParams, args);
if (!isContinue) {
throw new NotAllowQueryException("interceptor class:" + interceptor.getClass());
}
}
}
private void doInterceptAfterUpdate(final List<Object> tList, final int rows) {
Runnable runnable = () -> {
for (int i = interceptors.size() - 1; i >= 0; i--) {
interceptors.get(i).afterUpdate(tList, rows);
}
};
if(!executeAfterCommit(runnable)) {
runnable.run();
}
}
//////////////
@Override
public <T> int update(T t) throws NullKeyValueException {
return _update(t, false, true, null);
}
@Override
public <T> int update(T t, String postSql, Object... args) throws NullKeyValueException {
if(postSql != null) {postSql = postSql.replace('\t', ' ');}
return _update(t, false, true, postSql, args);
}
@Override
public <T> int updateWithNull(T t) throws NullKeyValueException {
return _update(t, true, true, null);
}
@Override
public <T> int updateWithNull(T t, String postSql, Object... args) throws NullKeyValueException {
if(postSql != null) {postSql = postSql.replace('\t', ' ');}
return _update(t, true, true, postSql, args);
}
@Override
public <T> int updateWithNull(Collection<T> list) throws NullKeyValueException {
if(list == null || list.isEmpty()) {
return 0;
}
List<Object> tmpList = new ArrayList<>(list);
doInterceptBeforeUpdate(tmpList, null, null);
int rows = 0;
for(T t : list) {
if(t != null) {
rows += _update(t, true, false, null);
}
}
doInterceptAfterUpdate(tmpList, rows);
return rows;
}
@Override
public <T> int update(Collection<T> list) throws NullKeyValueException {
if(list == null || list.isEmpty()) {
return 0;
}
List<Object> tmpList = new ArrayList<>(list);
doInterceptBeforeUpdate(tmpList, null, null);
int rows = 0;
for(T t : list) {
if(t != null) {
rows += _update(t, false, false, null);
}
}
doInterceptAfterUpdate(tmpList, rows);
return rows;
}
private <T> int _update(T t, boolean withNull, boolean withInterceptors,
String postSql, Object... args) throws NullKeyValueException {
if(DOInfoReader.getNotKeyColumns(t.getClass()).isEmpty()) {
return 0; // not need to update
}
PreHandleObject.preHandleUpdate(t);
List<Object> tList = new ArrayList<>();
tList.add(t);
if(withInterceptors) {
doInterceptBeforeUpdate(tList, null, null);
}
List<Object> values = new ArrayList<>(); | String sql = SQLUtils.getUpdateSQL(t, values, withNull, postSql); | 5 |
evant/simplefragment | simplefragment/src/main/java/me/tatarka/simplefragment/activity/SimpleFragmentDelegate.java | [
"public abstract class SimpleFragment implements SimpleFragmentManagerProvider {\n private View view;\n private State state = new State();\n private SimpleFragmentStateManager stateManager;\n private SimpleFragmentManager manager;\n\n public abstract void onCreate(Context context, @Nullable Bundle st... | import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.LayoutInflaterCompat;
import android.support.v4.view.LayoutInflaterFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import java.util.List;
import me.tatarka.simplefragment.SimpleFragment;
import me.tatarka.simplefragment.SimpleFragmentManager;
import me.tatarka.simplefragment.SimpleFragmentManagerProvider;
import me.tatarka.simplefragment.SimpleFragmentStateManager;
import me.tatarka.simplefragment.SimpleFragmentViewInflater; | package me.tatarka.simplefragment.activity;
/**
* A delegate class for implementing SimpleFragments in your own Activity. While there are a lot of
* methods, implementing is mostly a matter of overriding all the methods with the same name and
* calling the delegate. See {@link SimpleFragmentActivity} for an example on how this is done.
*/
public class SimpleFragmentDelegate implements SimpleFragmentManagerProvider, LayoutInflaterFactory {
private static final String TAG = "SimpleFragmentDelegate";
private static final String STATE = "me.tatarka.simplefragment.STATE";
private Activity activity; | private SimpleFragmentStateManager stateManager; | 3 |
nextgis/nextgislogger | app/src/main/java/com/nextgis/logger/UI/activity/MarkActivity.java | [
"public class LoggerApplication extends Application implements IGISApplication {\n private static final String MAP_NAME = \"default\";\n private static final String PERMISSION_MANAGE_ACCOUNTS = \"android.permission.MANAGE_ACCOUNTS\";\n private static final String PERMISSION_AUTHENTICATE_ACCOUNTS = \"androi... | import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;
import com.nextgis.logger.LoggerApplication;
import com.nextgis.logger.R;
import com.nextgis.logger.engines.BaseEngine;
import com.nextgis.logger.engines.GPSEngine;
import com.nextgis.logger.engines.InfoItem;
import com.nextgis.logger.util.FileUtil;
import com.nextgis.logger.util.LoggerConstants;
import com.nextgis.logger.util.MarkName;
import com.nextgis.maplib.api.IGISApplication;
import com.nextgis.maplib.datasource.GeoPoint;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale; | @Override
public Filter getFilter() {
return mFilter;
}
@Override
public int getCount() {
return mMatchedMarks.size();
}
int getTotalCount() {
return mMarks.size();
}
@Override
public String getItem(int position) {
return mMatchedMarks.get(position).getCat();
}
int getMarkPosition(MarkName item) {
return mMarks.indexOf(item);
}
int getMatchedMarkPosition(MarkName item) {
return mMatchedMarks.indexOf(item);
}
MarkName getMatchedMarkItem(int position) {
if (position >= 0 && position < mMatchedMarks.size())
return mMatchedMarks.get(position);
else
return new MarkName(-1, "null");
}
MarkName getMarkItem(int position) {
if (hasItem(position))
return mMarks.get(position);
else
return new MarkName(-1, "null");
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
return super.getView(position, convertView, parent);
}
boolean hasItem(int position) {
return position >= 0 && position < mMarks.size();
}
void addMark(MarkName mark) {
mMarks.add(mark);
sortById();
notifyDataSetChanged();
}
void replaceMark(MarkName mark, MarkName newMark) {
int position = mMarks.indexOf(mark);
mMarks.remove(position);
mMarks.add(position, newMark);
sortById();
notifyDataSetChanged();
}
private class SubstringFilter extends Filter {
@Override
protected FilterResults performFiltering(final CharSequence prefix) {
final FilterResults results = new FilterResults();
if (prefix != null) {
ArrayList<MarkName> resultList = new ArrayList<>();
for (MarkName item : mMarks) {
String CAT = getUpperString(item.getCat());
String substr = getUpperString(prefix.toString());
if (CAT.contains(substr))
resultList.add(item);
}
results.count = resultList.size();
results.values = resultList;
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(final CharSequence constraint, final FilterResults results) {
mMatchedMarks.clear();
if (results != null && results.count > 0) {
mMatchedMarks.addAll((ArrayList<MarkName>) results.values);
notifyDataSetChanged();
} else
notifyDataSetInvalidated();
}
String getUpperString(String str) {
return str.toUpperCase(Locale.getDefault());
}
}
}
private class MarksHandler extends Handler {
private long mUndoTimeStamp = 0;
private MarkActivity mParent;
MarksHandler(MarkActivity parent) {
mParent = parent;
}
public void handleMessage(Message msg) {
switch (msg.what) {
case MARK_SAVE:
if (Math.abs(System.currentTimeMillis() - mUndoTimeStamp) >= DELAY) {
Bundle bundle = msg.getData();
ArrayList<InfoItem> items = bundle.getParcelableArrayList(BUNDLE_SENSOR); | GeoPoint point = GPSEngine.getFix(items); | 2 |
fluxroot/pulse | src/test/java/com/fluxchess/pulse/SearchTest.java | [
"public final class Move {\n\n\t// These are our bit masks\n\tprivate static final int TYPE_SHIFT = 0;\n\tprivate static final int TYPE_MASK = MoveType.MASK << TYPE_SHIFT;\n\tprivate static final int ORIGIN_SQUARE_SHIFT = 3;\n\tprivate static final int ORIGIN_SQUARE_MASK = Square.MASK << ORIGIN_SQUARE_SHIFT;\n\tpri... | import com.fluxchess.pulse.model.Move;
import org.junit.jupiter.api.Test;
import java.util.concurrent.Semaphore;
import static com.fluxchess.pulse.MoveList.RootEntry;
import static com.fluxchess.pulse.model.Move.NOMOVE;
import static com.fluxchess.pulse.model.Square.*;
import static com.fluxchess.pulse.model.Value.*;
import static java.lang.Integer.signum;
import static java.lang.Math.abs;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright 2013-2021 Phokham Nonava
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package com.fluxchess.pulse;
class SearchTest {
@Test
void testMate() throws InterruptedException {
final int[] currentBestMove = {NOMOVE};
final int[] currentPonderMove = {NOMOVE};
final Semaphore semaphore = new Semaphore(0);
Search search = new Search(
new Protocol() {
@Override
public void sendBestMove(int bestMove, int ponderMove) {
currentBestMove[0] = bestMove;
currentPonderMove[0] = ponderMove;
semaphore.release();
}
@Override
public void sendStatus(int currentDepth, int currentMaxDepth, long totalNodes, int currentMove, int currentMoveNumber) {
}
@Override
public void sendStatus(boolean force, int currentDepth, int currentMaxDepth, long totalNodes, int currentMove, int currentMoveNumber) {
}
@Override | public void sendMove(RootEntry entry, int currentDepth, int currentMaxDepth, long totalNodes) { | 1 |
firepick1/FireBOM | src/main/java/org/firepick/firebom/bom/BOMHtmlPrinter.java | [
"public class Main {\n public static void main(String[] args) throws Exception {\n mainStream(args, System.out);\n }\n\n public static void mainStream(String[] args, PrintStream printStream) throws Exception {\n BOMFactory bomFactory = new BOMFactory();\n\n try {\n if (!pars... | import org.firepick.firebom.Main;
import org.firepick.relation.IRelation;
import org.firepick.relation.IRow;
import org.firepick.relation.IRowVisitor;
import org.firepick.relation.RelationPrinter;
import java.io.*; | package org.firepick.firebom.bom;
/*
BOMHtmlPrinter.java
Copyright (C) 2013 Karl Lew <karl@firepick.org>. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class BOMHtmlPrinter extends RelationPrinter {
private boolean printHtmlWrapper;
private String title;
public BOMHtmlPrinter() {
super.setPrintTitleRow(false);
super.setPrintTotalRow(true);
}
public String getTitle() {
return title;
}
public BOMHtmlPrinter setTitle(String value) {
title = value;
return this;
}
@Override | protected void printTotalRow(PrintStream printStream, IRelation relation) { | 1 |
ni3po42/traction.mvc | traction/src/main/java/traction/mvc/implementations/ViewFactory.java | [
"public class UIHandler extends Handler\n{\n\tprivate Thread uiThread;\n\tpublic UIHandler()\n\t{\n\t\t//save an instance of the current thread, where it was created.\n\t\tuiThread = Thread.currentThread();\n\t}\n\n\tpublic void tryPostImmediatelyToUIThread(Runnable action)\n\t{\n\t\t//if the current thread is same... | import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import traction.mvc.observables.ScopeBuilder;
import java.lang.reflect.Constructor;
import traction.mvc.R;
import traction.mvc.implementations.ui.UIHandler;
import traction.mvc.interfaces.IProxyViewBinding;
import traction.mvc.interfaces.IViewBinding;
import traction.mvc.observables.BindingInventory;
import traction.mvc.util.Log;
import traction.mvc.observables.IProxyObservableObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.LayoutInflater.Factory2; |
@SuppressLint("DefaultLocale")
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs)
{
//no name, no view
if (name == null)
return null;
//figure out full name of view to inflate
String viewFullName = "android.widget." + name;
if (name.equals("View") || name.equals("ViewGroup"))
viewFullName = "android.view." + name;
else if (name.toLowerCase().equals("fragment"))
{
//ignore if it's a fragment, it's handled higher in the parser, and no way will I try to mimic or override that
return null;
}
else if (name.toLowerCase().equals("fragmentstub"))
{
viewFullName = android.widget.FrameLayout.class.getName();
}
else if (name.contains("."))
viewFullName = name;
//inflate
View view = inflateViewByClassName(viewFullName, attrs);
//no view, um, well, no view.
if (view==null) return null;
//should we go on?
IProxyViewBinding parentViewBinding = parent == null ? null : getViewBinding(parent);
boolean isRoot = false;
boolean ignoreChildren = false;
String relativeContext = null;
String bindingType = null;
Object tag = view.getTag();
String modelClass = null;
try
{
JSONObject tagProperties = new JSONObject(tag == null ? "{}" : tag.toString());
isRoot = tagProperties.has("@IsRoot") && tagProperties.getBoolean("@IsRoot");
ignoreChildren = tagProperties.has("@IgnoreChildren") && tagProperties.getBoolean("@IgnoreChildren");
relativeContext = tagProperties.has("@RelativeContext") ? tagProperties.getString("@RelativeContext") : null;
bindingType = tagProperties.has("@BindingType") ? tagProperties.getString("@BindingType") : null;
tag = tagProperties.has("@tag") ? tagProperties.get("@tag") : tag;
modelClass = tagProperties.has("@model") ? tagProperties.getString("@model") : null;
}
catch (JSONException jsonException)
{
Log.e("Error getting JSON tag", jsonException);
}
view.setTag(tag);
//if either there is no View Binding for a non null parent or that parent's View Binding says to ignore children..
boolean noParentViewBindingAndNotRoot = parent != null && parentViewBinding == null && !isRoot;
boolean hasParentViewBindingButIgnoreChildrenFlag = (parentViewBinding != null && parentViewBinding.getProxyViewBinding() != null
&& IViewBinding.Flags.hasFlags(parentViewBinding.getProxyViewBinding().getBindingFlags(), IViewBinding.Flags.IGNORE_CHILDREN));
if (noParentViewBindingAndNotRoot || hasParentViewBindingButIgnoreChildrenFlag)
{
//then stop here and return the view, no binding steps needed now.
return view;
}
UIHandler handler = new UIHandler();
int flags = IViewBinding.Flags.NO_FLAGS;
flags |= ignoreChildren ? IViewBinding.Flags.IGNORE_CHILDREN : IViewBinding.Flags.NO_FLAGS;
flags |= isRoot ? IViewBinding.Flags.IS_ROOT : IViewBinding.Flags.NO_FLAGS;
flags |= relativeContext != null ? (IViewBinding.Flags.HAS_RELATIVE_CONTEXT): IViewBinding.Flags.NO_FLAGS;
flags |= modelClass != null ? (IViewBinding.Flags.SCOPE_PRESENT): IViewBinding.Flags.NO_FLAGS;
String prefix = (parentViewBinding == null || parentViewBinding.getProxyViewBinding() == null ? null : parentViewBinding.getProxyViewBinding().getPathPrefix());
if (relativeContext != null)
{
if (prefix == null)
prefix = relativeContext;
else
prefix = prefix + "." + relativeContext;
}
IProxyViewBinding newViewBinding = null;
//if view implements IViewBinding and no custom type is given...
if (view instanceof IProxyViewBinding && bindingType == null)
//use the view itself...
newViewBinding = (IProxyViewBinding)view;
else
//...otherwise lookup the binding needed.
newViewBinding = createViewBinding(view, bindingType);
//if at this point we actually have a view binding...
if (newViewBinding != null)
{
BindingInventory inv = (parentViewBinding == null || parentViewBinding.getProxyViewBinding() == null) ? null : parentViewBinding.getProxyViewBinding().getBindingInventory();
/*if (isRoot && hasRelativeContext)
inv = new BindingInventory(new BindingInventory(inv));
else*/
if (isRoot)
inv = new BindingInventory(inv);
//if not labeled as root and no inventory is coming from parent, then it's probably
//coming from a step above the root; ignore it
if (inv != null && newViewBinding != null)
{
newViewBinding.getProxyViewBinding().setPathPrefix(prefix);
view.setTag(R.id.viewholder, newViewBinding);
view.addOnAttachStateChangeListener(detachListener);
newViewBinding.getProxyViewBinding().initialise(view, handler, inv, flags);
if (modelClass != null)
{
try
{
Class<?> modelClassInstance = Class.forName(modelClass); | Object scope = ScopeBuilder.CreateScope(modelClassInstance); | 6 |
leonardo2204/Flow1.0.0-alphaExample | app/src/main/java/leonardo2204/com/br/flowtests/presenter/FirstScreenPresenter.java | [
"public final class Flow {\n static final Object ROOT_KEY = new Object() {\n @Override public String toString() {\n return Flow.class.getName() + \".ROOT_KEY\";\n }\n };\n\n @NonNull public static Flow get(@NonNull View view) {\n return get(view.getContext());\n }\n\n @NonNull public static Flow ... | import android.os.Bundle;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import flow.Flow;
import leonardo2204.com.br.flowtests.ContactsAdapter;
import leonardo2204.com.br.flowtests.di.component.FirstScreenComponent;
import leonardo2204.com.br.flowtests.di.scope.DaggerScope;
import leonardo2204.com.br.flowtests.domain.interactor.DefaultSubscriber;
import leonardo2204.com.br.flowtests.domain.interactor.GetContacts;
import leonardo2204.com.br.flowtests.model.Contact;
import leonardo2204.com.br.flowtests.screen.DetailsScreen;
import leonardo2204.com.br.flowtests.view.FirstView;
import mortar.ViewPresenter;
import rx.functions.Action0; | package leonardo2204.com.br.flowtests.presenter;
/**
* Created by Leonardo on 05/03/2016.
*/
@DaggerScope(FirstScreenComponent.class)
public class FirstScreenPresenter extends ViewPresenter<FirstView> {
private final GetContacts getContacts;
private final ActionBarOwner actionBarOwner;
private final FirstView.ContactListener contactListener = new FirstView.ContactListener() {
@Override
public void onClick(Contact contact) { | Flow.get(getView()).set(new DetailsScreen(contact)); | 0 |
NickstaDB/BaRMIe | src/nb/barmie/BaRMIe.java | [
"public class BaRMIeIllegalArgumentException extends BaRMIeException {\n\tpublic BaRMIeIllegalArgumentException(String message) {\n\t\tsuper(message);\n\t}\n\t\n\tpublic BaRMIeIllegalArgumentException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n}",
"public class BaRMIeInvalidPortException... | import nb.barmie.exceptions.BaRMIeIllegalArgumentException;
import nb.barmie.exceptions.BaRMIeInvalidPortException;
import nb.barmie.modes.attack.AttackMode;
import nb.barmie.modes.enumeration.EnumerationMode;
import nb.barmie.util.ProgramOptions;
| package nb.barmie;
/***********************************************************
* Java RMI enumeration and attack tool.
**********************************************************
* v1.0
* -> Initial release with several attacks and
* deserialization payloads.
* v1.01
* -> Added JMX deserialization payload and improved some
* error handling.
**********************************************************
* Written by Nicky Bloor (@NickstaDB).
**********************************************************/
public class BaRMIe {
/*******************
* Entry point - parse command line params, validate, and run the selected
* mode.
******************/
public static void main(String[] args) {
ProgramOptions options;
//Print a banner 'cause leet and stuff.
System.out.println("\n ▄▄▄▄ ▄▄▄ ██▀███ ███▄ ▄███▓ ██▓▓█████ \n" +
" ▓█████▄ ▒████▄ ▓██ ▒ ██▒▓██▒▀█▀ ██▒▓██▒▓█ ▀ \n" +
" ▒██▒ ▄██▒██ ▀█▄ ▓██ ░▄█ ▒▓██ ▓██░▒██▒▒███ \n" +
" ▒██░█▀ ░██▄▄▄▄██ ▒██▀▀█▄ ▒██ ▒██ ░██░▒▓█ ▄ \n" +
" ░▓█ ▀█▓ ▓█ ▓██▒░██▓ ▒██▒▒██▒ ░██▒░██░░▒████▒\n" +
" ░▒▓███▀▒ ▒▒ ▓▒█░░ ▒▓ ░▒▓░░ ▒░ ░ ░░▓ ░░ ▒░ ░\n" +
" ▒░▒ ░ ▒ ▒▒ ░ ░▒ ░ ▒░░ ░ ░ ▒ ░ ░ ░ ░\n" +
" ░ ░ ░ ▒ ░░ ░ ░ ░ ▒ ░ ░ \n" +
" ░ ░ ░ ░ ░ ░ ░ ░\n" +
" ░ v1.01\n" +
" Java RMI enumeration tool.\n" +
" Written by Nicky Bloor (@NickstaDB)\n\n" +
"Warning: BaRMIe was written to aid security professionals in identifying the\n" +
" insecure use of RMI services on systems which the user has prior\n" +
" permission to attack. BaRMIe must be used in accordance with all\n" +
" relevant laws. Failure to do so could lead to your prosecution.\n" +
" The developers assume no liability and are not responsible for any\n" +
" misuse or damage caused by this program.\n");
//Just print usage if command line is empty
if(args.length == 0) {
printUsage("");
return;
}
//Parse command line options
try {
options = new ProgramOptions(args);
} catch(BaRMIeIllegalArgumentException|BaRMIeInvalidPortException ex) {
//Something wrong with the command line
printUsage(ex.getMessage());
return;
}
//Delegate to the relevant program mode
switch(options.getExecutionMode()) {
case "-enum":
//Enumerate RMI endpoints
new EnumerationMode(options).run();
break;
case "-attack":
//Attack RMI endpoints
| new AttackMode(options).run();
| 2 |
thiagotts/CloudReports | src/main/java/cloudreports/gui/datacenters/SpecificDatacenterView.java | [
"public class DatacenterRegistryDAO {\n \n /** \n * Inserts a new datacenter registry into the database.\n * The datacenter's name must be unique.\n *\n * @param dr the datacenter registry to be inserted.\n * @return <code>true</code> if the datacenter registry\n * ... | import java.text.DecimalFormat;
import java.util.List;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import cloudreports.dao.DatacenterRegistryDAO;
import cloudreports.dao.HostRegistryDAO;
import cloudreports.dao.NetworkMapEntryDAO;
import cloudreports.enums.AllocationPolicy;
import cloudreports.gui.Dialog;
import cloudreports.gui.EditLink;
import cloudreports.gui.MainView;
import cloudreports.models.DatacenterRegistry;
import cloudreports.models.HostRegistry;
import cloudreports.models.NetworkMapEntry;
import cloudreports.models.SanStorageRegistry; |
/**
* Changes the operating system of this datacenter registry whenever the
* item of the operating system combo box changes.
*
* @param evt an item event.
* @since 1.0
*/
private void osBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_osBoxItemStateChanged
switch(osBox.getSelectedIndex()) {
default: //case 0:
getDatacenterRegistry().setOs("Linux");
}
drDAO.updateDatacenterRegistry(getDatacenterRegistry());
}//GEN-LAST:event_osBoxItemStateChanged
/**
* Changes the allocation policy of this datacenter registry whenever the
* item of the operating system combo box changes.
*
* @param evt an item event.
* @since 1.0
*/
private void policyBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_policyBoxItemStateChanged
getDatacenterRegistry().setAllocationPolicyAlias(policyBox.getSelectedItem().toString());
drDAO.updateDatacenterRegistry(getDatacenterRegistry());
}//GEN-LAST:event_policyBoxItemStateChanged
/**
* Enables/disables virtual machines migrations in this datacenter registry
* whenever the item of the virtual machines migrations combo box changes.
*
* @param evt an item event.
* @since 1.0
*/
private void vmMigrationsBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_vmMigrationsBoxItemStateChanged
switch(vmMigrationsBox.getSelectedIndex()) {
case 1:
getDatacenterRegistry().setVmMigration(false);
break;
default: //case 0:
getDatacenterRegistry().setVmMigration(true);
}
drDAO.updateDatacenterRegistry(getDatacenterRegistry());
}//GEN-LAST:event_vmMigrationsBoxItemStateChanged
/**
* Changes the processing cost of this datacenter whenever the state of the
* processing cost spinner changes.
*
* @param evt a change event.
* @since 1.0
*/
private void procCostSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_procCostSpinnerStateChanged
DecimalFormat dft = new DecimalFormat("00.###E0");
String n = String.valueOf(procCostSpinner.getValue());
getDatacenterRegistry().setCostPerSec(Double.valueOf(n));
drDAO.updateDatacenterRegistry(getDatacenterRegistry());
double costPerMips = (getDatacenterRegistry().getCostPerSec()/drDAO.getMips(getDatacenterRegistry().getId()));
getMipsCostLabel().setText("(Cost per MIPS: "+dft.format(costPerMips)+")");
}//GEN-LAST:event_procCostSpinnerStateChanged
/**
* Changes the memory cost of this datacenter whenever the state of the
* memory cost spinner changes.
*
* @param evt a change event.
* @since 1.0
*/
private void memoryCostSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_memoryCostSpinnerStateChanged
String n = String.valueOf(memoryCostSpinner.getValue());
getDatacenterRegistry().setCostPerMem(Double.valueOf(n));
drDAO.updateDatacenterRegistry(getDatacenterRegistry());
}//GEN-LAST:event_memoryCostSpinnerStateChanged
/**
* Changes the storage cost of this datacenter whenever the state of the
* storage cost spinner changes.
*
* @param evt a change event.
* @since 1.0
*/
private void storageCostSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_storageCostSpinnerStateChanged
String n = String.valueOf(storageCostSpinner.getValue());
getDatacenterRegistry().setCostPerStorage(Double.valueOf(n));
drDAO.updateDatacenterRegistry(getDatacenterRegistry());
}//GEN-LAST:event_storageCostSpinnerStateChanged
/**
* Changes the bandwidth cost of this datacenter whenever the state of the
* bandwidth cost spinner changes.
*
* @param evt a change event.
* @since 1.0
*/
private void bwCostSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_bwCostSpinnerStateChanged
String n = String.valueOf(bwCostSpinner.getValue());
getDatacenterRegistry().setCostPerBw(Double.valueOf(n));
drDAO.updateDatacenterRegistry(getDatacenterRegistry());
}//GEN-LAST:event_bwCostSpinnerStateChanged
/**
* Launches a {@link EditHost} form when the Edit button is clicked if
* there is a selected host.
*
* @param evt an action event.
* @since 1.0
*/
private void editHostButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editHostButtonActionPerformed
int i = hostsTable.getSelectedRow();
if(i>=0) {
Long hostId = Long.valueOf(String.valueOf(hostsTable.getModel().getValueAt(i, 0)));
HostRegistryDAO hrDAO = new HostRegistryDAO();
HostRegistry h = hrDAO.getHostRegistry(hostId);
EditHost e = new EditHost(h, this);
e.setLocationRelativeTo(this);
e.setVisible(true);
}
else{ | Dialog.showWarning(this, "Please select a host."); | 4 |
evolvingstuff/RecurrentJava | src/datasets/bAbI.java | [
"public class DataSequence implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\tpublic List<DataStep> steps = new ArrayList<>();\n\t\n\tpublic DataSequence() {\n\t\t\n\t}\n\t\n\tpublic DataSequence(List<DataStep> steps) {\n\t\tthis.steps = steps;\n\t}\n\t\n\t@Override\n\tpublic String ... | import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import datastructs.DataSequence;
import datastructs.DataSet;
import datastructs.DataStep;
import loss.LossArgMax;
import loss.LossSoftmax;
import model.LinearUnit;
import model.Model;
import model.Nonlinearity; | }
}
List<Statement> trimmed = new ArrayList<>();
for (Statement statement : statements) {
if (supportingFactsAndQuestions.contains(statement.lineNum)) {
trimmed.add(statement);
}
}
this.statements = trimmed;
}
else {
this.statements = statements;
}
}
List<Statement> statements;
@Override
public String toString() {
String result = "";
for (Statement statement : statements) {
result += statement.toString() + "\n";
}
return result;
}
}
List<Story> getStories(List<String> fileNames, boolean onlySupportingFacts) throws Exception {
List<Statement> statements = new ArrayList<>();
for (String fileName : fileNames) {
File file = new File(fileName);
List<String> lines = Files.readAllLines(file.toPath(), Charset.defaultCharset());
for (String line : lines) {
statements.add(new Statement(line));
}
}
List<Story> stories = new ArrayList<>();
int prevNum = 0;
List<Statement> storyList = new ArrayList<>();
boolean containsQuestion = false;
int errors = 0;
for (Statement statement : statements) {
if (statement.lineNum < prevNum) {
if (containsQuestion == false) {
//System.out.println("Incomplete story");
//for (Statement st : storyList) {
// System.out.println(st);
//}
errors++;
}
else {
Story story = new Story(storyList, onlySupportingFacts);
//System.out.println(story);
stories.add(story);
}
containsQuestion = false;
storyList = new ArrayList<>();
}
if (statement.isFact == false) {
containsQuestion = true;
}
storyList.add(statement);
prevNum = statement.lineNum;
}
Story story = new Story(storyList, onlySupportingFacts);
//System.out.println(story);
stories.add(story);
if (errors > 0) {
System.out.println("WARNING: " + errors + " INCORRECT STORIES REMOVED.");
}
return stories;
}
List<String> inputVocab = new ArrayList<>();
List<String> outputVocab = new ArrayList<>();
private void configureVocab(List<Story> storiesTrain, List<Story> storiesTest) {
Set<String> inputVocabSet = new HashSet<>();
Set<String> outputVocabSet = new HashSet<>();
List<Story> allStories = new ArrayList<>();
allStories.addAll(storiesTrain);
allStories.addAll(storiesTest);
for (Story story : allStories) {
for (Statement statement : story.statements) {
if (statement.isFact) {
for (String word : statement.fact) {
inputVocabSet.add(word);
}
}
else {
for (String word : statement.question) {
inputVocabSet.add(word);
}
outputVocabSet.add(statement.answer);
}
}
}
for (String word : inputVocabSet) {
inputVocab.add(word);
}
for (String word : outputVocabSet) {
outputVocab.add(word);
}
Collections.sort(inputVocab);
Collections.sort(outputVocab);
System.out.println("Possible answers: ");
for (int i = 0; i < outputVocab.size(); i++) {
System.out.println("\t["+i+"]: " + outputVocab.get(i));
}
}
private List<DataSequence> getSequences(List<Story> stories) {
int inputDimension = inputVocab.size();
int outputDimension = outputVocab.size();
List<DataSequence> sequences = new ArrayList<>();;
for (Story story : stories) {
| List<DataStep> steps = new ArrayList<>(); | 2 |
legobmw99/Allomancy | src/main/java/com/legobmw99/allomancy/modules/combat/item/CoinBagItem.java | [
"@Mod(Allomancy.MODID)\npublic class Allomancy {\n\n public static final String MODID = \"allomancy\";\n public static final CreativeModeTab allomancy_group = new CreativeModeTab(MODID) {\n @Override\n public ItemStack makeIcon() {\n return new ItemStack(CombatSetup.MISTCLOAK.get());\... | import com.legobmw99.allomancy.Allomancy;
import com.legobmw99.allomancy.api.data.IAllomancerData;
import com.legobmw99.allomancy.api.enums.Metal;
import com.legobmw99.allomancy.modules.combat.entity.ProjectileNuggetEntity;
import com.legobmw99.allomancy.modules.powers.PowerUtils;
import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.*;
import net.minecraft.world.level.Level;
import javax.annotation.Nonnull;
import java.util.function.Predicate; | package com.legobmw99.allomancy.modules.combat.item;
public class CoinBagItem extends ProjectileWeaponItem {
public static final Predicate<ItemStack> NUGGETS = (stack) -> {
Item item = stack.getItem();
return PowerUtils.doesResourceContainsMetal(item.getRegistryName()) && item.getRegistryName().getPath().contains("nugget");
};
public CoinBagItem() {
super(Allomancy.createStandardItemProperties().stacksTo(1));
}
private static Ammo getAmmoFromItem(Item itemIn) {
return switch (itemIn.getRegistryName().getPath()) {
case "iron_nugget", "steel_nugget", "bronze_nugget", "copper_nugget", "nickel_nugget" -> Ammo.HEAVY;
case "bendalloy_nugget", "nicrosil_nugget", "electrum_nugget", "platinum_nugget" -> Ammo.MAGIC;
default -> Ammo.LIGHT;
};
}
@Nonnull
public Predicate<ItemStack> getAllSupportedProjectiles() {
return NUGGETS;
}
@Override
public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) {
ItemStack itemstack = player.getProjectile(player.getItemInHand(hand));
if (itemstack.getItem() instanceof ArrowItem) { // the above get function has silly default behavior
itemstack = new ItemStack(Items.GOLD_NUGGET, 1);
}
| if (!itemstack.isEmpty() && player.getCapability(AllomancerCapability.PLAYER_CAP).filter(data -> data.isBurning(Metal.STEEL)).isPresent()) { | 2 |
popo1379/popomusic | app/src/main/java/com/popomusic/api/QQMusicApi.java | [
"@Entity\npublic class MusicBean extends BaseBean{\n /**\n * songname : 舍不得 (《漂亮的李慧珍》电视剧插曲)\n * seconds : 148\n * albummid : 001sP1d63Zutvt\n * songid : 200506552\n * singerid : 1099829\n * albumpic_big : http://i.gtimg.cn/music/photo/mid_album_300/v/t/001sP1d63Zutvt.jpg\n * albumpic_... | import com.popomusic.bean.MusicBean;
import com.popomusic.bean.QQMusicBody;
import com.popomusic.bean.QQMusicPage;
import com.popomusic.bean.QQMusicResult;
import com.popomusic.bean.SearchBean;
import com.popomusic.bean.SearchPage;
import java.util.List;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query; | package com.popomusic.api;
/**
* Created by dingmouren on 2017/2/3.
*/
public interface QQMusicApi {
//请求歌曲
@GET("213-4")
Observable<QQMusicResult<QQMusicBody<QQMusicPage<List<MusicBean>>>>>
getQQMusic(@Query("showapi_appid") String showapi_appid, @Query("showapi_sign") String showapi_sign, @Query("topid") String topic);
//搜索歌曲
@GET("213-1") | Observable<QQMusicResult<QQMusicBody<SearchPage<List<SearchBean>>>>> | 4 |
nextopcn/xcalendar | src/main/java/cn/nextop/thorin/rcp/support/swt/widget/xcalendar/model/config/widget/impl/XCalendarNextWidget.java | [
"public final class Fonts {\n\t//\n\tpublic static final Font SYSTEM = Display.getDefault().getSystemFont();\n\tpublic static final Font AWESOME = FontAwesome.getFont(Math.max(10, getHeight(SYSTEM)));\n\t\n\t//\n\tprotected static final ConcurrentMultiKeyMap<Class<?>, String, Font> FONTS = new ConcurrentMultiKeyMap... | import cn.nextop.thorin.rcp.support.swt.utility.graphics.Fonts;
import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.XCalendar;
import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.event.bus.internal.*;
import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.XCalendarModel;
import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.config.render.XCalendarFrame;
import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.config.widget.AbstractXCalendarWidget;
import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.theme.XCalendarTheme;
import cn.nextop.thorin.rcp.support.swt.widget.xcalendar.support.XVirtualCalendar;
import cn.nextop.thorin.rcp.support.util.type.Pair;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import static cn.nextop.thorin.rcp.support.swt.utility.graphics.Extents.extent;
import static com.patrikdufresne.fontawesome.FontAwesome.chevron_right; | package cn.nextop.thorin.rcp.support.swt.widget.xcalendar.model.config.widget.impl;
/**
* @author chenby
*
*/
public class XCalendarNextWidget extends AbstractXCalendarWidget {
/**
*
*/
public XCalendarNextWidget(XCalendar popup) {
super(popup);
}
/**
*
*/
@Override
public Pair<Point> locate(int x, int y, int w, int m) {
int u = w / 7;
return new Pair<>(new Point(u, u), new Point(m, y + u));
}
/**
* Event
*/
@Override
protected boolean onMouseMove(XCalendarMouseMoveEvent event) {
return true;
}
@Override
protected boolean onMouseDown(XCalendarMouseDownEvent event) {
return true;
}
@Override
protected boolean onMouseEnter(XCalendarMouseEnterEvent event) {
showCursor(); popup.redraw(); return true;
}
@Override
protected boolean onMouseLeave(XCalendarMouseLeaveEvent event) {
hideCursor(); popup.redraw(); return true;
}
@Override
protected boolean onMouseUp(final XCalendarMouseUpEvent event) {
if (!mouse.isEntered()) { popup.redraw(); return true; }
final XCalendarModel model = popup.getModel();
final XVirtualCalendar calendar = model.getCalendar();
model.getState().next(calendar); popup.redraw(); return true;
}
/**
*
*/
@Override
public void render(XCalendarFrame frame) {
// Background
final GC gc = frame.getGc();
final XCalendarModel model = popup.getModel();
final XCalendarTheme theme = model.getTheme();
final boolean hovered = this.mouse.isEntered();
int x = bounds.x, y = bounds.y, w = bounds.width, h = bounds.height;
gc.setBackground(theme.getBackground(true, false, false, hovered));
gc.fillRoundRectangle(x, y, w, h, theme.getArc(), theme.getArc());
// Foreground
String text = chevron_right;
gc.setForeground(theme.getForeground(true, false, true)); | gc.setFont(Fonts.getAwesomeFont()); final Point size = extent(gc, text); | 0 |
magnusmickelsson/pokeraidbot | src/test/java/pokeraidbot/domain/raid/RaidPokemonsTest.java | [
"public class LocaleService {\n private static final Logger LOGGER = LoggerFactory.getLogger(LocaleService.class);\n public static final String NEW_EX_RAID_HELP = \"NEW_EX_RAID_HELP\";\n public static final String RAIDSTATUS = \"RAIDSTATUS\";\n public static final String NO_RAID_AT_GYM = \"NO_RAID_AT_GY... | import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import pokeraidbot.domain.config.LocaleService;
import pokeraidbot.domain.pokemon.Pokemon;
import pokeraidbot.domain.pokemon.PokemonRaidInfo;
import pokeraidbot.domain.pokemon.PokemonRepository;
import pokeraidbot.infrastructure.jpa.config.UserConfigRepository;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when; | package pokeraidbot.domain.raid;
public class RaidPokemonsTest {
private LocaleService localeService;
private PokemonRepository pokemonRepository;
private PokemonRaidStrategyService strategyService;
@Before
public void setUp() throws Exception {
UserConfigRepository userConfigRepository = Mockito.mock(UserConfigRepository.class);
when(userConfigRepository.findOne(any(String.class))).thenReturn(null);
localeService = new LocaleService("sv", userConfigRepository);
pokemonRepository = new PokemonRepository("/pokemons.csv", localeService);
strategyService = new PokemonRaidStrategyService(pokemonRepository);
}
@Test
public void verifyTyranitarBestCounterIsMachamp() throws Exception {
final RaidBossCounters raidBossCounters = strategyService.getCounters(pokemonRepository.search("Tyranitar", null));
final String tyranitarBestCounter = raidBossCounters
.getSupremeCounters().iterator().next().getCounterPokemonName();
assertThat(tyranitarBestCounter, is("Machamp"));
}
@Test
public void verifyAllPokemonsInPokemonGoInRepo() throws Exception {
Set<Integer> numbers = new HashSet<>();
try {
for (int n = 1; n < 387; n++) {
numbers.add(n);
}
for (Pokemon pokemon : pokemonRepository.getAll()) {
numbers.remove(pokemon.getNumber());
}
assertThat("" + numbers, numbers.size(), is(0));
} catch (Throwable e) {
for (Integer pokemonNumber : numbers) {
System.out.println(pokemonRepository.getByNumber(pokemonNumber));
}
throw e;
}
}
@Test
public void verifyAllLegendaryPokemonsAreTier5() { | final PokemonRaidInfo raikou = strategyService.getRaidInfo(pokemonRepository.search("raikou", null)); | 2 |
PaystackHQ/paystack-android | paystack/src/main/java/co/paystack/android/Paystack.java | [
"public class AuthenticationException extends PaystackException {\n public AuthenticationException(String message) {\n super(message);\n }\n\n public AuthenticationException(String message, Throwable e) {\n super(message, e);\n }\n}",
"public class PaystackSdkNotInitializedException exte... | import android.app.Activity;
import co.paystack.android.exceptions.AuthenticationException;
import co.paystack.android.exceptions.PaystackSdkNotInitializedException;
import co.paystack.android.model.Charge;
import co.paystack.android.model.PaystackModel;
import co.paystack.android.utils.Utils; | package co.paystack.android;
/**
* This is the Paystack model class.\n
* <br>
* Try not to use this class directly.
* Instead, access the functionalities of this class via the {@link PaystackSdk}
*
* @author {androidsupport@paystack.co} on 9/16/15.
*/
public class Paystack extends PaystackModel {
private String publicKey;
/**
* Constructor.
*/
protected Paystack() throws PaystackSdkNotInitializedException {
//validate sdk initialized | Utils.Validate.validateSdkInitialized(); | 4 |
reines/httptunnel | src/main/java/com/yammer/httptunnel/server/HttpTunnelAcceptedChannel.java | [
"public enum SaturationStateChange {\r\n\t/**\r\n\t * There was no change in the channels saturation state.\r\n\t */\r\n\tNO_CHANGE,\r\n\r\n\t/**\r\n\t * The channel is no longer saturated and writing can safely commence.\r\n\t */\r\n\tDESATURATED,\r\n\r\n\t/**\r\n\t * The channel has become saturated and writing s... | import java.net.InetSocketAddress;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.AbstractChannel;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import com.yammer.httptunnel.state.SaturationStateChange;
import com.yammer.httptunnel.util.ChannelFutureAggregator;
import com.yammer.httptunnel.util.ForwardingFutureListener;
import com.yammer.httptunnel.util.HttpTunnelMessageUtils;
import com.yammer.httptunnel.util.IncomingBuffer;
import com.yammer.httptunnel.util.QueuedResponse;
import com.yammer.httptunnel.util.SaturationManager;
import com.yammer.httptunnel.util.WriteFragmenter;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Gauge; | return config;
}
@Override
public InetSocketAddress getLocalAddress() {
return this.isBound() ? localAddress : null;
}
@Override
public InetSocketAddress getRemoteAddress() {
return this.isConnected() ? remoteAddress : null;
}
@Override
public boolean isBound() {
return parent.getTunnel(tunnelId) != null;
}
@Override
public boolean isConnected() {
return parent.getTunnel(tunnelId) != null;
}
@Override
public boolean setClosed() {
final boolean success = super.setClosed();
Channels.fireChannelClosed(this);
return success;
}
synchronized ChannelFuture internalClose(boolean sendCloseRequest, ChannelFuture future) {
if (!opened.getAndSet(false)) {
future.setSuccess();
return future;
}
// Closed from the server end - we should notify the client
if (sendCloseRequest) {
final Channel channel = pollChannel.getAndSet(null);
// response channel is already in use, client will be notified of
// close at next opportunity
if (channel != null && channel.isOpen())
Channels.write(channel, HttpTunnelMessageUtils.createTunnelCloseResponse());
}
Channels.fireChannelDisconnected(this);
Channels.fireChannelUnbound(this);
parent.removeTunnel(tunnelId);
this.setClosed();
future.setSuccess();
return future;
}
synchronized ChannelFuture internalSetInterestOps(int ops, ChannelFuture future) {
if (this.getInterestOps() != ops)
this.setAndNotifyInterestedOpsChange(ops);
future.setSuccess();
return future;
}
private void setAndNotifyInterestedOpsChange(int ops) {
super.setInterestOpsNow(ops);
Channels.fireChannelInterestChanged(this);
// Update the incoming buffer
incomingBuffer.onInterestOpsChanged();
}
void internalReceiveMessage(ChannelBuffer message) {
if (!opened.get()) {
if (LOG.isWarnEnabled())
LOG.warn("Received message while channel is closed");
return;
}
// Attempt to queue this message in the incoming buffer
if (!incomingBuffer.offer(message)) {
if (LOG.isWarnEnabled())
LOG.warn("Incoming buffer rejected message, dropping");
return;
}
// If the buffer is over capacity start congestion control
if (incomingBuffer.overCapacity()) {
// TODO: Send a "stop sending shit" message!
// TODO: What about when to send the "start sending shit again"
// message?
}
}
synchronized ChannelFuture sendMessage(MessageEvent message) {
final ChannelFuture messageFuture = message.getFuture();
if (!this.isConnected()) {
final Exception error = new IllegalStateException("Unable to send message when not connected");
messageFuture.setFailure(error);
return messageFuture;
}
saturationManager.updateThresholds(config.getWriteBufferLowWaterMark(), config.getWriteBufferHighWaterMark());
// Deliver the message using the underlying channel
final ChannelBuffer messageBuffer = (ChannelBuffer) message.getMessage();
final int messageSize = messageBuffer.readableBytes();
updateSaturationStatus(messageSize);
messageFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
updateSaturationStatus(-messageSize);
}
});
| final ChannelFutureAggregator aggregator = new ChannelFutureAggregator(messageFuture); | 1 |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | [
"public class MockTestCase {\n\n\tprotected Mockery context = new JUnit4Mockery();\n\n\t@Before\n\tpublic void setupMockery() {\n\t\tcontext.setImposteriser(ClassImposteriser.INSTANCE);\n\t}\n\t\n\t@After\n\tpublic void mockeryAssertIsSatisfied(){\n\t\tcontext.assertIsSatisfied();\n\t}\n\n\tprotected void checking(... | import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandlerTest extends MockTestCase {
@Test
public void testReceivePackPassesCorrectStuffToJGIT() throws Exception {
final String pathtobasedir = "pathtobasedir";
final FilteredCommand filteredCommand = new FilteredCommand(
"git-receive-pack", "proj-2/git.git");
final InputStream mockInputStream = context.mock(InputStream.class);
final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final Repository mockRepoistory = context.mock(Repository.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty( | GitSCMCommandFactory.REPOSITORY_BASE); | 3 |
maofw/anetty_client | src/com/netty/client/handler/PushMessageHandler.java | [
"public class NettyServerManager {\n\n\t// 心跳監控週期 30s\n\tprivate EventLoopGroup group;\n\t// private ChannelFuture channelFuture;\n\n\t// private ApplicationContextClient applicationContextClient;\n\n\tprivate static NettyProcessorHandler mNettyProcessorHandler;\n\n\tprivate static NettyServerManager connectionMana... | import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.netty.client.android.NettyServerManager;
import com.netty.client.android.dao.Device;
import com.netty.client.android.handler.MessageObject;
import com.netty.client.android.handler.NettyProcessorHandler;
import com.netty.client.android.service.RemoteService;
import com.netty.client.context.ApplicationContextClient;
import com.xwtec.protoc.CommandProtoc;
import com.xwtec.protoc.CommandProtoc.PushMessage; | package com.netty.client.handler;
/**
* 客户端消息处理Handler
*
* @author maofw
*
*/
public class PushMessageHandler extends SimpleChannelInboundHandler<CommandProtoc.PushMessage> {
private ApplicationContextClient applicationContextClient;
private NettyServerManager mConnectionManager;
private Handler mHandler;
public PushMessageHandler(NettyServerManager connectionManager, Handler handler) {
this.mConnectionManager = connectionManager;
this.mHandler = handler; | this.applicationContextClient = RemoteService.getApplicationContextClient(); | 4 |
jDramaix/SlidingPuzzle | test/be/dramaix/ai/slidingpuzzle/SlidingPuzzleTest.java | [
"public class IDAStar implements SearchAlgorithm, UseHeuristic {\n\n\tprivate long startTime;\n\tprivate long exploredNodes;\n\tprivate int nextCostBound;\n\tprivate HeuristicFunction heuristic;\n\n\t@Override\n\tpublic PuzzleSolution resolve(State start, State goal) {\n\n\t\tNode startNode = new Node(start);\n\t\t... | import junit.framework.TestCase;
import org.junit.Ignore;
import be.dramaix.ai.slidingpuzzle.server.search.IDAStar;
import be.dramaix.ai.slidingpuzzle.server.search.SearchAlgorithm;
import be.dramaix.ai.slidingpuzzle.server.search.heuristic.LinearConflict;
import be.dramaix.ai.slidingpuzzle.server.search.heuristic.ManhattanDistance;
import be.dramaix.ai.slidingpuzzle.server.search.heuristic.UseHeuristic;
import be.dramaix.ai.slidingpuzzle.shared.Node;
import be.dramaix.ai.slidingpuzzle.shared.Path;
import be.dramaix.ai.slidingpuzzle.shared.State; | package be.dramaix.ai.slidingpuzzle;
public class SlidingPuzzleTest extends TestCase {
@Ignore
public void test3x3() {
runAStar(SLIDE_3X3, State.GOAL_3_3);
}
public void test4x4() {
runAStar(SLIDE_4X4, State.GOAL_4_4);
}
public void runAStar(byte[][] testData, State goal){
long averageTime = 0;
int solutionLength = 0;
int inError = 0;
for (byte[] startState : testData) { | SearchAlgorithm algo = new IDAStar(); | 0 |
wrey75/WaveCleaner | src/main/java/com/oxande/xmlswing/components/JPopupMenuUI.java | [
"public class AttributeDefinition {\r\n\t\r\n\tpublic final static Map<String, String> ALIGNS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CLOSE_OPERATIONS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CURSORS = new HashMap<String, String>();\r\n\tpub... | import javax.swing.JPopupMenu;
import org.w3c.dom.Element;
import com.oxande.xmlswing.AttributeDefinition;
import com.oxande.xmlswing.AttributesController;
import com.oxande.xmlswing.Parser;
import com.oxande.xmlswing.UnexpectedTag;
import com.oxande.xmlswing.AttributeDefinition.ClassType;
import com.oxande.xmlswing.jcode.JavaClass;
import com.oxande.xmlswing.jcode.JavaMethod;
| package com.oxande.xmlswing.components;
/**
*
* @author wrey75
* @version $Rev: 47 $
*
*/
public class JPopupMenuUI extends JComponentUI {
public static final AttributeDefinition[] PROPERTIES = {
new AttributeDefinition( "borderPainted", "setBorderPainted", ClassType.BOOLEAN ),
new AttributeDefinition( "label", "setLabel", ClassType.STRING ),
new AttributeDefinition( "lightweight", "setLightWeightPopupEnabled", ClassType.BOOLEAN ),
};
public static final AttributesController CONTROLLER = new AttributesController( JComponentUI.CONTROLLER, PROPERTIES );
| public String parse(JavaClass jclass, JavaMethod initMethod, Element root ) throws UnexpectedTag {
| 3 |
ganeshkamathp/killingspree | core/src/com/sillygames/killingSpree/serverEntities/ServerBullet.java | [
"public interface NonExplodingWeaponCategory {\r\n ServerEntity getShooter();\r\n}\r",
"public class Utils {\r\n \r\n public static boolean wrapBody(Vector2 position) {\r\n boolean wrap = false;\r\n if (position.x > WorldRenderer.VIEWPORT_WIDTH) {\r\n wrap = true;\r\n ... | import com.badlogic.gdx.math.MathUtils;
import com.sillygames.killingSpree.categories.NonExplodingWeaponCategory;
import com.sillygames.killingSpree.helpers.Utils;
import com.sillygames.killingSpree.helpers.EntityUtils.ActorType;
import com.sillygames.killingSpree.managers.WorldBodyUtils;
import com.sillygames.killingSpree.managers.physics.Body.BodyType;
import com.sillygames.killingSpree.networking.messages.EntityState;
| package com.sillygames.killingSpree.serverEntities;
public class ServerBullet extends ServerEntity implements NonExplodingWeaponCategory {
public static final float RADIUS = 5f;
private float velocity;
public float destroyTime;
public ServerEntity shooter;
public ServerBullet(short id, float x, float y, WorldBodyUtils world) {
super(id, x, y, world);
actorType = ActorType.BULLET;
body = world.addBox(RADIUS, RADIUS, position.x, position.y,
BodyType.DynamicBody);
body.setLinearVelocity(velocity, 0);
body.setGravityScale(0f);
body.setUserData(this);
destroyTime = 1f;
}
@Override
public void update(float delta) {
destroyTime -= delta;
position.set(body.getPosition());
if (Utils.wrapBody(position)) {
body.setTransform(position, 0);
}
if (destroyTime < 0) {
dispose();
}
}
@Override
public void dispose() {
world.destroyBody(body);
}
@Override
| public void updateState(EntityState state) {
| 5 |
oharaandrew314/TinkerTime | src/io/andrewohara/tinkertime/TinkerTimeLauncher.java | [
"@Singleton\npublic class ModManager extends Listenable<TaskCallback> {\n\n\tprivate final TaskLauncher taskLauncher;\n\tprivate final ModWorkflowBuilderFactory workflowBuilderFactory;\n\tprivate final ModLoader modLoader;\n\n\tprivate Mod selectedMod;\n\n\t@Inject\n\tModManager(ModWorkflowBuilderFactory workflowBu... | import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.SplashScreen;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.j256.ormlite.support.ConnectionSource;
import io.andrewohara.common.content.ImageManager;
import io.andrewohara.common.version.Version;
import io.andrewohara.common.views.Dialogs;
import io.andrewohara.tinkertime.controllers.ModManager;
import io.andrewohara.tinkertime.controllers.ModUpdateCoordinator;
import io.andrewohara.tinkertime.db.DbConnectionString;
import io.andrewohara.tinkertime.io.crawlers.CrawlerFactory.UnsupportedHostException;
import io.andrewohara.tinkertime.models.ConfigData;
import io.andrewohara.tinkertime.views.InstallationSelectorView;
import io.andrewohara.tinkertime.views.SelectedInstallationView;
import io.andrewohara.tinkertime.views.modSelector.ModListCellRenderer;
import io.andrewohara.tinkertime.views.modSelector.ModSelectorPanelController; | package io.andrewohara.tinkertime;
/**
* Main Class for Tinker Time
*
* @author Andrew O'Hara
*/
public class TinkerTimeLauncher implements Runnable {
public static final String
NAME = "Tinker Time",
AUTHOR = "oharaandrew314",
DOWNLOAD_URL = "https://kerbalstuff.com/mod/243";
public static final Version VERSION = Version.valueOf("2.0.1");
public static final String
SAFE_NAME = NAME.replace(" ", ""),
FULL_NAME = String.format("%s %s by %s", NAME, VERSION, AUTHOR);
private final Collection<Runnable> startupTasks = new LinkedList<>();
@Inject
TinkerTimeLauncher(ConfigVerifier configVerifier, SetupListeners setupListeners, LoadModsTask startupModLoader, UpdateChecker updateChecker, MainFrameLauncher mainFrameLauncher){
startupTasks.add(setupListeners);
startupTasks.add(configVerifier);
startupTasks.add(startupModLoader);
startupTasks.add(updateChecker);
startupTasks.add(mainFrameLauncher);
}
@Override
public void run() {
for (Runnable task : startupTasks){
task.run();
}
}
public static Path getHomePath(){
return Paths.get(System.getProperty("user.home"), "Documents", TinkerTimeLauncher.NAME);
}
public static void main(String[] args) {
Injector injector = Guice.createInjector(new MainModule());
// Test Database Connection
injector.getInstance(TestConnectionTask.class).call();
// Migrate database
injector.getInstance(DatabaseMigrator.class).run();
// Launch Application
TinkerTimeLauncher launcher = injector.getInstance(TinkerTimeLauncher.class);
launcher.run();
}
///////////////////
// Startup Tasks //
///////////////////
public static class TestConnectionTask implements Callable<Void> {
private final ConnectionSource dbConnection;
private final Dialogs dialogs;
@Inject
TestConnectionTask(ConnectionSource dbConnection, Dialogs dialogs){
this.dbConnection = dbConnection;
this.dialogs = dialogs;
}
@Override
public Void call() {
try {
dbConnection.getReadWriteConnection();
} catch (SQLException e) {
dialogs.errorDialog(null, "Error Connection to Database", e);
}
return null;
}
}
public static class DatabaseMigrator implements Runnable {
private final DbConnectionString connectionString;
@Inject
DatabaseMigrator(DbConnectionString connectionString){
this.connectionString = connectionString;
}
@Override
public void run() {
// Perform Database Migration
Flyway flyway = new Flyway();
flyway.setBaselineOnMigrate(true);
flyway.setLocations("io/andrewohara/tinkertime/db/migration");
flyway.setDataSource(connectionString.getUrl(), null, null);
try {
flyway.migrate();
} catch (FlywayException e){
flyway.repair();
throw e;
}
}
}
private static class ConfigVerifier implements Runnable {
private final ConfigData config;
private final InstallationSelectorView selector;
@Inject
ConfigVerifier(ConfigData config, InstallationSelectorView selector){
this.config = config;
this.selector = selector;
}
@Override
public void run() {
if (config.getSelectedInstallation() == null){
selector.toDialog();
}
}
}
private static class SetupListeners implements Runnable {
private final ModSelectorPanelController modSelectorPanelController;
private final ModListCellRenderer modListCellRenderer;
private final ModUpdateCoordinator modUpdateCoordinator;
private final SelectedInstallationView installationView;
@Inject
SetupListeners(ModUpdateCoordinator modUpdateCoordinator, ModSelectorPanelController modSelectorPanelController, ModListCellRenderer modListCellRender, SelectedInstallationView installationView) {
this.modUpdateCoordinator = modUpdateCoordinator;
this.modSelectorPanelController = modSelectorPanelController;
this.modListCellRenderer = modListCellRender;
this.installationView = installationView;
}
@Override
public void run() {
modUpdateCoordinator.setListeners(modSelectorPanelController, modListCellRenderer, installationView);
}
}
private static class LoadModsTask implements Runnable {
private final ModUpdateCoordinator updateCooridnator;
private final ConfigData config;
@Inject
LoadModsTask(ModUpdateCoordinator updateCooridnator, ConfigData config){
this.updateCooridnator = updateCooridnator;
this.config = config;
}
@Override
public void run() {
updateCooridnator.changeInstallation(config.getSelectedInstallation());
}
}
private static class UpdateChecker implements Runnable {
private final ConfigData config; | private final ModManager modManager; | 0 |
xbynet/crawler | crawler-core/src/test/java/net/xby1993/crawler/ZhihuRecommendCrawler.java | [
"public class Const {\n\tpublic enum HttpMethod{\n\t\tGET,POST,HEAD\n\t}\n\tpublic enum CssAttr{\n\t\tinnerHtml,text,allText\n\t}\n\tpublic enum ResponseType{\n\t\tTEXT,BIN\n\t}\n}",
"public abstract class Processor implements Closeable{\n\tprivate FileDownloader fileDownloader=null;\n\tprivate Spider spider=null... | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.xbynet.crawler.Const;
import com.github.xbynet.crawler.Processor;
import com.github.xbynet.crawler.Request;
import com.github.xbynet.crawler.Response;
import com.github.xbynet.crawler.Site;
import com.github.xbynet.crawler.Spider;
import com.github.xbynet.crawler.parser.JsonPathParser; | package net.xby1993.crawler;
public class ZhihuRecommendCrawler extends Processor{
private Logger log=LoggerFactory.getLogger(ZhihuRecommendCrawler.class);
private AtomicInteger offset=new AtomicInteger(0);
@Override
public void process(Response resp) {
String curUrl=resp.getRequest().getUrl();
JsonPathParser parser=resp.json();
int count=Integer.valueOf(parser.single("$.msg.length()"));
if(count>0){
resp.addRequest(getPostRequest(offset.addAndGet(20)));
}
StringBuilder sb=new StringBuilder();
for(int i=0;i<count;i++){
String itemStr=parser.single("$.msg["+i+"]");
Element e=Jsoup.parse(itemStr).select("div.zm-item").get(0);
String title=e.select("h2 a.question_link").text();
String link="https://www.zhihu.com"+e.select("h2 a.question_link").attr("href");
String authorAndInfo=e.select(".summary-wrapper").text();
String content=e.select(".zm-item-rich-text .zh-summary").html();
sb.append("<div style='margin: 6px 0 6px 400px;max-width:800px;border-bottom: 3px dashed #ccc;'><h4><a href=\""+link+"\">"+title+"</a></h4><span style='color:blue;'>"+authorAndInfo+"</span><a style='color:red;margin:0 10px;' href='"+link+"'>查看</a><div>"+content+"</div></div>\n");
}
appendToFile(sb.toString());
}
public void start() {
Site site = new Site();
site.setHeader("Referer", "https://www.zhihu.com/explore/recommendations");
Spider spider = Spider.builder(this).threadNum(5).site(site)
.requests(getPostRequest(0)).build();
spider.run();
appendToFile("</body></html>");
}
private Request getPostRequest(int offset){
Request req=new Request("https://www.zhihu.com/node/ExploreRecommendListV2"); | req.setMethod(Const.HttpMethod.POST); | 0 |
spearal/spearal-java | src/test/java/org/spearal/test/TestAliasedBean.java | [
"public interface SpearalDecoder {\n\t\n\tpublic interface Path {\n\t\t\n\t\tCollection<PathSegment> segments();\n\t}\n\t\n\tpublic interface PathSegment {\n\t\t\n\t\tPathSegment copy();\n\t}\n\n\tpublic interface CollectionPathSegment extends PathSegment {\n\t\t\n\t\tpublic Collection<?> getCollection();\n\t\tpubl... | import org.spearal.impl.SpearalDecoderImpl.ClassNotFound;
import org.spearal.test.model.AliasedSimpleBean;
import org.spearal.test.model.SimpleBean;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.junit.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spearal.SpearalDecoder;
import org.spearal.SpearalEncoder;
import org.spearal.DefaultSpearalFactory;
import org.spearal.SpearalFactory;
import org.spearal.configuration.AliasStrategy; | /**
* == @Spearal ==>
*
* Copyright (C) 2014 Franck WOLFF & William DRAI (http://www.spearal.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.spearal.test;
/**
* @author Franck WOLFF
*/
public class TestAliasedBean extends AbstractSpearalTestUnit {
@Before
public void setUp() throws Exception {
// printStream = System.out;
}
@After
public void tearDown() throws Exception {
printStream = NULL_PRINT_STREAM;
}
@SuppressWarnings("boxing")
@Test
public void test() throws IOException { | SimpleBean bean = new SimpleBean(true, 1, 0.1, "blabla"); | 7 |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/query/executor/QueryExecutor.java | [
"@BadSmell(\"1) Singleton dont allow multi thread - 2) Is it really necessary?\")\npublic class InMemoryDB {\n\n\tprivate static InMemoryDB me;\n\n\tprivate static final Object MUTEX = new Object();\n\t\n\tprivate Long sequence = 1L;\n\t\n\tprivate Map<String, List<Object>> data = new HashMap<String, List<Object>>(... | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.raidenjpa.db.InMemoryDB;
import org.raidenjpa.query.parser.FromClause;
import org.raidenjpa.query.parser.FromClauseItem;
import org.raidenjpa.query.parser.GroupByElements;
import org.raidenjpa.query.parser.JoinClause;
import org.raidenjpa.query.parser.QueryParser;
import org.raidenjpa.query.parser.WithClause;
import org.raidenjpa.util.BadSmell;
import org.raidenjpa.util.FixMe; | package org.raidenjpa.query.executor;
public class QueryExecutor {
private Integer maxResult;
private int firstResult;
private Map<String, Object> parameters;
private QueryParser queryParser;
public QueryExecutor(String jpql, Map<String, Object> parameters, Integer maxResult) {
this.queryParser = new QueryParser(jpql);
this.parameters = parameters;
this.maxResult = maxResult;
this.firstResult = 0;
}
public QueryExecutor(QueryParser queryParser, Map<String, Object> parameters) {
this.queryParser = queryParser;
this.parameters = parameters;
}
@FixMe("Which one is the first, group or order?")
public List<?> getResultList() {
showJpql();
QueryResult queryResult = new QueryResult();
executeFrom(queryResult);
executeJoin(queryResult);
executeWhere(queryResult);
executeGroup(queryResult);
executeOrderBy(queryResult);
executeLimit(queryResult);
return queryResult.getList(queryParser.getSelect(), queryParser.getGroupBy());
}
private void executeGroup(QueryResult queryResult) {
if (queryParser.getGroupBy() == null && !queryParser.getSelect().isThereAggregationFunction()) {
return;
}
List<List<String>> paths = new ArrayList<List<String>>();
if (queryParser.getGroupBy() == null) {
paths.add(Arrays.asList("fake_aggregation_for_group_all_rows"));
} else {
for (GroupByElements groupByElements : queryParser.getGroupBy().getElements()) {
paths.add(groupByElements.getPath());
}
}
queryResult.group(paths);
}
private void showJpql() {
String jpql = queryParser.getWords().getJpql();
for (Entry<String, Object> entry : parameters.entrySet()) {
jpql = jpql.replaceAll(":" + entry.getKey(), entry.getValue().toString());
}
}
private void executeOrderBy(QueryResult queryResult) {
queryResult.sort(queryParser.getOrderBy());
}
@BadSmell("It is kind of confused. Put it in QueryResult")
private void executeJoin(QueryResult queryResult) {
if (queryResult.size() == 0) {
return;
}
for (JoinClause join : queryParser.getJoins()) {
queryResult.join(join, queryParser.getWhere(), parameters);
}
// @FixMe - There is some case when IN is not equals to JOIN, study it
for (FromClauseItem item : queryParser.getFrom().getItens()) {
if (item.isInFrom()) {
JoinClause join = new JoinClause();
join.setAlias(item.getAliasName());
join.setPath(item.getInPath());
join.setWith(new WithClause());
queryResult.join(join, queryParser.getWhere(), parameters);
}
}
}
@FixMe("Execute limit before than group by is correct?")
private void executeLimit(QueryResult queryResult) {
queryResult.limit(firstResult, maxResult);
}
private void executeWhere(QueryResult queryResult) {
if (!queryParser.getWhere().hasElements()) {
return;
}
LogicExpressionExecutor logicExpressionExecutor = new LogicExpressionExecutor(queryParser.getWhere().getLogicExpression(), parameters);
Iterator<QueryResultRow> it = queryResult.iterator();
while(it.hasNext()) {
QueryResultRow row = it.next();
if (!logicExpressionExecutor.match(row, true)) {
it.remove();
}
}
}
@BadSmell("Refactory")
private void executeFrom(QueryResult queryResult) { | FromClause from = queryParser.getFrom(); | 1 |
monster860/FastDMM | src/main/java/com/github/monster860/fastdmm/editing/placement/DeletePlacementMode.java | [
"public class FastDMM extends JFrame implements ActionListener, TreeSelectionListener, ListSelectionListener {\n\tprivate static final long serialVersionUID = 1L;\n\tpublic File dme;\n\tpublic DMM dmm;\n\tpublic List<DMM> loadedMaps = new ArrayList<DMM>();\n\tpublic Map<String, ModifiedType> modifiedTypes = new Has... | import java.util.Set;
import javax.swing.JPopupMenu;
import com.github.monster860.fastdmm.FastDMM;
import com.github.monster860.fastdmm.dmirender.RenderInstance;
import com.github.monster860.fastdmm.dmmmap.Location;
import com.github.monster860.fastdmm.dmmmap.TileInstance;
import com.github.monster860.fastdmm.objtree.ObjInstance; | package com.github.monster860.fastdmm.editing.placement;
public class DeletePlacementMode implements PlacementMode {
@Override | public PlacementHandler getPlacementHandler(FastDMM editor, ObjInstance instance, Location initialLocation) { | 4 |
optimaize/command4j | src/test/java/com/optimaize/command4j/ext/extensions/failover/autoretry/AutoRetryExtensionTest.java | [
"public interface CommandExecutor {\n\n /**\n * Executes it in the current thread, and blocks until it either finishes successfully or aborts by\n * throwing an exception.\n *\n * @param <A> argument\n * @param <R> Result\n */\n @NotNull\n <A, R> Optional<R> execute(@NotNull Command... | import com.google.common.base.Optional;
import com.optimaize.command4j.CommandExecutor;
import com.optimaize.command4j.CommandExecutorBuilder;
import com.optimaize.command4j.ExecutionContext;
import com.optimaize.command4j.Mode;
import com.optimaize.command4j.commands.BaseCommand;
import com.optimaize.command4j.commands.CallCounter;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals; | package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
public class AutoRetryExtensionTest {
/**
* Runs a command that fails the first time, has auto-retry extension on, and works the 2nd time.
*/
@Test
public void worksOnSecondCall_wrappedCommand() throws Exception {
CommandExecutor nakedExecutor = new CommandExecutorBuilder().build();
//keeps track of how often the first command was called.
final CallCounter.Counter counter = new CallCounter.Counter();
BaseCommand<Void, Integer> cmd = makeCommandWhereFirstCallFails(counter);
| cmd = FailoverExtensions.withAutoRetry(cmd, AutoRetryStrategies.alwaysOnce()); | 6 |
orekyuu/Riho | src/net/orekyuu/riho/emotion/renderer/MojaRenderer.java | [
"public abstract class Animation {\n\n private Instant startTime;\n private final Duration duration;\n private final Duration delay;\n double valueFrom;\n double valueTo;\n double value;\n\n public Animation(Instant startTime, Duration duration) {\n this(startTime, duration, Duration.ZER... | import net.orekyuu.riho.animation.Animation;
import net.orekyuu.riho.animation.KeyFrameAnimation;
import net.orekyuu.riho.animation.LinearAnimation;
import net.orekyuu.riho.character.ImageResources;
import net.orekyuu.riho.character.ImageUtil;
import net.orekyuu.riho.character.Loop;
import net.orekyuu.riho.character.Riho;
import net.orekyuu.riho.character.renderer.CharacterPosition;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList; | package net.orekyuu.riho.emotion.renderer;
public class MojaRenderer extends EmotionRendererBase {
private final BufferedImage emotionImage;
private Duration animationTime = Duration.ofMillis(2000);
private Animation moveX;
private Animation moveY;
private Animation fade = new LinearAnimation(Instant.now(), Duration.ofMillis(400), Duration.ofMillis(1600));
private int[][] pos = {
{0, 0},
{15, 15},
{10, -5},
{-5, 0},
{0, 10},
{5, 5},
{10, -10},
{10, 5},
{15, 10},
{10, 0},
{7, -15},
};
public MojaRenderer(Loop maxLoopCount) {
super(maxLoopCount);
emotionImage = ImageResources.emotionMojya();
ArrayList<KeyFrameAnimation.KeyFrame> animX = new ArrayList<>();
ArrayList<KeyFrameAnimation.KeyFrame> animY = new ArrayList<>();
Instant now = Instant.now();
double r = 1f / pos.length;
for (int i = 1; i < pos.length; i++) {
LinearAnimation x = new LinearAnimation(now, Duration.ZERO);
x.setFromValue(ImageUtil.defaultScale(pos[i - 1][0]));
x.setToValue(ImageUtil.defaultScale(pos[i][0]));
animX.add(new KeyFrameAnimation.KeyFrame(r * (i - 1), r * i, x));
LinearAnimation y = new LinearAnimation(now, Duration.ZERO);
y.setFromValue(ImageUtil.defaultScale(pos[i][1]));
y.setToValue(ImageUtil.defaultScale(pos[i - 1][1]));
animY.add(new KeyFrameAnimation.KeyFrame(r * (i - 1), r * i, y));
}
moveX = new KeyFrameAnimation(now, Duration.ofMillis(2000), animX);
moveY = new KeyFrameAnimation(now, Duration.ofMillis(2000), animY);
fade.setFromValue(1);
fade.setToValue(0);
}
@Override | public void render(Instant now, Graphics2D g, CharacterPosition pos, Riho riho) { | 6 |
highsource/tenra | core/src/main/java/org/hisrc/tenra/converter/railwaytransportnetwork/_3/RailwayLinkSequenceTypeConverter.java | [
"public interface Converter<I, O> {\n\n\tpublic O convert(I value);\n\n}",
"public class IdentifierPropertyTypeToStringConverter implements\n\t\tConverter<IdentifierPropertyType, String> {\n\t\n\tpublic static final Converter<IdentifierPropertyType, String> INSTANCE = new IdentifierPropertyTypeToStringConverter()... | import inspire.x.specification.gmlas.network._3.DirectedLinkPropertyType;
import inspire.x.specification.gmlas.railwaytransportnetwork._3.RailwayLinkSequenceType;
import java.util.ArrayList;
import java.util.List;
import net.opengis.gml.v_3_2_1.ReferenceType;
import org.apache.commons.lang3.Validate;
import org.hisrc.tenra.converter.Converter;
import org.hisrc.tenra.converter.basetypes._3.IdentifierPropertyTypeToStringConverter;
import org.hisrc.tenra.converter.gml.v_3_2_1.CodeWithAuthorityTypeToStringConverter;
import org.hisrc.tenra.converter.gml.v_3_2_1.ReferenceTypeToStringConverter;
import org.hisrc.tenra.converter.network._3.DirectedLinkPropertyTypeToIdConverter;
import org.hisrc.tenra.model.DBNetzConstants;
import org.hisrc.tenra.model.RailwayLinkSequence;
import org.hisrc.tenra.util.Ensure; | package org.hisrc.tenra.converter.railwaytransportnetwork._3;
public class RailwayLinkSequenceTypeConverter implements
Converter<RailwayLinkSequenceType, RailwayLinkSequence> {
public static final Converter<RailwayLinkSequenceType, RailwayLinkSequence> INSTANCE = new RailwayLinkSequenceTypeConverter();
@Override
public RailwayLinkSequence convert(RailwayLinkSequenceType value) {
Validate.notNull(value);
Ensure.propertyIsNull(value.getBeginLifespanVersion(), value,
"beginLifespanVersion");
Ensure.propertyIsNull(value.getBoundedBy(), value, "boundedBy");
Ensure.propertyIsNull(value.getDescription(), value, "description");
Ensure.propertyIsNull(value.getDescriptionReference(), value,
"descriptionReference");
Ensure.propertyIsNull(value.getLocation(), value, "location");
Ensure.propertyIsNull(value.getValidFrom(), value, "validFrom");
Ensure.propertyIsNull(value.getValidTo(), value, "validTo");
Ensure.propertyIsEmpty(value.getMetaDataProperty(), value,
"metaDataProperty");
Ensure.propertyIsEmpty(value.getName(), value, "name");
Ensure.propertyIsNil(value.getEndLifespanVersion(), value,
"endLifespanVersion");
Ensure.propertyIsNull(value.getGeographicalName(), value,
"geographicalName");
Ensure.propertyIsNotNull(value.getInspireId(), value, "inspireId");
// Ensure.propertyIsNotNull(value.getStartNode(), value, "startNode");
// Ensure.propertyIsNotNull(value.getEndNode(), value, "endNode");
Ensure.propertyIsNotNull(value.getInNetwork(), value, "inNetwork");
// final String geographicalName =
// TransportLinkType_JAXBElement_GeographicalName_ToStringConverter.INSTANCE
// .convert(value.getGeographicalName());
final String id = CodeWithAuthorityTypeToStringConverter.INSTANCE
.convert(value.getIdentifier());
Ensure.propertyStartsWith(id, value, "identifier",
DBNetzConstants.ID_COLON_PREFIX);
final String localId = IdentifierPropertyTypeToStringConverter.INSTANCE
.convert(value.getInspireId());
final String expectedLocalId = id.substring(DBNetzConstants.ID_COLON_PREFIX
.length());
Ensure.propertyEquals(value.getId(), value, "id", localId);
Ensure.propertyEquals(value.getId(), value, "id", expectedLocalId);
final ReferenceType inNetwork = Ensure.propertyHasSingleItem(
value.getInNetwork(), value, "inNetwork");
final String inNetworkId = ReferenceTypeToStringConverter.INSTANCE
.convert(inNetwork);
Ensure.propertyIsNotEmpty(value.getLink(), value, "link");
final List<String> railwayLinkIds = new ArrayList<>(value.getLink().size());
for (final DirectedLinkPropertyType link : value.getLink()) { | railwayLinkIds.add(DirectedLinkPropertyTypeToIdConverter.INSTANCE | 4 |
Joy-Whale/EasyShare | demo/src/main/java/cn/joy/libs/platform/demo/LoginActivity.java | [
"public abstract class Auth<T extends Platform, Q extends PlatformAuthInfo> implements PlatformActionListener<Q> {\n\n\tprivate T platform;\n\tprivate boolean loginByClient = true;\n\tprivate PlatformActionListener<Q> listener;\n\n\tpublic enum Target {\n\t\tQQ, Wechat, Sina\n\t}\n\n\tpublic Auth(T platform, boolea... | import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import cn.joy.libs.platform.Auth;
import cn.joy.libs.platform.AuthBuilder;
import cn.joy.libs.platform.Logs;
import cn.joy.libs.platform.PlatformActionListener;
import cn.joy.libs.platform.PlatformAuthInfo;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.joy.libs.platform.Share;
import cn.joy.libs.platform.ShareBuilder;
import cn.joy.libs.platform.ShareParams; | package cn.joy.libs.platform.demo;
/**
* User: JiYu
* Date: 2016-07-27
* Time: 09-43
*/
public class LoginActivity extends Activity implements PlatformActionListener<PlatformAuthInfo> {
private static final String TAG = "LoginActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
}
@OnClick(R.id.btn1)
void loginWeichat() { | new AuthBuilder().authTo(Auth.Target.Wechat).listener(this).auth(); | 1 |
kristian/JDigitalSimulator | src/main/java/lc/kra/jds/components/buildin/register/ShiftRegister.java | [
"public final class Utilities {\n\tpublic static enum TranslationType { TEXT, ALTERNATIVE, TITLE, EXTERNAL, TOOLTIP, DESCRIPTION; }\n\n\tpublic static final String\n\t\tCONFIGURATION_LOCALIZATION_LANGUAGE = \"localization.language\",\n\t\tCONFIGURATION_LOOK_AND_FEEL_CLASS = \"lookandfeel.class\",\n\t\tCONFIGURATION... | import static lc.kra.jds.Utilities.*;
import java.awt.Graphics;
import java.awt.Point;
import java.beans.PropertyVetoException;
import java.util.Map;
import lc.kra.jds.Utilities.TranslationType;
import lc.kra.jds.contacts.Contact;
import lc.kra.jds.contacts.ContactUtilities;
import lc.kra.jds.contacts.InputContact;
import lc.kra.jds.contacts.OutputContact; | /*
* JDigitalSimulator
* Copyright (C) 2017 Kristian Kraljic
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package lc.kra.jds.components.buildin.register;
/**
* Shift-Register (build-in component)
* @author Kristian Kraljic (kris@kra.lc)
*/
public class ShiftRegister extends Register {
private static final long serialVersionUID = 2l;
private static final String KEY;
static { KEY = "component.register."+ShiftRegister.class.getSimpleName().toLowerCase(); }
public static final ComponentAttributes componentAttributes = new ComponentAttributes(KEY, getTranslation(KEY), "group.register", getTranslation(KEY, TranslationType.DESCRIPTION), "Kristian Kraljic (kris@kra.lc)", 1);
protected InputContact inputI, inputC, inputR;
private Contact[] contacts;
protected boolean oldClock;
public ShiftRegister() {
inputI = new InputContact(this, new Point(0, 6));
inputC = new InputContact(this, new Point(0, 16));
inputR = new InputContact(this, new Point(0, 26));
| contacts = ContactUtilities.concatenateContacts(new Contact[]{inputI, inputC, inputR}, outputs.toArray()); | 3 |
taskadapter/redmine-java-api | src/main/java/com/taskadapter/redmineapi/bean/Project.java | [
"public class NotFoundException extends RedmineException {\n\n private static final long serialVersionUID = 1L;\n\n public NotFoundException(String msg) {\n super(msg);\n }\n}",
"public class RedmineAuthenticationException extends RedmineSecurityException {\n\tprivate static final long serialVersi... | import com.taskadapter.redmineapi.NotFoundException;
import com.taskadapter.redmineapi.RedmineAuthenticationException;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.internal.RequestParam;
import com.taskadapter.redmineapi.internal.Transport;
import org.apache.http.message.BasicNameValuePair;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set; | *
* <p>see http://www.redmine.org/projects/redmine/repository/entry/trunk/app/models/project.rb
*
* @return possibly Redmine-version-specific number that represents project status (active/closed/archived)
* @since Redmine REST API 2.5.0
*/
public Integer getStatus() {
return storage.get(STATUS);
}
/**
* Sets the project status (Note that this will not take effect when updating a project as
* the **current Redmine version in 2018** does not allow reopen, close or archive projects,
* see https://www.redmine.org/issues/13725)
*/
public Project setStatus(Integer status) {
storage.set(STATUS, status);
return this;
}
/**
*
* @return true if the project is public, false if the project is private.
* Returns <code>null</code> if the project visibility was not specified or if the project was just retrieved from server.
*
* @since Redmine 2.6.0. see http://www.redmine.org/issues/17628 . this property is for writing only before Redmine 2.6.0.
* The value is not returned by older Redmine versions.
*/
@Deprecated
public Boolean getProjectPublic() {
return storage.get(PUBLIC);
}
public Project setInheritMembers(Boolean inheritMembers) {
storage.set(INHERIT_MEMBERS, inheritMembers);
return this;
}
public Boolean getInheritMembers() {
return storage.get(INHERIT_MEMBERS);
}
public Project setProjectPublic(Boolean projectPublic) {
storage.set(PUBLIC, projectPublic);
return this;
}
public Collection<CustomField> getCustomFields() {
return storage.get(CUSTOM_FIELDS);
}
public Project addCustomFields(Collection<CustomField> customFields) {
storage.get(CUSTOM_FIELDS).addAll(customFields);
return this;
}
public CustomField getCustomFieldById(int customFieldId) {
for (CustomField customField : getCustomFields()) {
if (customFieldId == customField.getId()) {
return customField;
}
}
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Project project = (Project) o;
if (getId() != null ? !getId().equals(project.getId()) : project.getId() != null) return false;
return true;
}
@Override
public int hashCode() {
return getId() != null ? getId().hashCode() : 0;
}
public PropertyStorage getStorage() {
return storage;
}
@Override
public void setTransport(Transport transport) {
this.transport = transport;
PropertyStorageUtil.updateCollections(storage, transport);
}
/**
* Sample usage:
*
* <pre>
* {@code
* Project project = new Project(transport);
* Long timeStamp = Calendar.getInstance().getTimeInMillis();
* String key = "projkey" + timeStamp;
* String name = "project number " + timeStamp;
* String description = "some description for the project";
* project.setIdentifier(key)
* .setName(name)
* .setDescription(description)
* .create();
* }
* </pre>
* <p>
* Note: if {@code project} trackers have not been set with {@link Project#addTrackers}
* and if they have been cleared with {@link Project#clearTrackers},
* the created project will get the server default trackers (if any).
* Otherwise, the {@code Project} trackers will override the server default settings.
* </p>
*
* @return the newly created Project object.
* @throws RedmineAuthenticationException invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
*/
public Project create() throws RedmineException { | return transport.addObject(this, new RequestParam("include", | 3 |
zaclimon/xipl | tiflibrary/src/main/java/com/google/android/media/tv/companionlibrary/sync/EpgSyncJobService.java | [
"public class Advertisement implements Comparable<Advertisement> {\n /** The advertisement type for VAST. */\n public static final int TYPE_VAST = 0;\n\n private long mStartTimeUtcMillis;\n private long mStopTimeUtcMillis;\n private int mType;\n private String mRequestUrl;\n\n private Advertise... | import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.media.tv.TvContract;
import android.media.tv.TvInputInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.PersistableBundle;
import android.os.RemoteException;
import androidx.annotation.VisibleForTesting;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.Log;
import android.util.LongSparseArray;
import android.util.SparseArray;
import com.google.android.media.tv.companionlibrary.model.Advertisement;
import com.google.android.media.tv.companionlibrary.model.Channel;
import com.google.android.media.tv.companionlibrary.model.InternalProviderData;
import com.google.android.media.tv.companionlibrary.model.ModelUtils;
import com.google.android.media.tv.companionlibrary.model.ModelUtils.OnChannelDeletedCallback;
import com.google.android.media.tv.companionlibrary.model.Program;
import com.google.android.media.tv.companionlibrary.utils.Constants;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | .setPersisted(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build();
scheduleJob(context, jobInfo);
if (DEBUG) {
Log.d(TAG, "Job has been scheduled for every " + fullSyncPeriod + "ms");
}
}
/**
* Manually requests a job to run now to retrieve EPG content for the next hour.
*
* @param context Application's context.
* @param inputId Component name for the app's TvInputService. This can be received through an
* Intent extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
* @param jobServiceComponent The {@link EpgSyncJobService} class that will run.
*/
public static void requestImmediateSync(
Context context, String inputId, ComponentName jobServiceComponent) {
requestImmediateSync(
context, inputId, DEFAULT_IMMEDIATE_EPG_DURATION_MILLIS, jobServiceComponent);
}
/**
* Manually requests a job to run now.
*
* <p>To check the current status of the sync, register a {@link
* android.content.BroadcastReceiver} with an {@link android.content.IntentFilter} which checks
* for the action {@link #ACTION_SYNC_STATUS_CHANGED}.
*
* <p>The sync status is an extra parameter in the {@link Intent} with key {@link #SYNC_STATUS}.
* The sync status is either {@link #SYNC_STARTED} or {@link #SYNC_FINISHED}.
*
* <p>Check that the value of {@link #BUNDLE_KEY_INPUT_ID} matches your {@link
* android.media.tv.TvInputService}. If you're calling this from your setup activity, you can
* get the extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
*
* <p>
*
* @param context Application's context.
* @param inputId Component name for the app's TvInputService. This can be received through an
* Intent extra parameter {@link TvInputInfo#EXTRA_INPUT_ID}.
* @param syncDuration The duration of EPG content to fetch in milliseconds. For a manual sync,
* this should be relatively short. For a background sync this should be long.
* @param jobServiceComponent The {@link EpgSyncJobService} class that will run.
*/
public static void requestImmediateSync(
Context context, String inputId, long syncDuration, ComponentName jobServiceComponent) {
if (jobServiceComponent.getClass().isAssignableFrom(EpgSyncJobService.class)) {
throw new IllegalArgumentException("This class does not extend EpgSyncJobService");
}
PersistableBundle persistableBundle = new PersistableBundle();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
}
persistableBundle.putString(EpgSyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
persistableBundle.putLong(EpgSyncJobService.BUNDLE_KEY_SYNC_PERIOD, syncDuration);
JobInfo.Builder builder = new JobInfo.Builder(REQUEST_SYNC_JOB_ID, jobServiceComponent);
JobInfo jobInfo =
builder.setExtras(persistableBundle)
.setOverrideDeadline(EpgSyncJobService.OVERRIDE_DEADLINE_MILLIS)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.build();
scheduleJob(context, jobInfo);
if (DEBUG) {
Log.d(TAG, "Single job scheduled");
}
}
/**
* Cancels all pending jobs.
*
* @param context Application's context.
*/
public static void cancelAllSyncRequests(Context context) {
JobScheduler jobScheduler =
(JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.cancelAll();
}
/** @hide */
public class EpgSyncTask extends AsyncTask<Void, Void, Void> {
private final JobParameters params;
private String mInputId;
public EpgSyncTask(JobParameters params) {
this.params = params;
}
@Override
public Void doInBackground(Void... voids) {
PersistableBundle extras = params.getExtras();
mInputId = extras.getString(BUNDLE_KEY_INPUT_ID);
if (mInputId == null) {
broadcastError(ERROR_INPUT_ID_NULL);
return null;
}
if (isCancelled()) {
broadcastError(ERROR_EPG_SYNC_CANCELED);
return null;
}
List<Channel> tvChannels;
try {
tvChannels = getChannels();
} catch (EpgSyncException e) {
broadcastError(e.getReason());
return null;
}
ModelUtils.updateChannels(
mContext,
mInputId,
tvChannels,
new OnChannelDeletedCallback() {
@Override
public void onChannelDeleted(long rowId) {
SharedPreferences.Editor editor =
mContext.getSharedPreferences( | Constants.PREFERENCES_FILE_KEY, | 6 |
PearsonEducation/StatsPoller | src/main/java/com/pearson/statspoller/internal_metric_collectors/InternalCollectorFramework.java | [
"public class ApplicationConfiguration {\n\n private static final Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class.getName());\n \n public static final int VALUE_NOT_SET_CODE = -4444;\n \n private static boolean isInitializeSuccess_ = false; \n \n private static Hierarchic... | import com.pearson.statspoller.globals.ApplicationConfiguration;
import com.pearson.statspoller.globals.GlobalVariables;
import java.util.List;
import com.pearson.statspoller.metric_formats.graphite.GraphiteMetric;
import com.pearson.statspoller.metric_formats.opentsdb.OpenTsdbMetric;
import com.pearson.statspoller.utilities.core_utils.StackTrace;
import com.pearson.statspoller.utilities.core_utils.Threads;
import com.pearson.statspoller.utilities.file_utils.FileIo;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.pearson.statspoller.internal_metric_collectors;
/**
* @author Jeffrey Schmidt
*/
public abstract class InternalCollectorFramework {
private static final Logger logger = LoggerFactory.getLogger(InternalCollectorFramework.class.getName());
protected final int NUM_FILE_WRITE_RETRIES = 3;
protected final int DELAY_BETWEEN_WRITE_RETRIES_IN_MS = 100;
private final boolean isEnabled_;
private final long collectionInterval_;
private final String internalCollectorMetricPrefix_;
private final String outputFilePathAndFilename_;
private final boolean writeOutputFiles_;
private final String linuxProcFileSystemLocation_ = removeTrailingSlash(ApplicationConfiguration.getLinuxProcLocation());
private final String linuxSysFileSystemLocation_ = removeTrailingSlash(ApplicationConfiguration.getLinuxSysLocation());
private String fullInternalCollectorMetricPrefix_ = null;
private String finalOutputFilePathAndFilename_ = null;
public InternalCollectorFramework(boolean isEnabled, long collectionInterval, String internalCollectorMetricPrefix,
String outputFilePathAndFilename, boolean writeOutputFiles) {
this.isEnabled_ = isEnabled;
this.collectionInterval_ = collectionInterval;
this.internalCollectorMetricPrefix_ = internalCollectorMetricPrefix;
this.outputFilePathAndFilename_ = outputFilePathAndFilename;
this.writeOutputFiles_ = writeOutputFiles;
createFullInternalCollectorMetricPrefix();
this.finalOutputFilePathAndFilename_ = this.outputFilePathAndFilename_;
}
public void outputGraphiteMetrics(List<GraphiteMetric> graphiteMetrics) {
if (graphiteMetrics == null) return;
for (GraphiteMetric graphiteMetric : graphiteMetrics) {
try {
if (graphiteMetric == null) continue;
String graphiteMetricPathWithPrefix = fullInternalCollectorMetricPrefix_ + graphiteMetric.getMetricPath();
GraphiteMetric outputGraphiteMetric = new GraphiteMetric(graphiteMetricPathWithPrefix, graphiteMetric.getMetricValue(), graphiteMetric.getMetricTimestampInSeconds());
outputGraphiteMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet());
GlobalVariables.graphiteMetrics.put(outputGraphiteMetric.getHashKey(), outputGraphiteMetric);
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
}
if (writeOutputFiles_) {
String outputString = buildGraphiteMetricsFile(graphiteMetrics, true, fullInternalCollectorMetricPrefix_);
writeGraphiteMetricsToFile(outputString);
}
}
| public void outputOpentsdbMetricsAsGraphiteMetrics(List<OpenTsdbMetric> openTsdbMetrics) { | 3 |
kristian/JDigitalSimulator | src/main/java/lc/kra/jds/components/buildin/display/SevenSegmentDisplay.java | [
"public static String getTranslation(String key) { return getTranslation(key, TranslationType.TEXT); }",
"public static enum TranslationType { TEXT, ALTERNATIVE, TITLE, EXTERNAL, TOOLTIP, DESCRIPTION; }",
"public abstract class Component implements Paintable, Locatable, Moveable, Cloneable, Serializable {\n\tpr... | import lc.kra.jds.contacts.InputContact;
import static lc.kra.jds.Utilities.getTranslation;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import lc.kra.jds.Utilities.TranslationType;
import lc.kra.jds.components.Component;
import lc.kra.jds.components.Sociable;
import lc.kra.jds.contacts.Contact;
import lc.kra.jds.contacts.ContactList;
import lc.kra.jds.contacts.ContactUtilities; | /*
* JDigitalSimulator
* Copyright (C) 2017 Kristian Kraljic
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package lc.kra.jds.components.buildin.display;
/**
* Seven segment display (build-in component)
* @author Kristian Kraljic (kris@kra.lc)
*/
public class SevenSegmentDisplay extends Component implements Sociable {
private static final long serialVersionUID = 2l;
private static final String KEY;
static { KEY = "component.display."+SevenSegmentDisplay.class.getSimpleName().toLowerCase(); }
public static final ComponentAttributes componentAttributes = new ComponentAttributes(KEY, getTranslation(KEY), "group.display", getTranslation(KEY, TranslationType.DESCRIPTION), "Kristian Kraljic (kris@kra.lc)", 1);
private static final int POLYGONS_X[][] = {
{ 4, 8, 32, 36, 32, 8, 4},
{36, 40, 40, 36, 32, 32, 36},
{36, 40, 40, 36, 32, 32, 36},
{ 4, 8, 32, 36, 32, 8, 4},
{ 4, 8, 8, 4, 0, 0, 4},
{ 4, 8, 8, 4, 0, 0, 4},
{ 4, 8, 32, 36, 32, 8, 4},
};
private static final int POLYGONS_Y[][] = {
{ 4, 0, 0, 4, 8, 8, 4},
{ 4, 8, 32, 36, 32, 8, 4},
{36, 40, 64, 68, 64, 40, 36},
{68, 64, 64, 68, 72, 72, 68},
{36, 40, 64, 68, 64, 40, 36},
{ 4, 8, 32, 36, 32, 8, 4},
{36, 32, 32, 36, 40, 40, 36},
};
private Dimension size;
private InputContact[] inputs;
public SevenSegmentDisplay() {
size = new Dimension(60, 80);
inputs = new InputContact[7];
for(int input=0;input<inputs.length;input++)
inputs[input] = new InputContact(this);
ContactList.setContactLocations(this, inputs);
}
@Override public void paint(Graphics graphics) {
graphics.setColor(Color.BLACK);
graphics.drawRect(10, 0, size.width-10, size.height);
for(int input=0;input<inputs.length;input++) {
Polygon polygon = new Polygon(POLYGONS_X[input], POLYGONS_Y[input], 7);
polygon.translate(15, 4);
if(inputs[input].isCharged()) {
graphics.setColor(Color.RED);
graphics.fillPolygon(polygon);
}
graphics.setColor(Color.BLACK);
graphics.drawPolyline(polygon.xpoints, polygon.ypoints, polygon.npoints);
} | ContactUtilities.paintSolderingJoints(graphics, 10, 0, inputs); | 6 |
Sleeksnap/sleeksnap | src/org/sleeksnap/uploaders/text/Paste2Uploader.java | [
"public class HttpUtil {\n\n\t/**\n\t * Attempt to encode the string silenty\n\t * \n\t * @param string\n\t * The string\n\t * @return The encoded string\n\t */\n\tpublic static String encode(String string) {\n\t\ttry {\n\t\t\treturn URLEncoder.encode(string, \"UTF-8\");\n\t\t} catch (UnsupportedEncoding... | import org.sleeksnap.http.HttpUtil;
import org.sleeksnap.http.RequestData;
import org.sleeksnap.http.ResponseType;
import org.sleeksnap.upload.TextUpload;
import org.sleeksnap.uploaders.Uploader; | /**
* Sleeksnap, the open source cross-platform screenshot uploader
* Copyright (C) 2014 Nikki <nikki@nikkii.us>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sleeksnap.uploaders.text;
/**
* An uploader for the Paste2 pastebin.
*
* @author Nikki
*
*/
public class Paste2Uploader extends Uploader<TextUpload> {
private static final String APIURL = "http://paste2.org/new-paste";
@Override
public String upload(TextUpload t) throws Exception {
RequestData data = new RequestData();
data.put("code", t.getText())
.put("description", "")
.put("lang", "text")
.put("parent", "");
| return HttpUtil.executePost(APIURL, data, ResponseType.REDIRECT_URL); | 0 |
xdtianyu/Gallery | app/src/main/java/org/xdty/gallery/activity/ViewerActivity.java | [
"public class Application extends android.app.Application {\n\n private static AppComponent sAppComponent;\n\n @Inject\n protected Setting mSetting;\n\n public static AppComponent getAppComponent() {\n return sAppComponent;\n }\n\n @Override\n public void onCreate() {\n super.onCr... | import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.google.android.material.snackbar.Snackbar;
import androidx.core.app.ActivityCompat;
import androidx.core.view.ViewCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import org.xdty.gallery.R;
import org.xdty.gallery.application.Application;
import org.xdty.gallery.contract.ViewerContact;
import org.xdty.gallery.di.DaggerViewerComponent;
import org.xdty.gallery.di.modules.AppModule;
import org.xdty.gallery.di.modules.ViewerModule;
import org.xdty.gallery.model.Media;
import org.xdty.gallery.utils.Constants;
import org.xdty.gallery.view.PagerAdapter;
import org.xdty.gallery.view.ViewPager;
import java.util.List;
import javax.inject.Inject; | package org.xdty.gallery.activity;
public class ViewerActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener,
ViewerContact.View {
public static final String TAG = ViewerActivity.class.getSimpleName();
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
@Inject
protected ViewerContact.Presenter mPresenter;
private Toolbar mToolbar;
private ViewPager mViewPager; | private PagerAdapter mPagerAdapter; | 6 |
rhritz/kyberia-haiku | app/models/feeds/UserLocationHistory.java | [
"@Entity(\"Feed\")\npublic class Feed extends MongoEntity{\n\n public static DBCollection dbcol = null;\n private static final String key = \"feed_\";\n\n protected String name;\n protected ObjectId owner;\n protected List<ObjectId> nodes;\n protected Int... | import plugins.MongoDB;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import java.util.List;
import java.util.Map;
import play.Logger;
import play.mvc.Http.Request;
import play.mvc.Scope.RenderArgs;
import play.mvc.Scope.Session;
import models.Feed;
import models.Page;
import models.User;
import models.UserLocation; | /*
Kyberia Haiku - advanced community web application
Copyright (C) 2010 Robert Hritz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package models.feeds;
public class UserLocationHistory extends Feed{
private static final BasicDBObject sort = new BasicDBObject("time", -1); // TODO natural sort
@Override
public void getData( Map<String, String> params,
Request request,
Session session,
User user,
RenderArgs renderArgs) {
Integer start = 0;
Integer count = 30;
List<UserLocation> r = null;
try {
BasicDBObject query = new BasicDBObject("userid", user.getId());
DBCursor iobj = UserLocation.dbcol.find(query).sort(sort).skip(start).limit(count);
r = MongoDB.transform(iobj, MongoDB.getSelf().toUserLocation());
} catch (Exception ex) {
Logger.info("getUserThreads");
ex.printStackTrace();
Logger.info(ex.toString());
}
renderArgs.put(dataName, r);
}
@Override | public void init(Page page) { | 1 |
KlubJagiellonski/pola-android | app/src/main/java/pl/pola_app/ui/activity/CreateReportActivity.java | [
"public class PolaApplication extends Application {\n\n private PolaComponent component;\n public static Retrofit retrofit;\n\n @Override public void onCreate() {\n super.onCreate();\n\n component = PolaComponent.Initializer.init(this);\n if(BuildConfig.USE_FIREBASE) {\n Fir... | import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import pl.pola_app.PolaApplication;
import pl.pola_app.R;
import pl.pola_app.databinding.ActivityCreateReportBinding;
import pl.pola_app.helpers.EventLogger;
import pl.pola_app.helpers.SessionId;
import pl.pola_app.helpers.Utils;
import pl.pola_app.model.Report;
import pl.pola_app.model.ReportResult;
import pl.pola_app.network.Api;
import pl.tajchert.nammu.Nammu;
import pl.tajchert.nammu.PermissionCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber; | sessionId = SessionId.create(this);
if (getIntent() != null) {
productId = getIntent().getStringExtra("productId");
code = getIntent().getStringExtra("code");
}
Nammu.init(this);
setImageView(bitmaps);
if (logger == null) {
logger = new EventLogger(this);
}
logger.logLevelStart("report", code, sessionId.get());
binding.sendButton.setOnClickListener(this::clickSendButton);
}
private void setImageView(final ArrayList<Bitmap> bitmapsToSet) {
int margin = Utils.dpToPx(photoMarginDp);
binding.linearImageViews.removeAllViews();
boolean showAddButton = true;
if (bitmapsToSet != null && bitmapsToSet.size() > 0) {
int i = 0;
for (final Bitmap bitmap : bitmapsToSet) {
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.rightMargin = i == MAX_IMAGE_COUNT ? 0 : margin;
layoutParams.weight = 1f;
imageView.setLayoutParams(layoutParams);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialogDeletePhoto(bitmapsToSet.indexOf(bitmap));
}
});
imageView.setImageBitmap(bitmap);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
binding.linearImageViews.addView(imageView);
i++;
}
showAddButton = bitmapsToSet.size() <= MAX_IMAGE_COUNT;
}
if (showAddButton) {
//Add add button
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.weight = 1f;
imageView.setLayoutParams(layoutParams);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchCamera();
}
});
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_add_black_24dp));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
binding.linearImageViews.addView(imageView);
}
}
private void showDialogDeletePhoto(final int position) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (bitmaps != null && position < bitmaps.size()) {
bitmaps.remove(position);
setImageView(bitmaps);
}
if (bitmapsPaths != null && position < bitmapsPaths.size()) {
bitmapsPaths.remove(position);
}
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(CreateReportActivity.this);
builder.setMessage(getString(R.string.dialog_delete_photo))
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.setNegativeButton(getString(R.string.no), dialogClickListener)
.show();
}
private void launchCamera() {
String permissions[] = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
Nammu.askForPermission(CreateReportActivity.this, permissions, permissionCallback);
}
@Override
protected void onPause() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.cancel();
}
super.onPause();
}
public void clickSendButton(View view) {
CharSequence description = binding.descriptonEditText.getText();
if (description != null) {
sendReport(description.toString(), productId);
}
}
private void sendReport(String description, String productId) {
if (productId == null && (bitmapsPaths == null || bitmapsPaths.size() == 0)) {
Toast.makeText(CreateReportActivity.this, getString(R.string.toast_raport_error_no_pic), Toast.LENGTH_LONG).show();
return;
} else if (description == null) {
description = "";
}
numberOfImages = bitmapsPaths.size();
//get ext from path
Report report;
if (productId != null) {
report = new Report(description, productId, numberOfImages, MIME_TYPE, FILE_EXT);
} else {
report = new Report(description, numberOfImages, MIME_TYPE, FILE_EXT);
} | Api api = PolaApplication.retrofit.create(Api.class); | 0 |
mziccard/secureit | src/main/java/me/ziccard/secureit/async/upload/BluetoothPeriodicPositionUploaderTask.java | [
"public class SecureItPreferences {\n\t\n\tprivate SharedPreferences appSharedPrefs;\n private Editor prefsEditor;\n \n public static final String LOW = \"Low\";\n public static final String MEDIUM = \"Medium\";\n public static final String HIGH = \"High\";\n \n public static final String FRONT... | import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import me.ziccard.secureit.SecureItPreferences;
import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket;
import me.ziccard.secureit.config.Remote;
import me.ziccard.secureit.messages.BluetoothMessage;
import me.ziccard.secureit.messages.KeyRequest;
import me.ziccard.secureit.messages.MessageBuilder;
import me.ziccard.secureit.messages.MessageType;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast; | /*
* Copyright (c) 2013-2015 Marco Ziccardi, Luca Bonato
* Licensed under the MIT license.
*/
package me.ziccard.secureit.async.upload;
public class BluetoothPeriodicPositionUploaderTask extends AsyncTask<Void, Void, Void> {
private Context context;
/**
* Boolean true iff last thread iterations position has been sent
*/
private boolean dataSent = false;
private SecureItPreferences prefs;
/**
* Adapter for bluetooth services
*/
private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
/**
* Creates a BroadcastReceiver for ACTION_FOUND and ACTION_DISCOVERY_FINISHED
*/
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
private ArrayList<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
Log.i("BluetoothPeriodicPositionUploaderTask", "Discovered "+device.getName());
CharSequence text = "Discovered "+device.getName();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
// When ending the discovery
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
for (BluetoothDevice device : devices){
Log.i("DISCOVERY", "FINISHED");
try {
BluetoothSocket tmp = null;
tmp = device.createInsecureRfcommSocketToServiceRecord(Remote.BLUETOOTH_UUID);
if (tmp != null) {
Log.i("BluetoothPeriodicPositionUploaderTask", "Trying to connect to " + device.getName());
adapter.cancelDiscovery();
tmp.connect();
Log.i("BluetoothPeriodicPositionUploaderTask", "Connected to " + device.getName());
ObjectBluetoothSocket socket = new ObjectBluetoothSocket(tmp);
MessageBuilder builder = new MessageBuilder();
builder.setPhoneId(phoneId);
builder.setTimestamp(new Date());
//Sending hello message
BluetoothMessage message = builder.buildMessage(MessageType.HELLO);
ObjectOutputStream ostream = socket.getOutputStream();
ostream.writeObject(message);
Log.i("BluetoothPeriodicPositionUploaderTask", "Sent message " + message.getType().toString());
//Receiving key request
ObjectInputStream instream = socket.getInputStream(); | KeyRequest keyRequestMessage = (KeyRequest) instream.readObject(); | 4 |
igd-geo/mongomvcc | src/main/java/de/fhg/igd/mongomvcc/impl/MongoDBVLargeCollection.java | [
"public interface VCounter {\n\t/**\n\t * A thread safe method to get the next unique id\n\t * @return a unique id\n\t */\n\tpublic long getNextId();\n}",
"public interface VCursor extends Iterable<Map<String, Object>> {\n\t/**\n\t * @return the number of database objects this cursor points to\n\t */\n\tint size(... | import de.fhg.igd.mongomvcc.helper.Filter;
import de.fhg.igd.mongomvcc.helper.TransformingIterator;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import de.fhg.igd.mongomvcc.VCounter;
import de.fhg.igd.mongomvcc.VCursor;
import de.fhg.igd.mongomvcc.VLargeCollection; | // This file is part of MongoMVCC.
//
// Copyright (c) 2012 Fraunhofer IGD
//
// MongoMVCC is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// MongoMVCC 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 MongoMVCC. If not, see <http://www.gnu.org/licenses/>.
package de.fhg.igd.mongomvcc.impl;
/**
* Saves primitive byte arrays and {@link InputStream}s in MongoDB's
* {@link GridFS}.
* @author Michel Kraemer
*/
public class MongoDBVLargeCollection extends MongoDBVCollection implements
VLargeCollection {
/**
* A cursor which calls {@link AccessStrategy#onResolve(Map)} for
* each object
*/
private class MongoDBVLargeCursor extends MongoDBVCursor {
/**
* @see MongoDBVCursor#MongoDBVCursor(DBCursor, Filter)
*/
public MongoDBVLargeCursor(DBCursor delegate, Filter<DBObject> filter) {
super(delegate, filter);
}
@Override
public Iterator<Map<String, Object>> iterator() {
DefaultConvertStrategy cs = new DefaultConvertStrategy(_gridFS, getCounter());
_accessStrategy.setConvertStrategy(cs);
return new TransformingIterator<Map<String, Object>, Map<String, Object>>(super.iterator()) {
@Override
protected Map<String, Object> transform(Map<String, Object> input) {
_accessStrategy.onResolve(input);
return input;
}
};
}
}
/**
* The attribute that references a GridFS file's parent object
*/
private static final String PARENT = "parent";
/**
* The MongoDB GridFS storing binary data
*/
private final GridFS _gridFS;
/**
* A strategy used to access large objects
*/
private final AccessStrategy _accessStrategy;
/**
* Creates a new MongoDBVLargeCollection.
* @param delegate the actual MongoDB collection
* @param gridFS the MongoDB GridFS storing binary data
* @param branch the branch currently checked out
* @param counter a counter to generate unique IDs
*/
public MongoDBVLargeCollection(DBCollection delegate, GridFS gridFS, | MongoDBVBranch branch, VCounter counter) { | 0 |
igoticecream/Snorlax | app/src/main/java/com/icecream/snorlax/module/feature/rename/RenameFormat.java | [
"@SuppressWarnings({\"unused\", \"FieldCanBeLocal\", \"WeakerAccess\"})\npublic final class Decimals {\n\n\tpublic static String format(float value, int minIntegerDigits, int maxIntegerDigits, int minFractionDigits, int maxFractionDigits) {\n\t\treturn getDecimalFormat(minIntegerDigits, maxIntegerDigits, minFractio... | import static POGOProtos.Data.PokemonDataOuterClass.PokemonData;
import static java.lang.Integer.parseInt;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Singleton;
import android.support.annotation.Nullable;
import com.icecream.snorlax.common.Decimals;
import com.icecream.snorlax.common.Strings;
import com.icecream.snorlax.module.pokemon.Pokemon;
import com.icecream.snorlax.module.pokemon.PokemonFactory;
import com.icecream.snorlax.module.pokemon.PokemonMoveMeta;
import com.icecream.snorlax.module.pokemon.PokemonType; | /*
* Copyright (c) 2016. Pedro Diaz <igoticecream@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.icecream.snorlax.module.feature.rename;
@Singleton
final class RenameFormat {
private static final String BASE_NICK = "NICK";
private static final String BASE_LVL = "LVL";
private static final String BASE_IV = "IV";
private static final String BASE_ATT = "ATT";
private static final String BASE_DEF = "DEF";
private static final String BASE_STA = "STA";
private static final String BASE_MV1 = "MV1";
private static final String BASE_MV2 = "MV2";
private static final String BASE_MVT1 = "MVT1";
private static final String BASE_MVT2 = "MVT2";
private static final String BASE_MVP1 = "MVP1";
private static final String BASE_MVP2 = "MVP2";
private static final String BASE_TYP1 = "TYP1";
private static final String BASE_TYP2 = "TYP2";
private final PokemonFactory mPokemonFactory;
private final RenamePreferences mRenamePreferences;
@Inject
RenameFormat(PokemonFactory pokemonFactory, RenamePreferences renamePreferences) {
mPokemonFactory = pokemonFactory;
mRenamePreferences = renamePreferences;
}
String format(PokemonData pokemonData) throws NullPointerException, IllegalArgumentException { | final Pokemon pokemon = mPokemonFactory.with(pokemonData); | 2 |
winzillion/FluxJava | demo-eventbus/src/sharedTest/java/com/example/fluxjava/eventbus/StubAppConfig.java | [
"public class Bus implements IFluxBus {\n\n private EventBus mBus = EventBus.getDefault();\n\n @Override\n public void register(final Object inSubscriber) {\n this.mBus.register(inSubscriber);\n }\n\n @Override\n public void unregister(final Object inSubscriber) {\n this.mBus.unregis... | import android.app.Application;
import com.example.fluxjava.eventbus.domain.Bus;
import com.example.fluxjava.eventbus.domain.StubActionHelper;
import com.example.fluxjava.eventbus.domain.stores.StubTodoStore;
import com.example.fluxjava.eventbus.domain.stores.StubUserStore;
import io.wzcodes.fluxjava.FluxContext;
import java.util.HashMap;
import static com.example.fluxjava.eventbus.domain.Constants.DATA_TODO;
import static com.example.fluxjava.eventbus.domain.Constants.DATA_USER; | /*
* Copyright (C) 2016 Bugs will find a way (https://wznote.blogspot.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.fluxjava.eventbus;
public class StubAppConfig extends Application {
@Override
public void onCreate() {
super.onCreate();
this.setupFlux();
}
private void setupFlux() {
HashMap<Object, Class<?>> storeMap = new HashMap<>();
storeMap.put(DATA_USER, StubUserStore.class); | storeMap.put(DATA_TODO, StubTodoStore.class); | 2 |
gdgand/android-rxjava | 2016-06-15_hot_and_cold/app/src/test/java/com/gdgand/rxjava/rxjavasample/hotandcold/presentation/mvp/imgur/ImgurMvpPresenterTest.java | [
"public class TestSchedulerProxy {\n\n private static final TestScheduler SCHEDULER = new TestScheduler();\n private static final TestSchedulerProxy INSTANCE = new TestSchedulerProxy();\n\n static {\n try {\n RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() {\... | import com.google.common.collect.Lists;
import com.gdgand.rxjava.rxjavasample.hotandcold.TestSchedulerProxy;
import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.ImgurApi;
import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.Topic;
import com.gdgand.rxjava.rxjavasample.hotandcold.data.imgur.TopicResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.List;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import static com.gdgand.rxjava.rxjavasample.hotandcold.TestTransformer.pass;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; | package com.gdgand.rxjava.rxjavasample.hotandcold.presentation.mvp.imgur;
@RunWith(MockitoJUnitRunner.class)
@Ignore("java.lang.IllegalStateException at ImgurMvpPresenterTest.java:52")
public class ImgurMvpPresenterTest {
@Mock
ImgurApi imgurApi;
@Mock
ImgurMvpView view;
@InjectMocks
ImgurMvpPresenter presenter;
@Before
public void setup() {
presenter.attachView(view);
given(view.bind()).willReturn(pass());
given(view.injectProgress()).willReturn(pass());
}
@After
public void finish() {
presenter.detachView();
}
TestSchedulerProxy proxy = TestSchedulerProxy.get();
@Test
public void testRefreshTopics() throws Exception {
// given
TopicResponse response = new TopicResponse(); | List<Topic> topics = Lists.newArrayList(new Topic(), new Topic(), new Topic()); | 2 |
cwan/im-log-stats | im-log-stats-project/src/test/java/net/mikaboshi/intra_mart/tools/log_stats/parser/TransitionLogParserTest.java | [
"public class TransitionLog extends Log {\n\n\t/**\n\t * 遷移タイプ\n\t */\n\tpublic TransitionType type = null;\n\n\t/**\n\t * リモートホスト\n\t */\n\tpublic String requestRemoteHost = null;\n\n\t/**\n\t * リモートアドレス\n\t */\n\tpublic String requestRemoteAddress = null;\n\n\t/**\n\t * ユーザID\n\t */\n\tpublic String transitionAcc... | import static org.junit.Assert.assertEquals;
import java.io.File;
import java.text.SimpleDateFormat;
import net.mikaboshi.intra_mart.tools.log_stats.entity.TransitionLog;
import net.mikaboshi.intra_mart.tools.log_stats.entity.TransitionType;
import net.mikaboshi.intra_mart.tools.log_stats.parser.LogLayoutDefinitions;
import net.mikaboshi.intra_mart.tools.log_stats.parser.ParserParameter;
import net.mikaboshi.intra_mart.tools.log_stats.parser.TransitionLogParser;
import net.mikaboshi.intra_mart.tools.log_stats.parser.Version;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package net.mikaboshi.intra_mart.tools.log_stats.parser;
public class TransitionLogParserTest {
@Test
public void test_V61標準() {
| String layout = LogLayoutDefinitions.getStandardTransitionLogLayout(Version.V61);
| 2 |
BoD/irondad | src/main/java/org/jraf/irondad/handler/feed/FeedHandler.java | [
"public class Config {\n\n public static final boolean LOGD = true;\n\n}",
"public class Constants {\n public static final String TAG = \"irondad/\";\n\n public static final String PROJECT_FULL_NAME = \"BoD irondad\";\n public static final String PROJECT_URL = \"https://github.com/BoD/irondad\";\n ... | import org.jraf.irondad.Constants;
import org.jraf.irondad.handler.BaseHandler;
import org.jraf.irondad.handler.HandlerContext;
import org.jraf.irondad.protocol.Command;
import org.jraf.irondad.protocol.Connection;
import org.jraf.irondad.protocol.Message;
import org.jraf.irondad.util.Log;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import org.jraf.irondad.Config; | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.handler.feed;
public class FeedHandler extends BaseHandler {
private static final String TAG = Constants.TAG + FeedHandler.class.getSimpleName();
private String getUrl(List<String> textAsList, HandlerContext handlerContext) {
FeedHandlerConfig handlerConfig = (FeedHandlerConfig) handlerContext.getHandlerConfig();
String command = textAsList.get(0);
String url = handlerConfig.get(command);
return url;
}
@Override
public boolean isMessageHandled(String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext) {
String url = getUrl(textAsList, handlerContext);
return url != null;
}
@Override
protected void handleChannelMessage(Connection connection, String channel, String fromNickname, String text, List<String> textAsList, Message message,
HandlerContext handlerContext) throws Exception {
String url = getUrl(textAsList, handlerContext);
SyndEntry latestEntry = getLatestEntry(url);
if (latestEntry == null) return;
String entryLink = latestEntry.getLink();
if (entryLink == null) {
entryLink = latestEntry.getUri();
}
if (entryLink == null) { | if (Config.LOGD) Log.d(TAG, "handleChannelMessage Could not get link for this entry"); | 7 |
boybeak/DelegateAdapter | timepaper/src/main/java/com/github/boybeak/timepaper/adapter/holder/PhotoInfoHolder.java | [
"public abstract class AbsViewHolder<Delegate> extends RecyclerView.ViewHolder {\n\n private boolean isViewAttachedToWindow;\n\n public AbsViewHolder(View itemView) {\n super(itemView);\n }\n\n /**\n * @param context context\n * @param delegate may be a subclass of {@link DelegateImpl}\n ... | import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.View;
import com.github.boybeak.adapter.AbsViewHolder;
import com.github.boybeak.adapter.DelegateAdapter;
import com.github.boybeak.timepaper.R;
import com.github.boybeak.timepaper.adapter.delegate.PhotoInfoDelegate;
import com.github.boybeak.timepaper.model.Location;
import com.github.boybeak.timepaper.model.Photo; | package com.github.boybeak.timepaper.adapter.holder;
/**
* Created by gaoyunfei on 2017/9/6.
*/
public class PhotoInfoHolder extends AbsViewHolder<PhotoInfoDelegate> {
private AppCompatTextView photoInfoDescTv, photoInfoLocationTv;
public PhotoInfoHolder(View itemView) {
super(itemView);
photoInfoDescTv = findViewById(R.id.photo_info_description);
photoInfoLocationTv = findViewById(R.id.photo_info_location);
}
@Override
public void onBindView(Context context, PhotoInfoDelegate t, int position, DelegateAdapter adapter) {
| Photo photo = t.getSource(); | 4 |
ShprAlex/SproutLife | src/com/sproutlife/panel/GameMenu.java | [
"public class Settings {\n HashMap<String, Object> settings;\n\n public static String SEED_TYPE = \"seedType\";\n public static String LIFE_MODE = \"competitiveMode\";\n public static String MUTATION_ENABLED = \"mutationEnabled\";\n public static String MUTATION_RATE = \"mutationRate\";\n public s... | import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
import com.sproutlife.Settings;
import com.sproutlife.action.ExportPngAction;
import com.sproutlife.action.LoadGenomeAction;
import com.sproutlife.action.SaveGenomeAction;
import com.sproutlife.model.GameModel;
import com.sproutlife.panel.gamepanel.ScrollPanel; | /*******************************************************************************
* Copyright (c) 2016 Alex Shapiro - github.com/shpralex
* This program and the accompanying materials
* are made available under the terms of the The MIT License (MIT)
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* Development started with a Java based implementation created by Matthew Burke.
* http://burke9077.com
* Burke9077@gmail.com @burke9077 Creative Commons Attribution 4.0 International
*******************************************************************************/
package com.sproutlife.panel;
public class GameMenu extends JMenuBar implements ActionListener {
PanelController controller;
private JMenu fileMenu;
private JMenu gameMenu;
private JMenuItem exitMenuItem;
private JMenuItem stepGameMenuItem;
private Action enableMutationAction;
public GameMenu(PanelController controller) {
this.controller = controller;
initActions();
initMenu();
}
private GameModel getGameModel() {
return controller.getGameModel();
}
| public ScrollPanel getScrollPanel() { | 5 |
JanWiemer/jacis | src/main/java/org/jacis/store/StoreTxDemarcationExecutor.java | [
"@JacisApi\r\npublic class JacisTransactionHandle {\r\n\r\n /** The id of the transaction */\r\n private final String txId;\r\n /** Description for the transaction giving some more information about the purpose of the transaction (for logging and debugging) */\r\n private final String txDescription;\r\n /** A ... | import java.util.concurrent.locks.ReadWriteLock;
import org.jacis.container.JacisTransactionHandle;
import org.jacis.exception.JacisModificationListenerException;
import org.jacis.exception.JacisTrackedViewModificationException;
import org.jacis.plugin.JacisModificationListener;
import org.jacis.plugin.dirtycheck.JacisDirtyCheck;
import org.jacis.plugin.persistence.JacisPersistenceAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright (c) 2017. Jan Wiemer
*/
package org.jacis.store;
/**
* This class contains the code for actual transaction demarcation.
*
* @author Jan Wiemer
*/
class StoreTxDemarcationExecutor {
private Logger logger = LoggerFactory.getLogger(StoreTxDemarcationExecutor.class);
private <K, TV, CV> void executeDirtyCheck(JacisStoreAdminInterface<K, TV, CV> store, JacisStoreTxView<K, TV, CV> txView) {
JacisDirtyCheck<K, TV> dirtyChecker = store.getObjectTypeSpec().getDirtyCheck();
if (dirtyChecker == null) {
return;
}
logger.trace("dirty check {} on {} by Thread {}", txView, this, Thread.currentThread().getName());
for (StoreEntryTxView<K, TV, CV> entryTxView : txView.getAllEntryTxViews()) {
if (!entryTxView.isUpdated()) {
K key = entryTxView.getKey();
TV value = entryTxView.getValue();
TV origValue = entryTxView.getOrigValue();
boolean dirty = dirtyChecker.isDirty(key, origValue, value);
if (dirty) {
logger.debug("detected dirty object not marked as updated {}", key);
if (logger.isTraceEnabled()) {
logger.debug(" ... orig value: {}", origValue);
logger.debug(" ... new value : {}", value);
}
txView.updateValue(entryTxView, value);
}
}
}
}
| <K, TV, CV> void executePrepare(JacisStoreImpl<K, TV, CV> store, JacisTransactionHandle transaction, ReadWriteLock storeAccessLock) { | 0 |
mosmetro-android/mosmetro-android | app/src/main/java/pw/thedrhax/mosmetro/httpclient/InterceptedWebViewClient.java | [
"public abstract class InterceptorTask implements Task {\n private final Pattern pattern;\n\n protected HashMap<String,Object> vars = null;\n\n public InterceptorTask(String regex) {\n this(Pattern.compile(regex));\n }\n\n public InterceptorTask(Pattern pattern) {\n this.pattern = patte... | import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import pw.thedrhax.mosmetro.authenticator.InterceptorTask;
import pw.thedrhax.util.Listener;
import pw.thedrhax.util.Logger;
import pw.thedrhax.util.Randomizer;
import pw.thedrhax.util.Util; | /**
* Wi-Fi в метро (pw.thedrhax.mosmetro, Moscow Wi-Fi autologin)
* Copyright © 2015 Dmitry Karikh <the.dr.hax@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pw.thedrhax.mosmetro.httpclient;
/**
* Implementation of WebViewClient that ignores redirects in onPageFinished()
* Inspired by https://stackoverflow.com/a/25547544
*/
public class InterceptedWebViewClient extends WebViewClient {
private final Listener<String> currentUrl = new Listener<String>("") {
@Override
public void onChange(String new_value) {
Logger.log(InterceptedWebViewClient.this, "Current URL | " + new_value);
}
};
private final String key;
private final String interceptorScript;
private final List<InterceptorTask> interceptors = new LinkedList<>();
private Context context;
private Randomizer random;
private WebView webview;
private Client client = null;
private String next_referer;
private String referer;
public InterceptedWebViewClient(Context context, Client client, WebView webview) {
this.context = context;
this.random = new Randomizer(context);
this.webview = webview;
key = random.string(25).toLowerCase();
try {
interceptorScript = | Util.readAsset(context, "xhook.min.js") + | 4 |
roncoo/roncoo-adminlte-springmvc | src/main/java/com/roncoo/adminlte/service/impl/dao/impl/RolePermissionsDaoImpl.java | [
"public class RcRolePermissions implements Serializable {\r\n private Long id;\r\n\r\n private String statusId;\r\n\r\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\r\n private Date createTime;\r\n \r\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\r\n private Date updateTime;\r\n\r\n pri... | import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.roncoo.adminlte.bean.entity.RcRolePermissions;
import com.roncoo.adminlte.bean.entity.RcRolePermissionsExample;
import com.roncoo.adminlte.bean.entity.RcRolePermissionsExample.Criteria;
import com.roncoo.adminlte.service.impl.dao.RolePermissionsDao;
import com.roncoo.adminlte.service.impl.dao.impl.mybatis.RcRolePermissionsMapper;
| /*
* Copyright 2015-2016 RonCoo(http://www.roncoo.com) Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.roncoo.adminlte.service.impl.dao.impl;
@Repository
public class RolePermissionsDaoImpl implements RolePermissionsDao {
@Autowired
private RcRolePermissionsMapper mapper;
@Override
| public List<RcRolePermissions> selectByRoleId(long id) {
| 0 |
FIXTradingCommunity/timpani | src/test/java/org/fixtrading/timpani/securitydef/datastore/MongoDBSecurityDefinitionStoreTest.java | [
"public class MongoDBSecurityDefinitionStore implements SecurityDefinitionStore {\n\n class SecurityDefinitionBlock implements Block<Document> {\n\n private final Consumer<SecurityDefinitionImpl> consumer;\n private int count = 0;\n\n public SecurityDefinitionBlock(Consumer<SecurityDefinitionImpl> consume... | import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import org.fixtrading.timpani.securitydef.datastore.MongoDBSecurityDefinitionStore;
import org.fixtrading.timpani.securitydef.messages.SecurityDefinition;
import org.fixtrading.timpani.securitydef.messages.SecurityDefinitionImpl;
import org.fixtrading.timpani.securitydef.messages.SecurityDefinitionRequestImpl;
import org.fixtrading.timpani.securitydef.messages.SecurityIDSource;
import org.fixtrading.timpani.securitydef.messages.SecurityRequestType;
import org.fixtrading.timpani.securitydef.messages.SecurityDefinitionImpl.MarketSegmentImpl;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test; | package org.fixtrading.timpani.securitydef.datastore;
// Uncomment to run this test. Prerequisite: datastore cluster must be running.
@Ignore
public class MongoDBSecurityDefinitionStoreTest {
private MongoDBSecurityDefinitionStore store; | class TestConsumer implements Consumer<SecurityDefinition> { | 1 |
jeperon/freqtrade-java | src/main/java/ch/urbanfox/freqtrade/telegram/command/StatusCommandHandler.java | [
"@Component\npublic class FreqTradeMainRunner {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(FreqTradeMainRunner.class);\n\n private State state = State.RUNNING;\n\n @Autowired\n private FreqTradeProperties properties;\n\n @Autowired\n private AnalyzeService analyzeService;\n\n... | import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import ch.urbanfox.freqtrade.FreqTradeMainRunner;
import ch.urbanfox.freqtrade.exchange.FreqTradeExchangeService;
import ch.urbanfox.freqtrade.telegram.TelegramService;
import ch.urbanfox.freqtrade.trade.TradeEntity;
import ch.urbanfox.freqtrade.trade.TradeService;
import ch.urbanfox.freqtrade.type.State; | package ch.urbanfox.freqtrade.telegram.command;
/**
* Handler for /status
*/
@Component
public class StatusCommandHandler extends AbstractCommandHandler {
@Autowired
private FreqTradeMainRunner runner;
@Autowired
private FreqTradeExchangeService exchangeService;
@Autowired
private TradeService tradeService;
@Autowired
private TelegramService telegramService;
@Override
public String getCommandName() {
return "/status";
}
/**
* Returns the current status
*
* @throws IOException if any error occurs while contacting the exchange
* @throws TelegramApiException if any error occurs while using the Telegram API
*/
@Override
protected void handleInternal(String[] params) throws Exception {
// Fetch open trade
List<TradeEntity> trades = tradeService.findAllOpenTrade(); | if (runner.getState() != State.RUNNING) { | 5 |
fedefernandez/MyAppList | application/src/main/java/com/projectsexception/myapplist/fragments/IgnoredListFragment.java | [
"public class MyAppListPreferenceActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {\n\n static final String KEY_EMAIL = \"mail\";\n public static final String KEY_HIDE_SYSTEM_APPS = \"hide_system_apps\";\n public static final String ... | import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.projectsexception.myapplist.MyAppListPreferenceActivity;
import com.projectsexception.myapplist.R;
import com.projectsexception.myapplist.model.AppInfo;
import com.projectsexception.myapplist.model.MyAppListDbHelper;
import com.projectsexception.myapplist.view.AppListIgnoredAdapter;
import com.projectsexception.myapplist.work.AppListLoader;
import java.util.ArrayList;
import java.util.List;
import butterknife.InjectView;
import butterknife.ButterKnife; | package com.projectsexception.myapplist.fragments;
public class IgnoredListFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<ArrayList<AppInfo>>,
AdapterView.OnItemClickListener {
public static interface CallBack {
MyAppListDbHelper getHelper();
}
private CallBack mCallBack;
private MenuItem mRefreshItem;
private AppListIgnoredAdapter mAdapter;
private SparseBooleanArray mCheckItems;
private boolean mListShown;
private boolean mAnimations;
@InjectView(android.R.id.list) ListView mListView;
@InjectView(android.R.id.empty) View mEmptyView;
@InjectView(android.R.id.progress) View mProgress;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof CallBack) {
mCallBack = (CallBack) activity;
} else {
throw new IllegalStateException("activity must implement fragment's callback");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
ButterKnife.inject(this, view);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mCheckItems = new SparseBooleanArray();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
mAnimations = prefs.getBoolean(MyAppListPreferenceActivity.KEY_ANIMATIONS, true);
mAdapter = new AppListIgnoredAdapter(getActivity(), mAnimations);
mListView = getListView();
mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
mListView.setAdapter(mAdapter);
mListView.setFastScrollEnabled(true);
mListView.setOnItemClickListener(this);
// Start out with a progress indicator.
setListShown(false);
setHasOptionsMenu(true);
getLoaderManager().initLoader(0, null, this);
}
@Override
public void onResume() {
super.onResume();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean animations = prefs.getBoolean(MyAppListPreferenceActivity.KEY_ANIMATIONS, true);
if (mAnimations != animations) {
mAnimations = animations;
mAdapter.setAnimations(animations);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_ign, menu);
mRefreshItem = menu.findItem(R.id.menu_refresh);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_select_all) {
boolean select = false;
// By default we are going to uncheck all
for (int i = 0; i < mListView.getCount(); ++i) {
if (!mCheckItems.get(i, false)) {
// If there are one element not checked
select = true;
break;
}
}
for (int i = 0; i < mListView.getCount(); ++i) {
mListView.setItemChecked(i, select);
mCheckItems.put(i, select);
}
return true;
} else if (item.getItemId() == R.id.menu_refresh) {
getLoaderManager().restartLoader(0, null, this);
return true;
} else if (item.getItemId() == R.id.menu_save) {
saveSelectedItems(getSelectedItems());
getActivity().finish(); return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public Loader<ArrayList<AppInfo>> onCreateLoader(int id, Bundle args) {
loading(true); | return new AppListLoader(getActivity()); | 4 |
esmasui/deb-kitkat-storage-access-framework | KitKatStorageProject/LiveSDK-for-Android/unittest/src/com/microsoft/live/unittest/UploadTest.java | [
"public final class JsonKeys {\n\n public static final String ACCESS = \"access\";\n public static final String ACCOUNT = \"account\";\n public static final String CODE = \"code\";\n public static final String CREATED_TIME = \"created_time\";\n public static final String COMMENTS_COUNT = \"comments_c... | import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.message.BasicStatusLine;
import org.json.JSONObject;
import android.text.TextUtils;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveUploadOperationListener;
import com.microsoft.live.OverwriteOption;
import com.microsoft.live.constants.JsonKeys;
import com.microsoft.live.constants.Paths;
import com.microsoft.live.mock.MockHttpEntity;
import com.microsoft.live.mock.MockHttpResponse;
import com.microsoft.live.test.util.UploadAsyncRunnable;
import com.microsoft.live.test.util.UploadOperationQueueingListener;
import com.microsoft.live.util.NullLiveUploadOperationListener; | package com.microsoft.live.unittest;
public class UploadTest extends ApiTest<LiveOperation, LiveUploadOperationListener> {
private static final String SOURCE = "http://download.location.com/some/path";
private static final InputStream FILE;
private static final String FILE_ID = "file.1231";
private static final String FILENAME = "some_file.txt";
static {
FILE = new ByteArrayInputStream("File contents".getBytes());
}
public void testAsyncFileNull() {
try {
this.liveConnectClient.uploadAsync(Paths.ME_SKYDRIVE,
null,
FILE, | NullLiveUploadOperationListener.INSTANCE); | 6 |
dmytroKarataiev/EarthquakeSurvival | app/src/main/java/com/adkdevelopment/earthquakesurvival/ui/geofence/GeofenceService.java | [
"public class Feature implements Parcelable {\n\n @SerializedName(\"type\")\n @Expose\n private String type;\n @SerializedName(\"properties\")\n @Expose\n private Properties properties;\n @SerializedName(\"geometry\")\n @Expose\n private Geometry geometry;\n @SerializedName(\"id\")\n ... | import android.app.IntentService;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.Feature;
import com.adkdevelopment.earthquakesurvival.ui.DetailActivity;
import com.adkdevelopment.earthquakesurvival.ui.PagerActivity;
import com.adkdevelopment.earthquakesurvival.R;
import com.adkdevelopment.earthquakesurvival.data.objects.earthquake.EarthquakeObject;
import com.adkdevelopment.earthquakesurvival.utils.LocationUtils;
import com.adkdevelopment.earthquakesurvival.utils.Utilities;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | /*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* 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.adkdevelopment.earthquakesurvival.ui.geofence;
/**
* Sends
* Created by karataev on 4/4/16.
*/
public class GeofenceService extends IntentService {
private static final String TAG = GeofenceService.class.getSimpleName();
public GeofenceService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
// if the event has an error - log the textual info about it
if (geofencingEvent.hasError()) {
String textualError = LocationUtils.getErrorString(this, geofencingEvent.getErrorCode());
Log.e(TAG, "onHandleIntent: " + textualError);
return;
}
// extract geofence event
int transition = geofencingEvent.getGeofenceTransition();
if (transition == Geofence.GEOFENCE_TRANSITION_ENTER ||
transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> geoEvents = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
List<String> geofenceDetails = LocationUtils
.getTransitionDetails(this, transition, geoEvents);
if (Utilities.getNotificationsPrefs(getBaseContext())
&& geofenceDetails != null && geofenceDetails.size() > 0) {
sendNotification(geofenceDetails);
}
} else {
Log.e(TAG, getString(R.string.geofence_error_invalid_type, transition));
}
}
/**
* Sends a notification to the phone
* @param notificationDetails String with details to show in the notification
*/
private void sendNotification(List<String> notificationDetails) {
Context context = getBaseContext();
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(context, DetailActivity.class); | notificationIntent.putStringArrayListExtra(Feature.GEOFENCE, (ArrayList<String>) notificationDetails); | 0 |
kpavlov/fixio | core/src/test/java/fixio/handlers/CompositeFixApplicationAdapterTest.java | [
"public interface FixMessage {\n\n String FIX_4_0 = \"FIX.4.0\";\n String FIX_4_1 = \"FIX.4.1\";\n String FIX_4_2 = \"FIX.4.2\";\n String FIX_4_3 = \"FIX.4.3\";\n String FIX_4_4 = \"FIX.4.4\";\n String FIX_5_0 = \"FIXT.1.1\";\n\n FixMessageHeader getHeader();\n\n List<FixMessageFragment> get... | import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.same;
import static org.mockito.Mockito.when;
import fixio.fixprotocol.FixMessage;
import fixio.fixprotocol.FixMessageBuilder;
import fixio.fixprotocol.FixMessageBuilderImpl;
import fixio.fixprotocol.FixMessageImpl;
import fixio.validator.FixMessageValidator;
import io.netty.channel.ChannelHandlerContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.Arrays; | /*
* Copyright 2014 The FIX.io Project
*
* The FIX.io Project 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 fixio.handlers;
@RunWith(org.mockito.junit.MockitoJUnitRunner.class)
public class CompositeFixApplicationAdapterTest {
private CompositeFixApplicationAdapter adapter;
@Mock
private FixMessageValidator messageValidator1;
@Mock
private FixMessageValidator messageValidator2;
@Mock
private FixMessageHandler messageHandler1;
@Mock
private FixMessageHandler messageHandler2;
@Mock
private FixMessageHandler messageHandler3;
@Mock
private ChannelHandlerContext ctx;
private ArrayList<Object> out;
@Before
public void setUp() {
adapter = new CompositeFixApplicationAdapter(
Arrays.asList(messageValidator1, messageValidator2),
Arrays.asList(messageHandler1, messageHandler2, messageHandler3));
out = new ArrayList<>();
}
@Test
public void testOnMessage() throws Exception { | final FixMessage message = new FixMessageImpl(); | 3 |
Valkryst/Schillsaver | src/main/java/Schillsaver/job/encode/FFMPEGEndec.java | [
"public class Job implements Serializable {\n private static final long serialVersionUID = 1;\n\n /** The name of the Job. */\n @Getter private final String name;\n /** The output directory. */\n @Getter private final String outputDirectory;\n /** The archiver used to archive the file(s). */\n ... | import Schillsaver.job.Job;
import Schillsaver.mvc.controller.MainController;
import Schillsaver.mvc.model.MainModel;
import Schillsaver.mvc.view.MainView;
import Schillsaver.setting.BlockSize;
import Schillsaver.setting.FrameDimension;
import Schillsaver.setting.FrameRate;
import Schillsaver.setting.Settings;
import javafx.application.Platform;
import javafx.scene.control.Tab;
import javafx.scene.control.TextArea;
import lombok.NonNull;
import org.apache.commons.io.FilenameUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List; | package Schillsaver.job.encode;
public class FFMPEGEndec extends Endec {
@Override
public List<Thread> prepareEncodingJobs(final @NonNull MainController controller) { | final MainModel model = (MainModel) controller.getModel(); | 2 |
superzanti/ServerSync | src/main/java/com/superzanti/serversync/config/SyncConfig.java | [
"@Command(name = \"ServerSync\", mixinStandardHelpOptions = true, version = RefStrings.VERSION, description = \"A utility for synchronizing a server<->client style game.\")\npublic class ServerSync implements Callable<Integer> {\n\n /* AWT EVENT DISPATCHER THREAD */\n\n public static final String APPLICATION_... | import com.superzanti.serversync.ServerSync;
import com.superzanti.serversync.files.DirectoryEntry;
import com.superzanti.serversync.files.EDirectoryMode;
import com.superzanti.serversync.files.FileRedirect;
import com.superzanti.serversync.util.enums.EConfigType;
import com.superzanti.serversync.util.enums.EServerMode;
import com.superzanti.serversync.util.enums.ETheme;
import java.io.IOException;
import java.util.*; | package com.superzanti.serversync.config;
/**
* Handles all functionality to do with serversyncs config file and
* other configuration properties
*
* @author Rheimus
*/
public class SyncConfig {
public final EConfigType configType;
// COMMON //////////////////////////////
public String SERVER_IP = "127.0.0.1";
public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg");
public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>();
public Locale LOCALE = Locale.getDefault();
public ETheme THEME = ETheme.BLUE_YELLOW;
public int BUFFER_SIZE = 1024 * 64;
////////////////////////////////////////
// SERVER //////////////////////////////
public int SERVER_PORT = 38067;
public Boolean PUSH_CLIENT_MODS = false;
public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**");
public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry(
"mods", | EDirectoryMode.mirror | 2 |
ThomasDaheim/ownNoteEditor | ownNoteEditor/src/main/java/tf/ownnote/ui/helper/OwnNoteFileManager.java | [
"public class OwnNoteEditor implements Initializable, IFileChangeSubscriber, INoteCRMDS {\n\n private final List<String> filesInProgress = new LinkedList<>();\n\n private final static OwnNoteEditorParameters parameters = OwnNoteEditorParameters.getInstance();\n \n public final static String DATE_TIME_FO... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import org.apache.commons.io.FileUtils;
import tf.ownnote.ui.main.OwnNoteEditor;
import tf.ownnote.ui.notes.INoteCRMDS;
import tf.ownnote.ui.notes.Note;
import tf.ownnote.ui.notes.NoteMetaData;
import tf.ownnote.ui.notes.NoteVersion;
import tf.ownnote.ui.tags.TagData;
import tf.ownnote.ui.tags.TagManager;
import tf.ownnote.ui.tasks.TaskManager; | assert groupName != null;
String result = null;
if (TagManager.isSpecialGroup(groupName)) {
// only the note name
result = "";
} else {
// group name upfront
result = "[" + groupName + "] ";
}
return result;
}
@Override
public boolean createNote(final String groupName, final String noteName) {
assert groupName != null;
assert noteName != null;
boolean result = true;
initFilesInProgress();
final String newFileName = buildNoteName(groupName, noteName);
try {
Path newPath = Files.createFile(Paths.get(this.notesPath, newFileName));
// TF, 20151129
// update notesList as well
final LocalDateTime filetime = LocalDateTime.ofInstant((new Date(newPath.toFile().lastModified())).toInstant(), ZoneId.systemDefault());
final Note noteRow = new Note(groupName, noteName);
noteRow.setNoteModified(FormatHelper.getInstance().formatFileTime(filetime));
noteRow.setNoteDelete(OwnNoteFileManager.deleteString);
// TFE, 20210113: init data as well - especially charset
noteRow.setNoteFileContent("");
noteRow.setMetaData(new NoteMetaData(noteRow));
noteRow.getMetaData().setCharset(StandardCharsets.UTF_8);
// use filename and not notename since duplicate note names can exist in diffeent groups
notesList.put(newFileName, noteRow);
// save metadata
saveNote(noteRow);
} catch (IOException ex) {
Logger.getLogger(OwnNoteFileManager.class.getName()).log(Level.SEVERE, null, ex);
result = false;
}
resetFilesInProgress();
return result;
}
public Note readNote(final Note curNote, final boolean forceRead) {
assert curNote != null;
// TFE, 20201231: only read if you really have to
if (curNote.getNoteFileContent() == null || forceRead) {
final StringBuffer result = new StringBuffer("");
final Path readPath = Paths.get(notesPath, buildNoteName(curNote.getGroupName(), curNote.getNoteName()));
if (StandardCharsets.ISO_8859_1.equals(curNote.getMetaData().getCharset())) {
try {
result.append(Files.readAllBytes(readPath));
} catch (IOException ex) {
Logger.getLogger(OwnNoteFileManager.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
try (final BufferedReader reader =
new BufferedReader(new InputStreamReader(new FileInputStream(readPath.toFile()), StandardCharsets.UTF_8))) {
boolean firstLine = true;
String str;
while ((str = reader.readLine()) != null) {
if (!firstLine) {
// don't use System.lineseparator() to avoid messup with metadata parsing
result.append("\n");
}
result.append(str);
firstLine = false;
}
} catch (IOException ex) {
Logger.getLogger(OwnNoteFileManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
// TFE; 20200814: store content in Note
curNote.setNoteFileContent(result.toString());
// TFE, 20210121: things get too complicated with metadata - at least check file consistency
if (!VerifyNoteContent.getInstance().verifyNoteFileContent(curNote) && myEditor != null) {
final ButtonType buttonOK = new ButtonType("OK", ButtonBar.ButtonData.OK_DONE);
myEditor.showAlert(
Alert.AlertType.ERROR,
"Error",
"File inconsistency found!",
"File: " + buildNoteName(curNote.getGroupName(), curNote.getNoteName()) + "\nCheck error log for further details.",
buttonOK);
}
}
return curNote;
}
@Override
public boolean saveNote(final Note note) {
return saveNote(note, false);
}
public boolean saveNote(final Note note, final boolean suppressMessages) {
assert note != null;
boolean result = true;
initFilesInProgress();
final String newFileName = buildNoteName(note);
// TFE, 20201230: update task ids | TaskManager.getInstance().replaceTaskDataInNote(note, suppressMessages); | 7 |
MaxSmile/EasyVPN-Free | Android-code/app/src/main/java/de/blinkt/openvpn/core/OpenVPNService.java | [
"public class ServerActivity extends BaseActivity {\n\n private static final int START_VPN_PROFILE = 70;\n private BroadcastReceiver br;\n private BroadcastReceiver trafficReceiver;\n public final static String BROADCAST_ACTION = \"de.blinkt.openvpn.VPN_STATUS\";\n\n private static OpenVPNService mVP... | import android.Manifest.permission;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.UiModeManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.VpnService;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.system.OsConstants;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.vasilkoff.easyvpnfree.BuildConfig;
import com.vasilkoff.easyvpnfree.R;
import com.vasilkoff.easyvpnfree.activity.ServerActivity;
import com.vasilkoff.easyvpnfree.util.TotalTraffic;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Locale;
import java.util.Vector;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.VpnStatus.ByteCountListener;
import de.blinkt.openvpn.core.VpnStatus.ConnectionStatus;
import de.blinkt.openvpn.core.VpnStatus.StateListener;
import static de.blinkt.openvpn.core.NetworkSpace.ipAddress;
import static de.blinkt.openvpn.core.VpnStatus.ConnectionStatus.LEVEL_CONNECTED;
import static de.blinkt.openvpn.core.VpnStatus.ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT; | }
}
}
synchronized (mProcessLock) {
if (mProcessThread != null) {
mProcessThread.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//ignore
}
}
}
}
private OpenVPNManagement instantiateOpenVPN3Core() {
try {
Class cl = Class.forName("de.blinkt.openvpn.core.OpenVPNThreadv3");
return (OpenVPNManagement) cl.getConstructor(OpenVPNService.class, VpnProfile.class).newInstance(this, mProfile);
} catch (IllegalArgumentException | InstantiationException | InvocationTargetException |
NoSuchMethodException | ClassNotFoundException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
@Override
public void onDestroy() {
synchronized (mProcessLock) {
if (mProcessThread != null) {
mManagement.stopVPN(true);
}
}
if (mDeviceStateReceiver != null) {
this.unregisterReceiver(mDeviceStateReceiver);
}
// Just in case unregister for state
VpnStatus.removeStateListener(this);
VpnStatus.flushLog();
}
private String getTunConfigString() {
// The format of the string is not important, only that
// two identical configurations produce the same result
String cfg = "TUNCFG UNQIUE STRING ips:";
if (mLocalIP != null)
cfg += mLocalIP.toString();
if (mLocalIPv6 != null)
cfg += mLocalIPv6;
cfg += "routes: " + TextUtils.join("|", mRoutes.getNetworks(true)) + TextUtils.join("|", mRoutesv6.getNetworks(true));
cfg += "excl. routes:" + TextUtils.join("|", mRoutes.getNetworks(false)) + TextUtils.join("|", mRoutesv6.getNetworks(false));
cfg += "dns: " + TextUtils.join("|", mDnslist);
cfg += "domain: " + mDomain;
cfg += "mtu: " + mMtu;
return cfg;
}
public ParcelFileDescriptor openTun() {
//Debug.startMethodTracing(getExternalFilesDir(null).toString() + "/opentun.trace", 40* 1024 * 1024);
Builder builder = new Builder();
VpnStatus.logInfo(R.string.last_openvpn_tun_config);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && mProfile.mAllowLocalLAN) {
allowAllAFFamilies(builder);
}
if (mLocalIP == null && mLocalIPv6 == null) {
VpnStatus.logError(getString(R.string.opentun_no_ipaddr));
return null;
}
if (mLocalIP != null) {
addLocalNetworksToRoutes();
try {
builder.addAddress(mLocalIP.mIp, mLocalIP.len);
} catch (IllegalArgumentException iae) {
VpnStatus.logError(R.string.dns_add_error, mLocalIP, iae.getLocalizedMessage());
return null;
}
}
if (mLocalIPv6 != null) {
String[] ipv6parts = mLocalIPv6.split("/");
try {
builder.addAddress(ipv6parts[0], Integer.parseInt(ipv6parts[1]));
} catch (IllegalArgumentException iae) {
VpnStatus.logError(R.string.ip_add_error, mLocalIPv6, iae.getLocalizedMessage());
return null;
}
}
for (String dns : mDnslist) {
try {
builder.addDnsServer(dns);
} catch (IllegalArgumentException iae) {
VpnStatus.logError(R.string.dns_add_error, dns, iae.getLocalizedMessage());
}
}
String release = Build.VERSION.RELEASE;
if ((Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && !release.startsWith("4.4.3")
&& !release.startsWith("4.4.4") && !release.startsWith("4.4.5") && !release.startsWith("4.4.6"))
&& mMtu < 1280) {
VpnStatus.logInfo(String.format(Locale.US, "Forcing MTU to 1280 instead of %d to workaround Android Bug #70916", mMtu));
builder.setMtu(1280);
} else {
builder.setMtu(mMtu);
}
| Collection<ipAddress> positiveIPv4Routes = mRoutes.getPositiveIPList(); | 6 |
SamuelGjk/GComic | app/src/main/java/moe/yukinoneko/gcomic/module/gallery/GalleryActivity.java | [
"public abstract class ToolBarActivity<T extends BasePresenter> extends BaseActivity<T> {\n protected ActionBar mActionBar;\n\n @BindView(R.id.toolbar)\n protected Toolbar mToolbar;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n ... | import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPropertyAnimatorListenerAdapter;
import android.support.v7.widget.AppCompatSeekBar;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import moe.yukinoneko.gcomic.R;
import moe.yukinoneko.gcomic.base.ToolBarActivity;
import moe.yukinoneko.gcomic.data.ComicData;
import moe.yukinoneko.gcomic.download.DownloadTasksManager;
import moe.yukinoneko.gcomic.network.GComicApi;
import moe.yukinoneko.gcomic.utils.SnackbarUtils;
import moe.yukinoneko.gcomic.utils.Utils;
import moe.yukinoneko.gcomic.widget.HackyViewPager; |
galleryPager.setLocked(true);
galleryPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
seekBar.setProgress(position - 1);
intCurPage = position;
if (intCurPage > mPagerAdapter.getCount() - 2) {
intCurPage = mPagerAdapter.getCount() - 2;
} else if (intCurPage < 1) {
intCurPage = 1;
}
curPage.setText(String.valueOf(intCurPage));
if (position == 0) {
galleryPager.setLocked(true);
seekBar.setEnabled(false);
mHandler.postDelayed(mPreviousRunnable, 1000);
} else if (position == mPagerAdapter.getCount() - 1) {
galleryPager.setLocked(true);
seekBar.setEnabled(false);
mHandler.postDelayed(mNextRunnable, 1000);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
mPagerAdapter = new GalleryPagerAdapter(getSupportFragmentManager());
galleryPager.setAdapter(mPagerAdapter);
seekBar.setEnabled(false);
seekBar.setKeyProgressIncrement(1);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
progress = i;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
galleryPager.setCurrentItem(progress + 1, false);
}
});
loadErrorLayout.setBackgroundColor(0xFF444444);
loadErrorTips.setTextColor(0x80FFFFFF);
Intent intent = getIntent();
mComicId = intent.getIntExtra(GALLERY_CMOIC_ID, -1);
firstLetter = intent.getStringExtra(GALLERY_CMOIC_FIRST_LETTER);
mChapters = intent.getParcelableArrayListExtra(GALLERY_CHAPTER_LIST);
mCurChapterPosition = intent.getIntExtra(GALLERY_CHAPTER_POSITION, -1);
mLastChapterPosition = mCurChapterPosition;
mHistoryBrowsePosition = intent.getIntExtra(GALLERY_BROWSE_POSITION, 1);
mToolbar.setTitle(mChapters.get(mCurChapterPosition).chapterTitle);
galleryPager.setCurrentItem(1, false);
fetchChapterContent(mChapters.get(mCurChapterPosition).chapterId);
}
@Override
public void showMessageSnackbar(int resId) {
SnackbarUtils.showShort(galleryPager, resId);
}
@Override
public void updatePagerContent(List<String> urls, List<byte[]> bytes, boolean isFromDisk) {
mToolbar.setTitle(mChapters.get(mCurChapterPosition).chapterTitle);
int count = isFromDisk ? bytes.size() : urls.size();
totalPages.setText(String.valueOf(count));
seekBar.setMax(count - 1);
galleryPager.setCurrentItem(1, false);
mPagerAdapter.replaceAll(urls, bytes, isFromDisk);
galleryPager.setLocked(false);
seekBar.setEnabled(true);
if (useHistory) {
useHistory = false;
galleryPager.setCurrentItem(mHistoryBrowsePosition, false);
}
// galleryPager.setCurrentItem(1, false);
}
@Override
public void loadError() {
galleryPager.setCurrentItem(intCurPage < 1 ? 1 : intCurPage);
mCurChapterPosition = mLastChapterPosition;
if (mPagerAdapter.getCount() == 3) {
loadErrorLayout.setVisibility(View.VISIBLE);
} else {
galleryPager.setLocked(false);
seekBar.setEnabled(true);
}
}
private void fetchChapterContent(int chapterId) {
// @formatter:off
// presenter.updateReadHistory(mComicId, chapterId);
String url = GComicApi.getInstance().generateDownloadUrl(firstLetter, mComicId, chapterId); | String path = DownloadTasksManager.getInstance(this).generatePath(url); | 2 |
byhieg/easyweather | app/src/main/java/com/weather/byhieg/easyweather/MyApplication.java | [
"public class DaoMaster extends AbstractDaoMaster {\n public static final int SCHEMA_VERSION = 1;\n\n /** Creates underlying database table using DAOs. */\n public static void createAllTables(Database db, boolean ifNotExists) {\n CityEntityDao.createTable(db, ifNotExists);\n LoveCityEntityDao... | import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import com.baidu.location.LocationClient;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.weather.byhieg.easyweather.data.source.local.dao.DaoMaster;
import com.weather.byhieg.easyweather.data.source.local.dao.DaoSession;
import org.greenrobot.greendao.database.Database;
import cn.byhieg.betterload.network.NetService;
import cn.byhieg.monitor.TimeMonitorConfig;
import cn.byhieg.monitor.TimeMonitorManager; | package com.weather.byhieg.easyweather;
public class MyApplication extends Application{
private static MyApplication mcontext;
public static DaoMaster daoMaster;
public static DaoSession daoSession;
public static LocationClient mLocationClient;
private static final String cityUrl = "https://free-api.heweather.com/";
private static final String heweatherKey = "93d476b872724a9681a642dce28c6523";
public static final String shareFilename1 ="nightMode";
public static final String shareFilename2 ="nightMode2";
public static final String logFilename = "log";
public static final String notificationname = "notification";
public static final String widgetname = "widget";
public static final String cachename = "cache";
// public static RefWatcher mRefWatcher;
public static boolean isNewDay = false;
public static final boolean ENCRYPTED = false;
public static DaoSession getDaoSession() {
if (daoMaster == null) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getAppContext(), ENCRYPTED ?
"weather-db-encrypted" : "weather-db");
Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
daoMaster = new DaoMaster(db);
daoSession = new DaoMaster(db).newSession();
}
return daoMaster.newSession();
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base); | TimeMonitorManager.getInstance().resetTimeMonitor(TimeMonitorConfig.TIME_MONITOR_ID_APPLICATION_START); | 4 |
x-falcon/Virtual-Hosts | app/src/main/java/com/github/xfalcon/vhosts/AdvanceActivity.java | [
"public class FileUtils {\n\n\n public static boolean writeFile(OutputStream o, String content) throws Exception {\n o.write(content.getBytes());\n o.flush();\n o.close();\n return true;\n\n }\n\n}",
"public class HttpUtils {\n /**\n * Send a get request\n * @param url... | import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.github.xfalcon.vhosts.util.FileUtils;
import com.github.xfalcon.vhosts.util.HttpUtils;
import com.github.xfalcon.vhosts.util.LogUtils;
import com.github.xfalcon.vhosts.vservice.DnsChange;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.github.xfalcon.vhosts.VhostsActivity.IS_LOCAL;
import static com.github.xfalcon.vhosts.VhostsActivity.PREFS_NAME; | package com.github.xfalcon.vhosts;
public class AdvanceActivity extends AppCompatActivity {
private static final String TAG = AdvanceActivity.class.getSimpleName();
private Handler handler=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advance);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
final Button confirm_button = findViewById(R.id.confirm_button);
final RadioButton local_radio_button = findViewById(R.id.local_radio_button);
final RadioButton net_radio_button = findViewById(R.id.net_radio_button);
final EditText url_edit_text = findViewById(R.id.url_edit_text);
final RadioGroup ln_radio_group = findViewById(R.id.ln_radio_group);
final ImageButton down_button = findViewById(R.id.down_button);
final ProgressBar progressBar = findViewById(R.id.progressBar);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
url_edit_text.setText(settings.getString(VhostsActivity.HOSTS_URL,"https://raw.githubusercontent.com/x-falcon/tools/master/hosts"));
url_edit_text.setSelection(4); | boolean isLocal = settings.getBoolean(IS_LOCAL, true); | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.