repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
recoilme/malevich | malevich/src/main/java/org/freemp/malevich/Malevich.java | 18903 | package org.freemp.malevich;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by recoilme on 12/06/15.
*/
public class Malevich extends ImageWorker{
/** Callbacks for Malevich events. */
public interface ErrorDecodingListener {
/**
* Invoked when an image has failed to load. This is useful for reporting image failures to a
* remote analytics service, for example.
*/
void onImageDecodeError(Malevich malevich, String data, String error);
}
public interface ImageDecodedListener {
/**
* Invoked when an image has load. This is useful for transformayion image
*/
Bitmap onImageDecoded(String data, int reqWidth, int reqHeight, Bitmap bitmap);
}
private static final String TAG = "Malevich";
private final Context context;
private final boolean debug;
private final int maxSize;
private final ImageCache.ImageCacheParams cacheParams;
private final Bitmap loadingImage;
private final ErrorDecodingListener errorDecodingListener;
private Object data = null;
private int reqWidth = 0;
private int reqHeight = 0;
private ImageDecodedListener imageDecodedListener;
public static class Builder {
// required params
private final Context context;
// not requried params
private boolean debug = false;
private int maxSize;
private ImageCache.ImageCacheParams cacheParams;
private Bitmap loadingImage;
private ErrorDecodingListener errorDecodingListener;
public Builder (Context contextContainer) {
if (contextContainer == null) {
throw new IllegalArgumentException("Context must not be null.");
}
context = contextContainer.getApplicationContext();
// Default params init
// Fetch screen height and width, to use as our max size when loading images as this
// activity runs full screen
final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;
// For most apps you may use half of the longest width to resize our images. As the
// image scaling ensures the image is larger than this, we should be left with a
// resolution that is appropriate for both portrait and landscape. For best image quality
// don't divide by 2, but this will use more memory and require a larger memory
// cache. If you set this value more then 2048 you may have problems with renderings
this.maxSize = (height > width ? height : width);
// Set default folder for image cache
cacheParams = new ImageCache.ImageCacheParams(context,"images");
// Set memory cache to 40% of app memory
cacheParams.setMemCacheSizePercent(0.4f);
// Create transparent bitmap for default image loading image
int[] colors = new int[1];
colors[0] = Color.argb(0, 0, 0, 0);
loadingImage = Bitmap.createBitmap(colors, 1, 1, Bitmap.Config.ARGB_8888);
}
public Builder debug (boolean debug) {
this.debug = debug;
return this;
}
public Builder maxSize (int maxSize) {
this.maxSize = maxSize;
return this;
}
public Builder LoadingImage (Bitmap loadingImage) {
this.loadingImage = loadingImage;
return this;
}
public Builder LoadingImage (int resId) {
this.loadingImage = BitmapFactory.decodeResource(context.getResources(), resId);
return this;
}
public Builder CacheParams (ImageCache.ImageCacheParams cacheParams) {
this.cacheParams = cacheParams;
return this;
}
/** Specify a listener for interesting events. */
public Builder globalListener(ErrorDecodingListener errorDecodingListener) {
if (errorDecodingListener == null) {
throw new IllegalArgumentException("Listener must not be null.");
}
if (this.errorDecodingListener != null) {
throw new IllegalStateException("Listener already set.");
}
this.errorDecodingListener = errorDecodingListener;
return this;
}
public Malevich build() {
return new Malevich(this);
}
}
// Malevich init
private Malevich (Builder builder) {
super(builder.context, builder.debug);
context = builder.context;
debug = builder.debug;
maxSize = builder.maxSize;
cacheParams = builder.cacheParams;
loadingImage = builder.loadingImage;
errorDecodingListener = builder.errorDecodingListener;
// TODO reorginize it, loading image may change?
setLoadingImage(loadingImage);
addImageCache(cacheParams);
}
// This is starting method for every image loading
public Malevich load (Object data) {
this.data = data;
// clear params to default for every new load
this.reqWidth = maxSize;
this.reqHeight = maxSize;
this.imageDecodedListener = null;
return this;
}
public Malevich width (int reqWidth) {
this.reqWidth = reqWidth;
return this;
}
public Malevich height (int reqHeight) {
this.reqHeight = reqHeight;
return this;
}
public Malevich imageDecodedListener(ImageDecodedListener imageDecodedListener) {
this.imageDecodedListener = imageDecodedListener;
return this;
}
// This is final method for every image loading
public void into (ImageView imageView) {
loadImage(data, imageView, reqWidth, reqHeight, imageDecodedListener);
}
// Built in Malevich Utils
public enum Utils {;
public static boolean hasHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
public static boolean hasHoneycombMR1() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
}
public static boolean hasJellyBean() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
public static boolean hasKitKat() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
}
/**
* Workaround for bug pre-Froyo, see here for more info:
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*/
public static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
/**
* Decode and sample down a bitmap from resources to the requested width and height.
*
* @param res The resources object containing the image data
* @param resId The resource id of the image data
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight, ImageCache cache, boolean debug) {
if (debug) {
Log.d(TAG, "decodeSampledBitmapFromResource - " + resId);
}
// BEGIN_INCLUDE (read_bitmap_dimensions)
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// END_INCLUDE (read_bitmap_dimensions)
// If we're running on Honeycomb or newer, try to use inBitmap
if (hasHoneycomb()) {
addInBitmapOptions(options, cache);
}
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/**
* Decode and sample down a bitmap from a file to the requested width and height.
*
* @param filename The full path of the file to decode
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight, ImageCache cache) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// If we're running on Honeycomb or newer, try to use inBitmap
if (hasHoneycomb()) {
addInBitmapOptions(options, cache);
}
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
/**
* Decode and sample down a bitmap from a file input stream to the requested width and height.
*
* @param fileDescriptor The file descriptor to read from
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @param cache The ImageCache used to find candidate bitmaps for use with inBitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromDescriptor(
FileDescriptor fileDescriptor, int reqWidth, int reqHeight, ImageCache cache) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// If we're running on Honeycomb or newer, try to use inBitmap
if (Malevich.Utils.hasHoneycomb()) {
addInBitmapOptions(options, cache);
}
return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) {
//BEGIN_INCLUDE(add_bitmap_options)
// inBitmap only works with mutable bitmaps so force the decoder to
// return mutable bitmaps.
options.inMutable = true;
if (cache != null) {
// Try and find a bitmap to use for inBitmap
Bitmap inBitmap = cache.getBitmapFromReusableSet(options);
if (inBitmap != null) {
options.inBitmap = inBitmap;
}
}
//END_INCLUDE(add_bitmap_options)
}
/**
* Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object when decoding
* bitmaps using the decode* methods from {@link BitmapFactory}. This implementation calculates
* the closest inSampleSize that is a power of 2 and will result in the final decoded bitmap
* having a width and height equal to or larger than the requested width and height.
*
* @param options An options object with out* params already populated (run through a decode*
* method with inJustDecodeBounds==true
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// BEGIN_INCLUDE (calculate_sample_size)
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
// People are strange, so take 2/3 required size, for optimal memory usage, is it dirty?
reqHeight = (int) (reqHeight * 0.6f);
reqWidth = (int) (reqWidth * 0.6f);
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
// wtf, Romain?
// TODO test panorams
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
/*
long totalPixels = width * height / inSampleSize;
// Anything more than 2x the requested pixels we'll sample down further
final long totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels > totalReqPixelsCap) {
inSampleSize *= 2;
totalPixels /= 2;
}
*/
}
return inSampleSize;
// END_INCLUDE (calculate_sample_size)
}
// Some useful image utils
/**
* Creates a centered bitmap of the desired size.
* I am not sure in this code provided by google
*
* @param bitmap original bitmap source
* @param reqWidth targeted width
* @param reqHeight targeted height
*/
public static Bitmap extractThumbnail(Bitmap bitmap, int reqWidth, int reqHeight) {
return ThumbnailUtils.extractThumbnail(bitmap, reqWidth, reqHeight);
}
/**
* Creates a circle bitmap
*
* @param bitmap original bitmap source
*/
public static Bitmap getCircleBitmap(Bitmap bitmap) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final int color = Color.RED;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}
// Get squared bitmap and transform it to circle
public static Bitmap getSquaredCircleBitmap(Bitmap bitmap,int reqWidth) {
return getCircleBitmap(extractThumbnail(bitmap,reqWidth,reqWidth));
}
// Draw circle bitmap with text inside
public static Bitmap drawTextInCircle(int diametr, String txt, int color, float textSize) {
Bitmap b = Bitmap.createBitmap(diametr, diametr, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(diametr / 2, diametr / 2, diametr / 2, paint);
paint.setTextAlign(Paint.Align.CENTER);
paint.setColor(Color.parseColor("#FFFFFF"));
paint.setTextSize(textSize);
canvas.drawText("" + txt, diametr / 2, diametr / 2 + (paint.getTextSize() / 3), paint);
return b;
}
}
}
| mit |
rafwell/laravel-simplegrid | src/Query/SqlServerQueryBuilder.php | 1376 | <?php
namespace Rafwell\Simplegrid\Query;
use Rafwell\Simplegrid\Query\QueryBuilderContract;
use Rafwell\Simplegrid\Query\DefaultQueryBuilder;
use Illuminate\Database\Eloquent\Builder;
use DB;
use Exception;
use Carbon\Carbon;
use Log;
class SqlServerQueryBuilder extends DefaultQueryBuilder implements QueryBuilderContract
{
protected $fieldsForSelect = [];
protected $model;
protected $searchedValue;
public function __construct(Builder $model)
{
$this->model = $model;
}
public function getFieldsForSelect($hydrate = true, $addAlias = true)
{
$fieldsForSelect = [];
foreach ($this->fieldsForSelect as $k => $v) {
if (!is_array($v)) {
Log::debug($this->fieldsForSelect);
throw new Exception('An array was expected.');
}
if (strpos($v['field'], ' ') !== false) {
$v['field'] = '(' . $v['field'] . ')';
}
if ($v['field'] <> $v['alias']) {
$fieldsForSelect[$k] = $v['field'] . ' as ' . $v['alias'];
} else
$fieldsForSelect[$k] = $v['field'];
if ($hydrate)
$fieldsForSelect[$k] = DB::raw($fieldsForSelect[$k]);
}
return $fieldsForSelect;
}
public function getSimpleSearchConcatenatedFields()
{
$where = '';
foreach ($this->fieldsForSelect as $field) {
$where .= "+COALESCE(CAST({$field['field']} AS NVARCHAR(MAX)), '')";
}
if ($where)
$where = substr($where, 1);
return $where;
}
}
| mit |
Kylart/KawAnime | src/main/services/localLists/update.js | 1550 | import { eventsList } from 'vendor'
import { Logger, hashName } from '../../utils'
import { localFiles } from '../../externals'
const logger = new Logger('Local Lists (Update)')
const FILE_NAME = 'localLists.json'
const events = eventsList.localLists.update
function update (data) {
return localFiles.writeFile(data, FILE_NAME)
}
function handler (event, { type, data, isDelete = false }) {
try {
const storage = localFiles.getFile(FILE_NAME)
const currentList = storage[type]
const index = currentList.findIndex(({ name, key }) => name === data.name || (data.key && key === data.key))
const isUpdate = index !== -1
if (isDelete) {
if (index === -1) throw new Error('Cannot delete non-existing entry.')
currentList.splice(index, 1)
logger.info(`Deleted ${data.name} from ${type} list.`)
} else if (isUpdate) {
const current = currentList[index]
// Updating each value separately as there might be other keys
// that were not sent here.
Object.keys(data).forEach((key) => {
current[key] = data[key]
})
logger.info(`Updated ${type} list`)
} else {
// Setting up data key
data.key = hashName(data.name)
currentList.push(data)
}
update(storage)
logger.info('Successfully saved storage.')
event.sender.send(events.success, storage)
} catch (e) {
logger.error('Failed to update local information', e)
event.sender.send(events.error, e.message)
}
}
export default {
eventName: events.main,
handler
}
| mit |
yveskaufmann/MatrixCalculator | src/org/yvka/Beleg1/ui/commands/RetrieveMatrixCommand.java | 3170 | package org.yvka.Beleg1.ui.commands;
import org.yvka.Beleg1.matrix.Matrix;
import org.yvka.Beleg1.ui.Application;
import org.yvka.Beleg1.ui.ApplicationCommand;
import org.yvka.Beleg1.ui.IOTools;
import org.yvka.Beleg1.ui.MatrixTO;
/**
* <p>
* A Command which is used to request a single matrix from the user.<br>
* In other word the class asks for a matrix name and enables the caller to
* retrieve the corresponding matrix instance.<br>
* <br>
* The names of the matrix can be pass to {@link #execute(String...)}
* but the caller can call {@link #execute(String...)} without arguments.
* In this case the class request the name from the user.
* <br>
* If an entered matrix name does not exist, the class asks the
* user to create the matrix.
* </p>
* @author Yves Kaufmann
*
*/
public class RetrieveMatrixCommand extends ApplicationCommand {
private MatrixTO matrixResult = null;
private String prompt = null;
private boolean shouldAskForNewMatrix = true;
/**
* Create a RetrieveMatrixCommand and assigned to the
* Application 'application'.
*
* @param application the assigned Application.
* @param prompt the prompt message which should showed to the user
* when asked for a matrix name.
*/
public RetrieveMatrixCommand(Application application, String prompt) {
super(application);
this.prompt = prompt;
shouldAskForNewMatrix = true;
}
/**
* Determines if the matrix was successfully entered from the user.
*
* @return true, if the matrix was correctly entered.
*/
public boolean hasMatrix() {
return matrixResult != null;
}
/**
* Returns the correctly entered matrix.
*
* @return the entered matrixTO or null if the matrix was not correctly entered.
*/
public MatrixTO getMatrixTO() {
return matrixResult;
}
/**
* Disables the question for creating a matrix when a matrix name is entered
* which doesn't exists.
*/
public void disableAskForNewMatrix() {
this.shouldAskForNewMatrix = false;
}
@Override
public void execute(String... args) {
String name = null;
if(args.length > 0) {
name = args[0];
}
name = retrieveMatrixName(name);
Matrix matrix = retrieveMatrix(name);
if(matrix != null) {
matrixResult = new MatrixTO(matrix, name);
}
}
private Matrix retrieveMatrix(String name) {
boolean isTransposingRequested = name.endsWith("^t") || name.endsWith("^T");
if(isTransposingRequested) {
name = name.substring(0, name.length() - 2);
}
if(!getContext().hasMatrix(name)) {
System.out.printf("The specified matrix '%s' does not exists.\n", name);
if(!shouldAskForNewMatrix) return null;
String prompt = String.format("Do you want to create the matrix '%s' ? [yes,no] ", name);
String answer = IOTools.readString(prompt).trim();
if(!answer.startsWith("y")) {
return null;
}
getMenuCommand("create").execute(name);
}
Matrix m = getContext().getMatrix(name);
return isTransposingRequested ? m.transposition() : m;
}
private String retrieveMatrixName(String name) {
if(name == null) {
return IOTools.readString(prompt).trim();
} else {
return name;
}
}
}
| mit |
impiaaa/MyWorldGen | src/main/java/net/boatcake/MyWorldGen/Schematic.java | 18317 | package net.boatcake.MyWorldGen;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import org.apache.logging.log4j.Level;
import com.google.common.collect.Lists;
import net.boatcake.MyWorldGen.blocks.BlockAnchorLogic;
import net.boatcake.MyWorldGen.blocks.BlockAnchorMaterial;
import net.boatcake.MyWorldGen.blocks.BlockAnchorMaterial.AnchorType;
import net.boatcake.MyWorldGen.blocks.BlockAnchorMaterialLogic;
import net.boatcake.MyWorldGen.blocks.BlockPlacementLogic;
import net.boatcake.MyWorldGen.utils.DirectionUtils;
import net.boatcake.MyWorldGen.utils.WorldUtils;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityList;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.tileentity.TileEntityDispenser;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Rotation;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3i;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.common.DungeonHooks;
import net.minecraftforge.fml.common.registry.GameData;
public class Schematic {
public short width;
public short height;
public short length;
private int blocks[][][];
private int meta[][][];
public NBTTagList entities;
public NBTTagList tileEntities;
public Map<Integer, Block> idMap;
public Map<Integer, BlockAnchorLogic> matchingMap;
public Map<Integer, BlockPlacementLogic> placingMap;
// cache of the x,y,z locations of all anchor blocks
private ArrayList<BlockPos> anchorBlockLocations;
public SchematicInfo info;
// Designated constructor
public Schematic(short w, short h, short d, String n) {
width = w;
height = h;
length = d;
blocks = new int[w][h][d];
meta = new int[w][h][d];
entities = null;
tileEntities = null;
idMap = new HashMap<Integer, Block>();
matchingMap = new HashMap<Integer, BlockAnchorLogic>();
placingMap = new HashMap<Integer, BlockPlacementLogic>();
anchorBlockLocations = new ArrayList<BlockPos>();
info = new SchematicInfo();
info.name = n;
}
public Schematic() {
this((short) 0, (short) 0, (short) 0, null);
}
public Schematic(NBTTagCompound tag, String n) {
this();
readFromNBT(tag, n);
}
public void readFromNBT(NBTTagCompound tag, String n) {
info.name = n;
if (!tag.getString("Materials").equals("Alpha")) {
throw new RuntimeException("Non-Alpha schematics are not supported!");
}
width = tag.getShort("Width");
height = tag.getShort("Height");
length = tag.getShort("Length");
if (tag.hasKey("MWGIDMap")) {
NBTTagCompound mapTag = tag.getCompoundTag("MWGIDMap");
for (Object o : mapTag.getKeySet()) {
String blockName = (String) o;
int id = mapTag.getInteger(blockName);
Block block = Block.getBlockFromName(blockName);
if (block != null) {
idMap.put(id, block);
} else if (!BlockAnchorLogic.isAnchorBlock(blockName)
&& !BlockPlacementLogic.placementLogicExists(blockName)) {
MyWorldGen.log.log(Level.WARN, "Can't find a block named {}", blockName);
}
if (BlockAnchorLogic.isAnchorBlock(blockName)) {
matchingMap.put(id, BlockAnchorLogic.get(blockName));
}
if (BlockPlacementLogic.placementLogicExists(blockName)) {
placingMap.put(id, BlockPlacementLogic.get(blockName));
}
}
} else {
if (tag.hasKey("ignoreBlockId")) {
int id = tag.getInteger("ignoreBlockId");
if (MyWorldGen.ignoreBlock != null) {
idMap.put(id, MyWorldGen.ignoreBlock);
}
placingMap.put(id, BlockPlacementLogic.get(MyWorldGen.MODID + ":ignore"));
} else {
MyWorldGen.log.log(Level.WARN,
"Schematic file {} has no ignoreBlockId tag, defaulting to ID from config", info.name);
if (MyWorldGen.ignoreBlock != null) {
placingMap.put(GameData.getBlockRegistry().getId(MyWorldGen.ignoreBlock),
BlockPlacementLogic.get(MyWorldGen.MODID + ":ignore"));
}
placingMap.put(MyWorldGen.ignoreBlockId, BlockPlacementLogic.get(MyWorldGen.MODID + ":ignore"));
}
if (tag.hasKey("anchorBlockId")) {
int id = tag.getInteger("anchorBlockId");
if (MyWorldGen.materialAnchorBlock != null) {
idMap.put(id, MyWorldGen.materialAnchorBlock);
}
placingMap.put(id, BlockPlacementLogic.get(MyWorldGen.MODID + ":anchor"));
matchingMap.put(id, BlockAnchorLogic.get(MyWorldGen.MODID + ":anchor"));
} else {
MyWorldGen.log.log(Level.WARN,
"Schematic file {} has no anchorBlockId tag, defaulting to ID from config", info.name);
if (MyWorldGen.materialAnchorBlock != null) {
placingMap.put(GameData.getBlockRegistry().getId(MyWorldGen.materialAnchorBlock),
BlockPlacementLogic.get(MyWorldGen.MODID + ":anchor"));
matchingMap.put(GameData.getBlockRegistry().getId(MyWorldGen.materialAnchorBlock),
BlockAnchorLogic.get(MyWorldGen.MODID + ":anchor"));
}
placingMap.put(MyWorldGen.materialAnchorBlockId, BlockPlacementLogic.get(MyWorldGen.MODID + ":anchor"));
matchingMap.put(MyWorldGen.materialAnchorBlockId, BlockAnchorLogic.get(MyWorldGen.MODID + ":anchor"));
}
if (MyWorldGen.inventoryAnchorBlock != null) {
placingMap.put(GameData.getBlockRegistry().getId(MyWorldGen.inventoryAnchorBlock),
BlockPlacementLogic.get(MyWorldGen.MODID + ":anchorInventory"));
matchingMap.put(GameData.getBlockRegistry().getId(MyWorldGen.inventoryAnchorBlock),
BlockAnchorLogic.get(MyWorldGen.MODID + ":anchorInventory"));
}
placingMap.put(MyWorldGen.inventoryAnchorBlockId,
BlockPlacementLogic.get(MyWorldGen.MODID + ":anchorInventory"));
matchingMap.put(MyWorldGen.inventoryAnchorBlockId,
BlockAnchorLogic.get(MyWorldGen.MODID + ":anchorInventory"));
}
anchorBlockLocations.clear();
blocks = new int[width][height][length];
meta = new int[width][height][length];
byte blockBytes[] = tag.getByteArray("Blocks");
byte metaBytes[] = tag.getByteArray("Data");
byte blockUpperBits[];
if (tag.hasKey("AddBlocks")) {
blockUpperBits = tag.getByteArray("AddBlocks");
} else {
blockUpperBits = null;
}
// YZX order
for (int y = 0, blockIdx = 0; y < height; y++) {
for (int z = 0; z < length; z++) {
for (int x = 0; x < width; x++, blockIdx++) {
blocks[x][y][z] = (blockBytes[blockIdx]) & 0xFF;
meta[x][y][z] = (metaBytes[blockIdx]) & 0x0F;
if (blockUpperBits != null) {
blocks[x][y][z] |= (blockUpperBits[blockIdx >> 1] << ((blockIdx % 2 == 0) ? 4 : 8)) & 0xF00;
}
if (matchingMap.containsKey(blocks[x][y][z])) {
anchorBlockLocations.add(new BlockPos(x, y, z));
}
}
}
}
entities = (NBTTagList) tag.getTag("Entities");
tileEntities = (NBTTagList) tag.getTag("TileEntities");
if (anchorBlockLocations.isEmpty() && info.name != null) {
MyWorldGen.log.log(Level.WARN, "No anchors found in schematic {}", info.name);
info.fuzzyMatching = true;
}
info.readFromNBT(tag);
}
public Schematic(World world, BlockPos pos1, BlockPos pos2) {
this((short) (Math.abs(pos2.getX() - pos1.getX()) + 1), (short) (Math.abs(pos2.getY() - pos1.getY()) + 1),
(short) (Math.abs(pos2.getZ() - pos1.getZ()) + 1), null);
BlockPos min = new BlockPos(Math.min(pos1.getX(), pos2.getX()), Math.min(pos1.getY(), pos2.getY()),
Math.min(pos1.getZ(), pos2.getZ()));
Vec3i minVec = new Vec3i(min.getX(), min.getY(), min.getZ());
BlockPos max = new BlockPos(Math.max(pos1.getX(), pos2.getX()), Math.max(pos1.getY(), pos2.getY()),
Math.max(pos1.getZ(), pos2.getZ()));
for (Object o : BlockPos.getAllInBox(min, max)) {
BlockPos pos = (BlockPos) o;
IBlockState blockState = world.getBlockState(pos);
Block block = blockState.getBlock();
int id = Block.getIdFromBlock(block);
BlockPos offset = pos.subtract(minVec);
blocks[offset.getX()][offset.getY()][offset.getZ()] = id;
idMap.put(id, block);
meta[offset.getX()][offset.getY()][offset.getZ()] = block.getMetaFromState(blockState);
}
if (!world.isRemote) {
this.entities = WorldUtils.getEntities(world, min, max);
this.tileEntities = WorldUtils.getTileEntities(world, min, max);
}
}
public boolean fitsIntoWorldAt(World world, BlockPos at, Rotation rotation) {
// used for world generation to determine if all anchor blocks in the
// schematic match up with the world
Vec3d offset = new Vec3d(at.getX(), at.getY(), at.getZ());
if (anchorBlockLocations.isEmpty()) {
Vec3d middle = DirectionUtils.rotateCoords(new Vec3d(width / 2, 0, length / 2), offset, rotation);
BlockPos mid = new BlockPos(middle);
BlockPos midDown = mid.down();
IBlockState otherBlockBelow = world.getBlockState(mid);
IBlockState otherBlockAbove = world.getBlockState(midDown);
BiomeGenBase biome = world.getBiomeGenForCoords(mid);
return BlockAnchorMaterialLogic.matchesStatic(BlockAnchorMaterial.AnchorType.GROUND, otherBlockBelow, biome)
&& BlockAnchorMaterialLogic.matchesStatic(BlockAnchorMaterial.AnchorType.AIR, otherBlockAbove,
biome);
} else {
for (int i = 0; i < anchorBlockLocations.size(); i++) {
BlockPos origCoords = anchorBlockLocations.get(i);
Vec3d rotatedCoords = DirectionUtils.rotateCoords(origCoords, offset, rotation);
BlockPos rotatedPos = new BlockPos(rotatedCoords);
int blockId = blocks[origCoords.getX()][origCoords.getY()][origCoords.getZ()];
if (!(matchingMap.get(blockId)).matches(meta[origCoords.getX()][origCoords.getY()][origCoords.getZ()],
getTileEntityAt(world.getMinecraftServer(), origCoords), world, rotatedPos)) {
return false;
}
}
return true;
}
}
public NBTTagCompound getNBT() {
// http://www.minecraftwiki.net/wiki/Schematic_file_format
NBTTagCompound base = new NBTTagCompound();
base.setShort("Width", width);
base.setShort("Height", height);
base.setShort("Length", length);
base.setString("Materials", "Alpha");
int size = width * height * length;
byte blockBytes[] = new byte[size];
byte metaBytes[] = new byte[size];
if (size % 2 != 0) {
size++;
}
byte blockUpperBits[] = new byte[size / 2];
// YZX order
for (int y = 0, blockIdx = 0; y < height; y++) {
for (int z = 0; z < length; z++) {
for (int x = 0; x < width; x++, blockIdx++) {
blockBytes[blockIdx] = (byte) (blocks[x][y][z] & 0xFF);
metaBytes[blockIdx] = (byte) (meta[x][y][z] & 0x0F);
blockUpperBits[blockIdx >> 1] |= (byte) ((blocks[x][y][z] & 0xF00) >> ((blockIdx % 2 == 0) ? 4
: 8));
}
}
}
base.setByteArray("Blocks", blockBytes);
base.setByteArray("Data", metaBytes);
base.setByteArray("AddBlocks", blockUpperBits);
if (entities != null) {
base.setTag("Entities", entities);
}
if (tileEntities != null) {
base.setTag("TileEntities", tileEntities);
}
NBTTagCompound idMapTag = new NBTTagCompound();
for (Entry<Integer, Block> entry : idMap.entrySet()) {
idMapTag.setInteger(Block.blockRegistry.getNameForObject(entry.getValue()).toString(), entry.getKey());
}
base.setTag("MWGIDMap", idMapTag);
info.writeToNBT(base);
return base;
}
public TileEntity getTileEntityAt(MinecraftServer server, BlockPos pos) {
for (int i = 0; i < tileEntities.tagCount(); i++) {
NBTTagCompound tileEntityTag = tileEntities.getCompoundTagAt(i);
if (tileEntityTag.getInteger("x") == pos.getX() && tileEntityTag.getInteger("y") == pos.getY()
&& tileEntityTag.getInteger("z") == pos.getZ()) {
TileEntity e = TileEntity.createTileEntity(server, tileEntityTag);
return e;
}
}
return null;
}
private static final List<WeightedRandomChestContent> jungleDispenserContents = Lists.newArrayList(
new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.arrow, 0, 2, 7, 30) });
public void placeInWorld(World world, BlockPos at, Rotation rot, boolean generateChests, boolean generateSpawners,
boolean followPlacementRules, Random rand) {
float yawOffset = DirectionUtils.yawOffsetForRotation(rot);
Vec3d offset = new Vec3d(at.getX(), at.getY(), at.getZ());
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < length; z++) {
BlockPos pos = new BlockPos(x, y, z);
Vec3d rotatedCoords = DirectionUtils.rotateCoords(pos, offset, rot);
BlockPos rotatedPos = new BlockPos(rotatedCoords);
if (placingMap.containsKey(blocks[x][y][z]) && followPlacementRules) {
placingMap.get(blocks[x][y][z]).affectWorld(meta[x][y][z],
getTileEntityAt(world.getMinecraftServer(), pos), world, rotatedPos,
info.terrainSmoothing);
} else if (idMap.containsKey(blocks[x][y][z])) {
IBlockState blockState = idMap.get(blocks[x][y][z]).getStateFromMeta(meta[x][y][z])
.withRotation(rot);
world.setBlockState(rotatedPos, blockState, 0x2);
} else {
IBlockState blockState = Block.getBlockById(blocks[x][y][z]).getStateFromMeta(meta[x][y][z])
.withRotation(rot);
world.setBlockState(rotatedPos, blockState, 0x2);
}
}
}
}
// late update
for (int x = -1; x < width + 1; x++) {
for (int y = -1; y < height + 1; y++) {
for (int z = -1; z < length + 1; z++) {
BlockPos pos = new BlockPos(x, y, z);
Vec3d rotatedCoords = DirectionUtils.rotateCoords(pos, offset, rot);
BlockPos rotatedPos = new BlockPos(rotatedCoords);
world.notifyBlockOfStateChange(rotatedPos, world.getBlockState(rotatedPos).getBlock());
}
}
}
if (entities != null) {
for (int i = 0; i < entities.tagCount(); i++) {
NBTTagCompound entityTag = entities.getCompoundTagAt(i);
Entity e = EntityList.createEntityFromNBT(entityTag, world);
if (e == null) {
MyWorldGen.log.log(Level.WARN, "Not loading entity ID {}", entityTag.getString("id"));
} else {
Vec3d newCoords = DirectionUtils.rotateCoords(new Vec3d(e.posX, e.posY, e.posZ), offset, rot);
e.setPositionAndRotation(newCoords.xCoord, newCoords.yCoord, newCoords.zCoord, e.rotationPitch,
e.rotationYaw + yawOffset);
world.spawnEntityInWorld(e);
}
}
}
if (tileEntities != null) {
for (int i = 0; i < tileEntities.tagCount(); i++) {
NBTTagCompound tileEntityTag = tileEntities.getCompoundTagAt(i);
TileEntity e = TileEntity.createTileEntity(world.getMinecraftServer(), tileEntityTag);
if (e == null) {
MyWorldGen.log.log(Level.WARN, "Not loading tile entity ID {}", tileEntityTag.getString("id"));
} else {
BlockPos newPos = new BlockPos(DirectionUtils.rotateCoords(e.getPos(), offset, rot));
e.setPos(newPos);
world.addTileEntity(e);
}
}
}
ResourceLocation chestLootTable = new ResourceLocation(info.chestLootTable);
// Check for chests *after* we place the ones from the schematic,
// because the schematic may not have defined the tile entities
// properly.
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int z = 0; z < length; z++) {
BlockPos rotatedPos = new BlockPos(DirectionUtils.rotateCoords(new Vec3d(x, y, z), offset, rot));
Block block = world.getBlockState(rotatedPos).getBlock();
TileEntity e = world.getTileEntity(rotatedPos);
if (generateChests && !info.chestLootTable.isEmpty()) {
if (e instanceof TileEntityChest) {
((TileEntityChest) e).setLoot(chestLootTable, rand.nextLong());
} else if (e instanceof TileEntityDispenser) {
WeightedRandomChestContent.generateDispenserContents(rand, jungleDispenserContents,
(TileEntityDispenser) e, 2);
}
}
if (info.generateSpawners && generateSpawners && block == Blocks.mob_spawner
&& e instanceof TileEntityMobSpawner) {
((TileEntityMobSpawner) e).getSpawnerBaseLogic()
.setEntityName(DungeonHooks.getRandomDungeonMob(rand));
}
}
}
}
}
public BlockPos getFuzzyMatchingLocation(Chunk chunk, Rotation rotation, Random rand) {
if (anchorBlockLocations.isEmpty()) {
// Now, this is a tough situation. Structures without anchors
// should probably be able to fit anywhere on the ground, and
// fuzzy/quick matching is a great way to make that happen.
// Unfortunately, that means the generation rate is way too high,
// and we can't just modify the base generation rate. For now, just
// add in an additional chance to fail.
if (rand.nextInt(64) <= 62) { // 1/64 chance to place
return null;
}
BlockPos middleBottomOfSchematic = new BlockPos(width / 2, 0, height / 2);
BlockPos worldAnchorPos = BlockAnchorMaterialLogic.getQuickMatchingBlockInChunkStatic(AnchorType.GROUND,
chunk, rand);
if (worldAnchorPos != null) {
Vec3d worldSchematicPos = DirectionUtils.rotateCoords(
new BlockPos(0, 0, 0).subtract(middleBottomOfSchematic), new Vec3d(worldAnchorPos), rotation);
return new BlockPos(worldSchematicPos);
} else {
return null;
}
} else {
ArrayList<BlockPos> shuffledAnchors = (ArrayList<BlockPos>) anchorBlockLocations.clone();
Collections.shuffle(shuffledAnchors, rand);
for (BlockPos anchorPos : shuffledAnchors) {
BlockAnchorLogic matching = matchingMap
.get(blocks[anchorPos.getX()][anchorPos.getY()][anchorPos.getZ()]);
int anchorMeta = meta[anchorPos.getX()][anchorPos.getY()][anchorPos.getZ()];
TileEntity anchorEntity = getTileEntityAt(chunk.getWorld().getMinecraftServer(), anchorPos);
BlockPos worldAnchorPos = matching.getQuickMatchingBlockInChunk(anchorMeta, anchorEntity, chunk, rand);
if (worldAnchorPos != null) {
Vec3d worldSchematicPos = DirectionUtils.rotateCoords(new BlockPos(0, 0, 0).subtract(anchorPos),
new Vec3d(worldAnchorPos), rotation);
return new BlockPos(worldSchematicPos);
}
}
return null;
}
}
}
| mit |
VajraFramework/PipelineTools | FbxExporter/Source/Exporter/Parsers/ReconstructSkeletalAnimations/ReconstructSkeletalAnimations.cpp | 3756 | #include "Exporter/Common/Common.h"
#include "Exporter/Definitions/Face.h"
#include "Exporter/Definitions/Material.h"
#include "Exporter/Definitions/Mesh.h"
#include "Exporter/Definitions/Model.h"
#include "Exporter/Definitions/Polylist.h"
#include "Exporter/Definitions/Scene.h"
#include "Exporter/Definitions/Vertex.h"
#include "Exporter/Parsers/ParseAnimations/RigidAnimationData.h"
#include "Exporter/Parsers/ParseBones/Definitions.h"
#include "Exporter/Parsers/ReconstructSkeletalAnimations/ReconstructSkeletalAnimations.h"
#include "Exporter/Parsers/ReconstructSkeletalAnimations/ReplaySkeletalAnimation.h"
#include "Exporter/Utilities/Utilities.h"
#include <algorithm>
#include <fstream>
#include <vector>
void insertUniqueNumberIntoVector(std::vector<float>& out_vectorOfNumbers, float newUniqueNumber) {
for (int i = 0; i < out_vectorOfNumbers.size(); ++i) {
if (areFloatsApproximatelyEqual(out_vectorOfNumbers[i], newUniqueNumber)) {
// Number already exists:
return;
}
}
out_vectorOfNumbers.push_back(newUniqueNumber);
}
void getListOfKeyframeTimesForBone_recursive(Armature* armature, Bone* trootBone, Scene* scene, std::vector<float>& out_listOfKeyframeTimes) {
Model* boneModel = scene->GetModelByModelName(trootBone->name);
ASSERT(boneModel != nullptr, "Bone model found");
// TODO [Implement] Support more than 1 set of rigid animations on each bone, maybe
ASSERT(boneModel->rigidAnimationDatas->size() <= 1, "Not more than 1 set of rigid animations per bone");
//
if (boneModel->rigidAnimationDatas->size() != 0) {
RigidAnimationData* rigidAnimationData = boneModel->rigidAnimationDatas->at(0);
int numKeyframes = rigidAnimationData->GetNumKeyframes();
for (int i = 0; i < numKeyframes; ++i) {
RigidAnimationKeyframe* keyframe = rigidAnimationData->GetKeyframeAtIndex(i);
insertUniqueNumberIntoVector(out_listOfKeyframeTimes, keyframe->time);
}
}
// Recurse over children bones:
for (auto it = trootBone->childrenNames.begin(); it != trootBone->childrenNames.end(); ++it) {
std::string childBoneName = *it;
Bone* childBone = armature->GetBoneByName(childBoneName);
if (childBone != nullptr) {
getListOfKeyframeTimesForBone_recursive(armature, childBone, scene, out_listOfKeyframeTimes);
}
}
}
std::vector<float> getListOfKeyframeTimesForArmature(Armature* armature, Scene* scene) {
std::vector<float> timesOfKeyframes;
Bone* rootBone = armature->GetBoneByName(armature->GetRootBoneName());
ASSERT(rootBone != nullptr, "Rootbone found");
getListOfKeyframeTimesForBone_recursive(armature, rootBone, scene, timesOfKeyframes);
// Sort thelist of times of keyframes:
std::sort(timesOfKeyframes.begin(), timesOfKeyframes.end());
return timesOfKeyframes;
}
void reconstructSkeletalAnimationForModel(Model* model, Scene* scene) {
ASSERT(model->mesh != nullptr && model->mesh->armature != nullptr, "Model has an armature");
Armature* armature = model->mesh->armature;
std::vector<float> timesOfKeyframes; // Sorted list of the times at which a keyframe occurs for at least 1 bone in the armature
{
timesOfKeyframes = getListOfKeyframeTimesForArmature(armature, scene);
printf("\nGot list of %d times of keyframes for armature %s:\n", timesOfKeyframes.size(), armature->name.c_str());
for (int i = 0; i < timesOfKeyframes.size(); ++i) {
printf("%f ", timesOfKeyframes[i]);
}
}
{
ReplaySkeletalAnimationIntoSkeletalAnimationData(armature, scene, timesOfKeyframes);
}
}
void ReconstructSkeletalAnimation(Scene* scene) {
for (auto it = scene->models->begin(); it != scene->models->end(); ++it) {
Model* model = *it;
if (model->mesh != nullptr && model->mesh->armature != nullptr) {
reconstructSkeletalAnimationForModel(model, scene);
}
}
return;
}
| mit |
PureWeen/ReactiveUI.XamlForms.Sample | ReactiveUI.Sample.NetStandard/ISampleRoutableViewModel.cs | 253 | using System;
using System.Collections.Generic;
using System.Text;
namespace ReactiveUI.XamlForms.Sample
{
public interface ISampleRoutableViewModel
{
string UrlPathSegment { get; }
ISampleScreen HostScreen { get; }
}
}
| mit |
ChuckLangford/RSSReader | RSSReader/App/main.js | 726 | require.config({
paths: { "text": "durandal/amd/text" }
});
define(function (require) {
var system = require('durandal/system'),
app = require('durandal/app'),
viewLocator = require('durandal/viewLocator'),
router = require('durandal/plugins/router')
logger = require('services/logger');
system.debug(true);
app.start().then(function () {
router.useConvention();
viewLocator.useConvention();
app.setRoot('viewmodels/shell', 'entrance');
//bad route handler, write to log and show toast error
router.handleInvalidRoute = function (route, params) {
logger.log('No route found', route, 'main', true);
};
});
}); | mit |
SimpleRegex/SRL-PHP | src/Exceptions/ImplementationException.php | 89 | <?php
namespace SRL\Exceptions;
class ImplementationException extends SRLException
{
}
| mit |
Muxi-Studio/AndroidHomework | yuyi/Spectop141210/app/src/main/java/com/example/root/spectop141210/test.java | 1093 | package com.example.root.spectop141210;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class test extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_test, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| mit |
ibutra/SpyDashServer | spydashserver/plugins.py | 2596 | from importlib import import_module
from .settings import plugins
class PluginConfig(object):
def __init__(self, name, root, label=None, models=None):
# Python path to the Plugin e.g. 'weather'
self.name = name
# The python path to the root class of this plugin relative to name
self.root = root
# The label must be unique and will be used as prefix for database tables and identifier
# If no label is set the python path wil be used
if label:
self.label = label
else:
self.label = name
# The module containing the model definitions e.g. "notes.models"
# If this is None no models are used by the module
self.models = models
@classmethod
def load(cls, name):
# TODO: We should handle the possible exceptions here instead of just passing them on
module = import_module(name)
return module.plugin_config
class PluginManager(object):
def __init__(self):
self.configs = []
def load_configs(self):
for name in plugins:
self.configs.append(PluginConfig.load(name))
def load_plugin_roots(self, server):
for plugin_config in self.configs:
module = import_module(plugin_config.name + '.' + plugin_config.root[:plugin_config.root.rfind(".")])
try:
root = getattr(module, plugin_config.root[plugin_config.root.rfind('.') + 1:])
except AttributeError:
continue
try: # Try to pass a reference to server
plugin_config.instance = root(server=server)
except TypeError:
plugin_config.instance = root()
def load_models(self):
for plugin_config in self.configs:
try:
import_module(plugin_config.models)
except AttributeError:
pass
def get_instances(self):
return [config.instance for config in self.configs]
def get_containing_pluginconfig(self, object):
object_name = object.__module__
for plugin_config in self.configs:
if object_name.startswith(plugin_config.name):
return plugin_config
def get_containing_pluginlabel(self, object):
return self.get_containing_pluginconfig(object).label
def get_plugin_for_label(self, label):
return next(config.instance for config in self.configs if config.label == label)
def get_labels(self):
return [config.label for config in self.configs]
pluginmanager = PluginManager() | mit |
johnspackman/qxcompiler | source/resource/qx/tool/cli/templates/skeleton/mobile/source/class/custom/page/Overview.tmpl.js | 811 | /* ************************************************************************
Copyright:
License:
Authors:
************************************************************************ */
/**
* TODO: needs documentation
*/
qx.Class.define("${namespace}.page.Overview",
{
extend : qx.ui.mobile.page.NavigationPage,
construct : function()
{
this.base(arguments);
this.setTitle("Overview");
this.setShowBackButton(true);
this.setBackButtonText("Back");
},
members :
{
// overridden
_initialize : function()
{
this.base(arguments);
this.getContent().add(new qx.ui.mobile.basic.Label("Your first app."));
},
// overridden
_back : function(triggeredByKeyEvent)
{
qx.core.Init.getApplication().getRouting().back();
}
}
});
| mit |
delanepj/designPatterns | DesignPatterns/src/com/designpatterns/singleton/SingleObject.java | 481 | package com.designpattern.singleton;
public class SingleObject {
// Instantiate the Singleton Object
private static SingleObject instance = new SingleObject();
// Make Constructor Private so it can't be instantiated.
private SingleObject(){}
// Make Instance retrivable.
public static SingleObject getInstance(){
return instance;
} // end getInstance
public void showMessage(){
System.out.println("Hello World!");
} // end showMessage
}
| mit |
EmilPopov/C-Sharp | Web Services and Cloud/Exam/Teleimot_Exam2015/Web/Teleimot.Web.Api/Models/RealEstates/CreateRealEstateRequestModel.cs | 783 | namespace Teleimot.Web.Api.Models.RealEstates
{
using Data.Models;
using Mapping;
using System;
using System.ComponentModel.DataAnnotations;
public class CreateRealEstateRequestModel : IMapFrom<RealEstate>
{
[Required]
public string Address { get; set; }
[Required]
[MinLength(5)]
[MaxLength(50)]
public string Title { get; set; }
[Required]
[MinLength(10)]
[MaxLength(1000)]
public string Description { get; set; }
public int SellingPrice { get; set; }
public int RentingPrice { get; set; }
public int Type { get; set; }
[Required]
public string Contact { get; set; }
public int ConstructionYear { get; set; }
}
} | mit |
aecrim/LoLRetriever | LoLRetriever.java | 4163 | package com.aecrim.lol.retriever;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class LoLRetriever {
public static final String APIKEY = "ebf4332b-03f4-49e5-a15c-c1d31882b530";
private String name;
public static void main(String[] args) {
if (args.length == 1) {
String name = args[0];
LoLRetriever apiComm = new LoLRetriever(name);
Summoner summoner = apiComm.getSummonerDetails();
System.out.println("Summoner details for: " + summoner.getName());
System.out.println("-------------------------------------------------------------------------------------------------");
PlayerStats playerStats = apiComm.getPlayerStats(summoner.getId());
List<PlayerStatsSummary> playerStatsSummary = playerStats.getPlayerStatSummaries();
for (PlayerStatsSummary stats : playerStatsSummary) {
Map<String, Integer> aggregatedStats = stats.getAggregatedStats();
System.out.println(stats.getPlayerStatSummaryType());
System.out.println("-------------------------------------------------------------------------------------------------");
System.out.println("Wins: " + stats.getWins());
System.out.println("Losses: " + stats.getLosses());
for (Map.Entry<String, Integer> entry : aggregatedStats.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("\n");
/*System.out.println("Champion list:");
System.out.println("-------------------------------------------------------------------------------------------------");
List<Champion> championList = apiComm.getChampionsList().getChampions();
for (Champion champion : championList) {
System.out.println("Id: " + champion.getId() + " / Name: " + champion.getName());
}*/
RankedStats rankedStats = apiComm.getRankedStats(summoner.getId());
System.out.println("Ranked stats:");
System.out.println("-------------------------------------------------------------------------------------------------");
for (ChampionStats championStats : rankedStats.getChampions()) {
System.out.println(championStats.getName() + ":");
for (Map.Entry<String, Integer> entry : championStats.getStats().entrySet()) {
System.out.println("* " + entry.getKey() + ": " + entry.getValue());
}
System.out.println(/**********************************************/);
}
}
} else {
System.out.println("Usage: Please provide a summoner name as an argument");
}
}
public LoLRetriever(String passedName) {
name = passedName;
}
public Summoner getSummonerDetails() {
Summoner summoner = new Summoner();
try {
URL url = new URL("https://prod.api.pvp.net/api/lol/euw/v1.2/summoner/by-name/" + name + "?api_key=" + APIKEY);
LoLDataRetrieval<Summoner> data = new LoLDataRetrieval<Summoner>(url, summoner);
summoner = data.retrieve();
} catch (Exception e) {
}
return summoner;
}
public PlayerStats getPlayerStats(long id) {
PlayerStats playerStats = new PlayerStats();
try {
URL url = new URL("http://prod.api.pvp.net/api/lol/euw/v1.2/stats/by-summoner/" + id + "/summary?season=SEASON3&api_key=" + APIKEY);
LoLDataRetrieval<PlayerStats> data = new LoLDataRetrieval<PlayerStats>(url, playerStats);
playerStats = data.retrieve();
} catch (Exception e) {
}
return playerStats;
}
public ChampionList getChampionsList() {
ChampionList championList = new ChampionList();
try {
URL url = new URL("http://prod.api.pvp.net/api/lol/euw/v1.1/champion?api_key=" + APIKEY);
LoLDataRetrieval<ChampionList> data = new LoLDataRetrieval<ChampionList>(url, championList);
championList = data.retrieve();
} catch (Exception e) {
}
return championList;
}
public RankedStats getRankedStats(long id) {
RankedStats stats = new RankedStats();
try {
URL url = new URL("http://prod.api.pvp.net/api/lol/euw/v1.2/stats/by-summoner/" + id + "/ranked?season=SEASON3&api_key=" + APIKEY);
LoLDataRetrieval<RankedStats> data = new LoLDataRetrieval<RankedStats>(url, stats);
stats = data.retrieve();
} catch (Exception e) {
}
return stats;
}
}
| mit |
trigunshin/trimp_calc | static/js/app.js | 9097 | 'use strict';
//////////////////
// app //
//////////////////
var clickerCalcs = angular.module('trimpCalcApp', []);
clickerCalcs.controller('TrimpCalcCtrl', function($scope) {
$scope.keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
$scope.keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
$scope.weapons = ['Dagger', 'Mace', 'Polearm', 'Battleaxe', 'Greatsword'];
$scope.armor = ['Boots', 'Helmet', 'Pants', 'Shoulderguards', 'Breastplate'];
$scope.block = ['Shield'];
$scope.population = ['Hut', 'House', 'Mansion', 'Hotel', 'Resort', 'Gateway', 'Wormhole'];
$scope.show_items = [['Shield', $scope.block], ['Weapons', $scope.weapons], ['Armor', $scope.armor]];
$scope.defaults = newGame();
$scope.base_buildings = $scope.defaults.buildings;
$scope.base_equipment = $scope.defaults.equipment;
$scope.base_prestige = $scope.defaults.global.prestige;
$scope.upgrade_names = $scope.defaults.upgrades;
$scope._get_best_item = function(accum, name) {
var datum = $scope.data.equipment[name];
if(datum.locked === 1 || datum.purchased === 0) return accum;
var cost_per_val = $scope.data.equipment[name].current_price / $scope.data.equipment[name].display_value;
if(cost_per_val < accum[1])
return [name, cost_per_val];
else return accum;
}
$scope._item_price = function(item) {
var resource = '';
if(item.name === 'Shield') resource = 'wood';
else resource = 'metal';
return $scope.getItemPrice(item, resource, true);
};
$scope._get_display_value = function(item) {
if(item.name === 'Shield') {
if(item.blockNow) return item.blockCalculated;
else return item.healthCalculated;
} else if (_.indexOf($scope.weapons, item.name) > -1) {
return item.attackCalculated;
} else return item.healthCalculated;
}
$scope._get_total_building_cost = function(name) {
var cur = $scope.data.buildings[name];
var costs = _.map(_.keys(cur.cost), function(resource_name) {
return parseFloat($scope.getItemPrice(cur, resource_name, false));
});
return _.sum(costs);
};
$scope._get_best_building = function(accum, name) {
var datum = $scope.data.buildings[name];
if(datum.locked === 1 || datum.purchased === 0) return accum;
var cost_per_val = $scope.data.buildings[name].current_price / $scope.data.buildings[name].increase.by;
if(cost_per_val < accum[1])
return [name, cost_per_val];
else return accum;
}
$scope._import_buildings = function() {
_.each($scope.population, function(name) {
var cur = $scope.data.buildings[name];
var base_data = $scope.base_buildings[name];
cur.cost = base_data.cost;
cur.current_price = $scope._get_total_building_cost(name);
});
var best_pop = _.reduce($scope.population, $scope._get_best_building, ['', Number.MAX_VALUE], this);
$scope.data.buildings[best_pop[0]].is_best = true;
};
$scope.import = function(save_data) {
$scope.data = JSON.parse(LZString.decompressFromBase64(save_data));
$scope.data.global.prestige = $scope.base_prestige;
_.each(_.keys($scope.base_equipment), function(equip_name) {
// set defaults; these are zeroed out in the save data
var equip_data = $scope.data.equipment[equip_name];
var base_data = $scope.base_equipment[equip_name];
equip_data.cost = base_data.cost;
// bring the prestiges up to par
if(equip_data.prestige > 1) {
for(var i=1,iLen=equip_data.prestige;i<iLen;i++) {
$scope.prestigeEquipment(equip_name, true, true);
}
}
// simple displays
equip_data.name = equip_name;
equip_data.current_price = $scope._item_price(equip_data);
equip_data.display_value = Math.max(0, $scope._get_display_value(equip_data));
// calculate prestige values
var prestige_value = $scope.getNextPrestigeValue(equip_data);
var prestige_cost = $scope.getNextPrestigeCost(equip_data);
equip_data.upgrade_efficiency = prestige_cost / prestige_value;
equip_data.prestige_surpass = Math.ceil(equip_data.display_value * equip_data.level / prestige_value);
// need to incrementally do this, inaccurate past L1 due to scaling cost
// equip_data.prestige_cost = prestige_cost * equip_data.prestige_surpass;
});
// calculate the best equipment in their classes
var best_wep = _.reduce($scope.weapons, $scope._get_best_item, ['', Number.MAX_VALUE], this);
$scope.data.equipment[best_wep[0]].is_best = true;
var best_armor = _.reduce($scope.armor, $scope._get_best_item, ['', Number.MAX_VALUE], this);
$scope.data.equipment[best_armor[0]].is_best = true;
$scope._import_buildings();
console.log($scope.data);
};
$scope.getItemPrice = function(toBuy, costItem, is_equipment) {
if(!toBuy) return 0;
var price = 0;
var compare = (is_equipment) ? "level" : "purchased";
var thisCost = toBuy.cost[costItem];
if (typeof thisCost[1] !== 'undefined'){
if (thisCost.lastCheckCount != $scope.data.global.buyAmt || thisCost.lastCheckOwned != toBuy[compare]){
for (var x = 0; x < $scope.data.global.buyAmt; x++){
price += $scope.resolvePow(thisCost, toBuy, x);
}
thisCost.lastCheckCount = $scope.data.global.buyAmt;
thisCost.lastCheckAmount = price;
thisCost.lastCheckOwned = toBuy[compare];
}
else price = thisCost.lastCheckAmount;
}
else if (typeof thisCost === 'function') {
price = thisCost();
}
else {
price = thisCost * $scope.data.global.buyAmt;
}
return price;
}
$scope.resolvePow = function(cost, whatObj, addOwned) {
if (!addOwned) addOwned = 0;
var compare;
if (typeof whatObj.done !== 'undefined') compare = 'done';
if (typeof whatObj.level !== 'undefined') compare = 'level';
if (typeof whatObj.owned !== 'undefined') compare = 'owned';
if (typeof whatObj.purchased !== 'undefined') compare = 'purchased';
return (Math.floor(cost[0] * Math.pow(cost[1], (whatObj[compare] + addOwned))));
}
$scope.prestigeEquipment = function(what, fromLoad, noInc) {
var equipment = $scope.data.equipment[what];
if (!fromLoad && !noInc) equipment.prestige++;
var resource = (what == "Shield") ? "wood" : "metal";
var cost = equipment.cost[resource];
var prestigeMod = 0;
if (equipment.prestige >= 4) prestigeMod = (((equipment.prestige - 3) * .85) + 2);
else prestigeMod = (equipment.prestige - 1);
cost[0] = Math.round(equipment.oc * Math.pow(1.069, ((prestigeMod) * $scope.data.global.prestige.cost) + 1));
cost.lastCheckAmount = null;
cost.lastCheckCount = null;
cost.lastCheckOwned = null;
var stat;
if (equipment.blockNow) stat = "block";
else stat = (typeof equipment.health !== 'undefined') ? "health" : "attack";
if (!fromLoad) $scope.data.global[stat] -= (equipment[stat + "Calculated"] * equipment.level);
equipment[stat + "Calculated"] = Math.round(equipment[stat] * Math.pow(1.19, ((equipment.prestige - 1) * $scope.data.global.prestige[stat]) + 1));
//No need to touch level if it's newNum
if (fromLoad) return;
equipment.level = 0;
if (document.getElementById(what + "Numeral") !== null) document.getElementById(what + "Numeral").innerHTML = romanNumeral(equipment.prestige);
}
$scope.getNextPrestigeCost = function(equipment){
var prestigeMod;
var nextPrestigeCount = equipment.prestige + 1;
if (nextPrestigeCount >= 4) prestigeMod = (((nextPrestigeCount - 3) * .85) + 2);
else prestigeMod = (nextPrestigeCount - 1);
return Math.round(equipment.oc * Math.pow(1.069, ((prestigeMod) * $scope.data.global.prestige.cost) + 1));
}
$scope.getNextPrestigeValue = function(equipment){
var stat;
if (equipment.blockNow) stat = "block";
else stat = (typeof equipment.health !== 'undefined') ? "health" : "attack";
var toReturn = Math.round(equipment[stat] * Math.pow(1.19, ((equipment.prestige) * $scope.data.global.prestige[stat]) + 1));
return toReturn;
}
// initialize tooltip values
$(function () {
$('[data-toggle="tooltip"]').tooltip()
});
// initialize underscore/lodash templates
// _.templateSettings.variable = "rc";
});
| mit |
GollyGood/klaviyo-api-php | src/Exception/NotFoundApiException.php | 169 | <?php
namespace Klaviyo\Exception;
/**
* Simple Exception for Klaviyo API.
*/
class NotFoundApiException extends \Exception implements KlaviyoExceptionInterface
{
}
| mit |
alsemyonov/vk | spec/vk/api/users/crop_photo_spec.rb | 477 | # frozen_string_literal: true
require 'spec_helper'
require 'vk/api/users/crop_photo'
RSpec.describe Vk::API::Users::CropPhoto do
subject(:model) { described_class }
it { is_expected.to be < Dry::Struct }
it { is_expected.to be < Vk::Schema::Object }
describe 'attributes' do
subject(:attributes) { model.instance_methods(false) }
it { is_expected.to include :photo }
it { is_expected.to include :crop }
it { is_expected.to include :rect }
end
end
| mit |
kapadiamush/Eve-s-Adventure | src/views/scenes/LoadMenuSceneA.java | 2547 | package views.scenes;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import views.MainApp;
import controllers.ButtonHandlers;
/**
*
*/
public final class LoadMenuSceneA extends Scene {
/**
*
*/
private static final class LoadMenuPaneA extends BorderPane {
/**
*
*/
private static LoadMenuPaneA instanceOfLoadMenuPaneA = null;
private Button LOAD_CAMPAIGN_BUTTON, NEW_CAMPAIGN_BUTTON, BACK_BUTTON;
/**
*
*/
private LoadMenuPaneA() {
this.getStylesheets().add("./loadmenu_style.css");
setupObjects();
this.setCenter(addVBox());
this.setBottom(addHBox());
LOAD_CAMPAIGN_BUTTON
.setOnAction(ButtonHandlers::LOAD_CAMPAIGN_ADVENTURE_BUTTON_HANDLER);
NEW_CAMPAIGN_BUTTON
.setOnAction(ButtonHandlers::NEW_CAMPAIGN_BUTTON_HANDLER);
BACK_BUTTON
.setOnAction(ButtonHandlers::BACK_HOMESCREEN_BUTTON_HANDLER);
}
private void setupObjects() {
LOAD_CAMPAIGN_BUTTON = new Button("LOAD CAMPAIGN");
NEW_CAMPAIGN_BUTTON = new Button("NEW CAMPAIGN");
BACK_BUTTON = new Button("BACK TO HOME SCREEN");
LOAD_CAMPAIGN_BUTTON.setPrefWidth(500);
NEW_CAMPAIGN_BUTTON.setPrefWidth(500);
BACK_BUTTON.setPrefWidth(300);
LOAD_CAMPAIGN_BUTTON.setId("load-button");
NEW_CAMPAIGN_BUTTON.setId("new-button");
BACK_BUTTON.setId("back-button");
}
private VBox addVBox() {
VBox vbox = new VBox();
vbox.setPrefWidth(500);
vbox.getChildren().add(LOAD_CAMPAIGN_BUTTON);
vbox.getChildren().add(NEW_CAMPAIGN_BUTTON);
vbox.setAlignment(Pos.CENTER);
return vbox;
}
private HBox addHBox() {
HBox hbox = new HBox();
hbox.setPrefWidth(300);
hbox.getChildren().add(BACK_BUTTON);
hbox.setAlignment(Pos.CENTER);
return hbox;
}
private static LoadMenuPaneA getInstance() {
return (instanceOfLoadMenuPaneA == null) ? instanceOfLoadMenuPaneA = new LoadMenuPaneA()
: instanceOfLoadMenuPaneA;
}
}
/**
*
*/
private static LoadMenuSceneA instanceOfLoadMenuAScene = null;
/**
*/
private LoadMenuSceneA(Parent arg0, double arg1, double arg2) {
super(arg0, arg1, arg2);
}
public static LoadMenuSceneA getInstance() {
return (LoadMenuSceneA.instanceOfLoadMenuAScene == null) ? instanceOfLoadMenuAScene = new LoadMenuSceneA(
LoadMenuPaneA.getInstance(), MainApp.WINDOW_WIDTH,
MainApp.WINDOW_HEIGHT) : instanceOfLoadMenuAScene;
}
}
| mit |
pcelvng/task | bus/io/consumer_test.go | 1005 | package io
import (
"bufio"
"context"
"io"
"testing"
"github.com/jbsmith7741/trial"
)
func TestNewConsumer(t *testing.T) {
fn := func(args ...interface{}) (interface{}, error) {
pth := args[0].(string)
_, err := NewConsumer(pth)
return nil, err
}
trial.New(fn, trial.Cases{
"missing path": {
Input: "",
ShouldErr: true,
},
"file does not exist": {
Input: "err.txt",
ShouldErr: true,
},
}).Test(t)
}
type mockReader struct {
lineCount int
line int
}
func (t *mockReader) Read(p []byte) (n int, err error) {
if t.line >= t.lineCount-1 {
return 0, io.EOF
}
t.line++
p[0] = '\n'
return 1, nil
}
func TestConsumer_Info(t *testing.T) {
c := &Consumer{
pth: "test",
scanner: bufio.NewScanner(&mockReader{lineCount: 10}),
}
c.ctx, c.cncl = context.WithCancel(context.Background())
for done := false; !done; _, done, _ = c.Msg() {
}
if c.Info().Received != 10 {
t.Errorf("Message received mismatch 10 != %d", c.Info().Received)
}
}
| mit |
uzura8/flockbird | fuel/app/modules/admin/classes/controller/news/file/api.php | 532 | <?php
namespace Admin;
class Controller_News_File_Api extends Controller_Api
{
protected $check_not_auth_action = array();
public function before()
{
parent::before();
}
/**
* Delete news file
*
* @access public
* @param int $id target id
* @return Response(json)
* @throws Exception in Controller_Base::controller_common_api
* @see Controller_Base::controller_common_api
*/
public function post_delete($id = null)
{
$this->api_delete_common('news_file', $id, null, t('site.file.view'));
}
}
| mit |
cleargif/digital-casefile-frontend | test/spec/controllers/dashboard.spec.js | 627 | 'use strict';
describe('Controller: DashboardCtrl', function () {
// load the controller's module
beforeEach(module('digitalCasefileApp'));
var DashboardCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
DashboardCtrl = $controller('DashboardCtrl', {
$scope: scope
});
}));
it('should have a newCasefile method', function() {
expect(scope.newCasefile).toBeDefined();
});
it('should attach tableParams to the scope', function () {
expect(scope.tableParams).toBeDefined();
});
});
| mit |
Rarioty/Parallax-Engine | src/PIL/FS/fs.cpp | 524 | #include <Parallax/FS/fs.hpp>
#include <Parallax/FS/URL.hpp>
#include <Parallax/Platform.hpp>
#if PARALLAX_PLATFORM_WINDOWS
#include <Parallax/FS/Windows/LocalFileSystem.hpp>
#else
#include <Parallax/FS/POSIX/LocalFileSystem.hpp>
#endif
#include <memory>
namespace Parallax::FS
{
File open(const std::string& path)
{
Url url(path);
std::string localPath = url.path();
static std::shared_ptr<LocalFileSystem> fs(new LocalFileSystem);
return fs->open(localPath);
}
}
| mit |
bukhmastov/CDOITMO | app/src/main/java/com/bukhmastov/cdoitmo/util/singleton/Transliterate.java | 3040 | package com.bukhmastov.cdoitmo.util.singleton;
public class Transliterate {
public static String cyr2lat(String s) {
StringBuilder sb = new StringBuilder(s.length() * 2);
for (char ch: s.toCharArray()) {
sb.append(cyr2lat(ch));
}
return sb.toString();
}
public static String cyr2lat(char ch) {
switch (ch) {
case 'А': return "A"; case 'а': return "a";
case 'Б': return "B"; case 'б': return "b";
case 'В': return "V"; case 'в': return "v";
case 'Г': return "G"; case 'г': return "g";
case 'Д': return "D"; case 'д': return "d";
case 'Е': return "E"; case 'е': return "e";
case 'Ё': return "E"; case 'ё': return "e";
case 'Ж': return "ZH"; case 'ж': return "zh";
case 'З': return "Z"; case 'з': return "z";
case 'И': return "I"; case 'и': return "i";
case 'Й': return "J"; case 'й': return "j";
case 'К': return "K"; case 'к': return "k";
case 'Л': return "L"; case 'л': return "l";
case 'М': return "M"; case 'м': return "m";
case 'Н': return "N"; case 'н': return "n";
case 'О': return "O"; case 'о': return "o";
case 'П': return "P"; case 'п': return "p";
case 'Р': return "R"; case 'р': return "r";
case 'С': return "S"; case 'с': return "s";
case 'Т': return "T"; case 'т': return "t";
case 'У': return "U"; case 'у': return "u";
case 'Ф': return "F"; case 'ф': return "f";
case 'Х': return "KH"; case 'х': return "kh";
case 'Ц': return "C"; case 'ц': return "c";
case 'Ч': return "CH"; case 'ч': return "ch";
case 'Ш': return "SH"; case 'ш': return "sh";
case 'Щ': return "JSH"; case 'щ': return "jsh";
case 'Ъ': return "''"; case 'ъ': return "''";
case 'Ы': return "Y"; case 'ы': return "y";
case 'Ь': return "'"; case 'ь': return "'";
case 'Э': return "E"; case 'э': return "e";
case 'Ю': return "JU"; case 'ю': return "ju";
case 'Я': return "JA"; case 'я': return "ja";
default: return String.valueOf(ch);
}
}
public static String letter2lat(String letter) {
if (StringUtils.isBlank(letter)) {
return letter;
}
char ch = letter.charAt(0);
switch (ch) {
case 'А': return "A"; case 'а': return "a";
case 'Е': return "E"; case 'е': return "e";
case 'К': return "K"; case 'к': return "k";
case 'М': return "M"; case 'м': return "m";
case 'О': return "O"; case 'о': return "o";
case 'Т': return "T"; case 'т': return "t";
default: return String.valueOf(ch);
}
}
}
| mit |
victronenergy/dbus_modbustcp | pdu.cpp | 2361 | #include "pdu.h"
#define QS_LOG_DISABLE
#include "QsLog.h"
const QMap <int,QString> PDU::initFunctionMap()
{
QMap <int,QString> functionMap;
functionMap[1] = "Read Coils";
functionMap[2] = "Read Discrete Inputs";
functionMap[3] = "Read Holding Registers";
functionMap[4] = "Read Input Registers";
functionMap[5] = "Write Single Coil";
functionMap[6] = "Write Single Register";
functionMap[7] = "Read Exception Status";
functionMap[8] = "Diagnostics";
functionMap[11] = "Get Comm Event Counter";
functionMap[12] = "Get Comm Event Log";
functionMap[15] = "Write Multiple Coils";
functionMap[16] = "Write Multiple registers";
functionMap[17] = "Report Slave ID";
functionMap[20] = "Read File Record";
functionMap[21] = "Write File Record";
functionMap[22] = "Mask Write Register";
functionMap[23] = "Read/Write Multiple registers";
functionMap[24] = "Read FIFO Queue";
functionMap[43] = "Encapsulated Interface Transport";
return functionMap;
}
const QMap <int,QString> PDU::functionMap = initFunctionMap();
const QMap <int,QString> PDU::initExceptionMap()
{
QMap <int,QString> exceptionMap;
exceptionMap[0] = "No Exeption";
exceptionMap[1] = "Illegal Function";
exceptionMap[2] = "Illegal Data Address";
exceptionMap[3] = "Illegal Data Value";
exceptionMap[4] = "Slave Device Failure";
exceptionMap[5] = "Acknowledge";
exceptionMap[6] = "Slave Device Busy";
exceptionMap[7] = "Memory Parity Error";
exceptionMap[10] = "Gateway Path Unavailable";
exceptionMap[11] = "Gateway Target Device Failed To Respond";
return exceptionMap;
}
const QMap <int,QString> PDU::exceptionMap = initExceptionMap();
PDU::PDU():
mFunctionCode(0),
mExeptionCode(NoExeption)
{
}
PDU::PDU(const QByteArray & pduRequest):
// First 6 byte are MBAP Header so starting with 7
mFunctionCode(static_cast<quint8>(pduRequest[7])),
mExeptionCode(NoExeption),
mData(pduRequest.mid(8))
{
}
void PDU::setData(const QByteArray & data)
{
mData = data;
}
void PDU::setExceptionCode(ExceptionCode code)
{
mFunctionCode |= 0x80;
mExeptionCode = code;
}
QString PDU::pduToString() const
{
QString string;
if (mFunctionCode >= 0x80)
string += "\tException Code: " + exceptionMap[mExeptionCode] + "\n";
else
string += "\tFunction Code: " + functionMap[mFunctionCode] + "\n";
string += "\tData: " + mData.toHex().toUpper() + "\n";
return string;
}
| mit |
balckdp/forum | Forum/src/com/forum/web/config/SecurityConfig.java | 2160 | package com.forum.web.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/static/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/login", "/logout", "/successfullogout", "/failedlogout").permitAll()
.antMatchers("/newaccount", "/createaccount").permitAll()
.antMatchers("/fetchrss", "/dofetch").access("hasRole('ADMIN')")
.and().formLogin().loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutUrl("/logout")
.and().authorizeRequests().anyRequest().denyAll();
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
} | mit |
311labs/SRL | radmin/python/timeout_xmlrpclib.py | 935 | # @author Ian Starnes
# @date March 19, 2008
#
# This code was taken from an article by: Volodymyr Orlenko
import xmlrpclib
import httplib
loads = xmlrpclib.loads
class TimeoutTransport(xmlrpclib.Transport):
def make_connection(self, host):
conn = TimeoutHTTP(host)
conn.set_timeout(self.timeout)
return conn
def Server(url, *args, **kwargs):
t = TimeoutTransport()
t.timeout = kwargs.get('timeout', 120)
if 'timeout' in kwargs:
del kwargs['timeout']
kwargs['transport'] = t
server = xmlrpclib.Server(url, *args, **kwargs)
return server
class TimeoutHTTPConnection(httplib.HTTPConnection):
def connect(self):
httplib.HTTPConnection.connect(self)
self.sock.settimeout(self.timeout)
class TimeoutHTTP(httplib.HTTP):
_connection_class = TimeoutHTTPConnection
def set_timeout(self, timeout):
self._conn.timeout = timeout
| mit |
tparisi/Vizi | engine/src/scene/sceneVisual.js | 457 | /**
* @fileoverview A visual containing a model in Collada format
* @author Tony Parisi
*/
goog.provide('Vizi.SceneVisual');
goog.require('Vizi.Visual');
Vizi.SceneVisual = function(param)
{
param = param || {};
Vizi.Visual.call(this, param);
this.object = param.scene;
}
goog.inherits(Vizi.SceneVisual, Vizi.Visual);
Vizi.SceneVisual.prototype.realize = function()
{
Vizi.Visual.prototype.realize.call(this);
this.addToScene();
}
| mit |
mysmarthouse/mysmarthouse-web | server/api/sensor/sensor.model.js | 392 | 'use strict';
var mongoose = require('mongoose-q')();
var Schema = mongoose.Schema;
var SensorSchema = new Schema({
name: String,
type: {
type: String,
enum: ['value', 'state', 'electricity'],
default: 'value'
},
boardId: String,
lastValue: Number,
connected: Boolean,
lastUpdated: Date,
pin: Number
});
module.exports = mongoose.model('Sensor', SensorSchema);
| mit |
mwhelan/WebApi2Testing | src/TestableWebApi.Api/Handlers/Credentials.cs | 175 | namespace TestableWebApi.Api.Handlers
{
public class Credentials
{
public string Username { get; set; }
public string Password { get; set; }
}
} | mit |
BTDF/BTDF | src/btdf-esb-resolver/Tools/CommonAssemblyInfo.cs | 1171 | // Deployment Framework for BizTalk ESB Resolver
// Copyright (C) 2008 Thomas F. Abraham
// See LICENSE.txt for licensing information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyCompany("Abraham")]
[assembly: AssemblyProduct("Deployment Framework for BizTalk ESB Resolver")]
[assembly: AssemblyCopyright("Copyright (C) 2008 Thomas F. Abraham")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
xhochy/delicious-feeds | spec/delicious-feeds_spec.rb | 208 | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "DeliciousFeeds" do
it "fails" do
fail "hey buddy, you should probably rename this file and start specing for real"
end
end
| mit |
leader22/simple-pokedex-v2 | _scraping/fetch/63.js | 7969 | module.exports = {
"key": "abra",
"moves": [
{
"learn_type": "tutor",
"name": "foul-play"
},
{
"learn_type": "tutor",
"name": "magic-room"
},
{
"learn_type": "tutor",
"name": "wonder-room"
},
{
"learn_type": "machine",
"name": "ally-switch"
},
{
"learn_type": "machine",
"name": "round"
},
{
"learn_type": "machine",
"name": "telekinesis"
},
{
"learn_type": "machine",
"name": "psyshock"
},
{
"learn_type": "egg move",
"name": "guard-split"
},
{
"learn_type": "tutor",
"name": "gravity"
},
{
"learn_type": "tutor",
"name": "magic-coat"
},
{
"learn_type": "tutor",
"name": "role-play"
},
{
"learn_type": "tutor",
"name": "zen-headbutt"
},
{
"learn_type": "tutor",
"name": "signal-beam"
},
{
"learn_type": "tutor",
"name": "trick"
},
{
"learn_type": "machine",
"name": "charge-beam"
},
{
"learn_type": "machine",
"name": "grass-knot"
},
{
"learn_type": "machine",
"name": "captivate"
},
{
"learn_type": "machine",
"name": "trick-room"
},
{
"learn_type": "machine",
"name": "energy-ball"
},
{
"learn_type": "machine",
"name": "drain-punch"
},
{
"learn_type": "egg move",
"name": "guard-swap"
},
{
"learn_type": "egg move",
"name": "power-trick"
},
{
"learn_type": "machine",
"name": "fling"
},
{
"learn_type": "machine",
"name": "embargo"
},
{
"learn_type": "machine",
"name": "natural-gift"
},
{
"learn_type": "machine",
"name": "recycle"
},
{
"learn_type": "machine",
"name": "shock-wave"
},
{
"learn_type": "machine",
"name": "calm-mind"
},
{
"learn_type": "machine",
"name": "secret-power"
},
{
"learn_type": "machine",
"name": "snatch"
},
{
"learn_type": "machine",
"name": "skill-swap"
},
{
"learn_type": "egg move",
"name": "knock-off"
},
{
"learn_type": "machine",
"name": "taunt"
},
{
"learn_type": "machine",
"name": "focus-punch"
},
{
"learn_type": "machine",
"name": "facade"
},
{
"learn_type": "machine",
"name": "torment"
},
{
"learn_type": "machine",
"name": "iron-tail"
},
{
"learn_type": "machine",
"name": "safeguard"
},
{
"learn_type": "machine",
"name": "shadow-ball"
},
{
"learn_type": "machine",
"name": "psych-up"
},
{
"learn_type": "machine",
"name": "sunny-day"
},
{
"learn_type": "machine",
"name": "rain-dance"
},
{
"learn_type": "machine",
"name": "hidden-power"
},
{
"learn_type": "egg move",
"name": "encore"
},
{
"learn_type": "machine",
"name": "dynamicpunch"
},
{
"learn_type": "machine",
"name": "frustration"
},
{
"learn_type": "machine",
"name": "return"
},
{
"learn_type": "machine",
"name": "sleep-talk"
},
{
"learn_type": "machine",
"name": "attract"
},
{
"learn_type": "machine",
"name": "swagger"
},
{
"learn_type": "machine",
"name": "endure"
},
{
"learn_type": "machine",
"name": "zap-cannon"
},
{
"learn_type": "machine",
"name": "protect"
},
{
"learn_type": "machine",
"name": "curse"
},
{
"learn_type": "machine",
"name": "snore"
},
{
"learn_type": "machine",
"name": "nightmare"
},
{
"learn_type": "machine",
"name": "thief"
},
{
"learn_type": "machine",
"name": "dream-eater"
},
{
"learn_type": "egg move",
"name": "light-screen"
},
{
"learn_type": "egg move",
"name": "barrier"
},
{
"learn_type": "machine",
"name": "headbutt"
},
{
"learn_type": "machine",
"name": "thunderpunch"
},
{
"learn_type": "machine",
"name": "ice-punch"
},
{
"learn_type": "machine",
"name": "fire-punch"
},
{
"learn_type": "machine",
"name": "substitute"
},
{
"learn_type": "machine",
"name": "tri-attack"
},
{
"learn_type": "machine",
"name": "rest"
},
{
"learn_type": "machine",
"name": "psywave"
},
{
"learn_type": "machine",
"name": "flash"
},
{
"learn_type": "machine",
"name": "skull-bash"
},
{
"learn_type": "machine",
"name": "metronome"
},
{
"learn_type": "machine",
"name": "bide"
},
{
"learn_type": "machine",
"name": "reflect"
},
{
"learn_type": "machine",
"name": "double-team"
},
{
"learn_type": "machine",
"name": "mimic"
},
{
"learn_type": "level up",
"level": 1,
"name": "teleport"
},
{
"learn_type": "machine",
"name": "rage"
},
{
"learn_type": "machine",
"name": "psychic"
},
{
"learn_type": "machine",
"name": "toxic"
},
{
"learn_type": "machine",
"name": "thunder-wave"
},
{
"learn_type": "machine",
"name": "seismic-toss"
},
{
"learn_type": "machine",
"name": "counter"
},
{
"learn_type": "machine",
"name": "submission"
},
{
"learn_type": "machine",
"name": "double-edge"
},
{
"learn_type": "machine",
"name": "take-down"
},
{
"learn_type": "machine",
"name": "body-slam"
},
{
"learn_type": "machine",
"name": "mega-kick"
},
{
"learn_type": "machine",
"name": "mega-punch"
}
]
}; | mit |
fyoudine/three.js | examples/jsm/loaders/VTKLoader.js | 27248 | import {
BufferAttribute,
BufferGeometry,
FileLoader,
Float32BufferAttribute,
Loader,
LoaderUtils
} from 'three';
import * as fflate from '../libs/fflate.module.js';
class VTKLoader extends Loader {
constructor( manager ) {
super( manager );
}
load( url, onLoad, onProgress, onError ) {
const scope = this;
const loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.setResponseType( 'arraybuffer' );
loader.setRequestHeader( scope.requestHeader );
loader.setWithCredentials( scope.withCredentials );
loader.load( url, function ( text ) {
try {
onLoad( scope.parse( text ) );
} catch ( e ) {
if ( onError ) {
onError( e );
} else {
console.error( e );
}
scope.manager.itemError( url );
}
}, onProgress, onError );
}
parse( data ) {
function parseASCII( data ) {
// connectivity of the triangles
const indices = [];
// triangles vertices
const positions = [];
// red, green, blue colors in the range 0 to 1
const colors = [];
// normal vector, one per vertex
const normals = [];
let result;
// pattern for detecting the end of a number sequence
const patWord = /^[^\d.\s-]+/;
// pattern for reading vertices, 3 floats or integers
const pat3Floats = /(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)/g;
// pattern for connectivity, an integer followed by any number of ints
// the first integer is the number of polygon nodes
const patConnectivity = /^(\d+)\s+([\s\d]*)/;
// indicates start of vertex data section
const patPOINTS = /^POINTS /;
// indicates start of polygon connectivity section
const patPOLYGONS = /^POLYGONS /;
// indicates start of triangle strips section
const patTRIANGLE_STRIPS = /^TRIANGLE_STRIPS /;
// POINT_DATA number_of_values
const patPOINT_DATA = /^POINT_DATA[ ]+(\d+)/;
// CELL_DATA number_of_polys
const patCELL_DATA = /^CELL_DATA[ ]+(\d+)/;
// Start of color section
const patCOLOR_SCALARS = /^COLOR_SCALARS[ ]+(\w+)[ ]+3/;
// NORMALS Normals float
const patNORMALS = /^NORMALS[ ]+(\w+)[ ]+(\w+)/;
let inPointsSection = false;
let inPolygonsSection = false;
let inTriangleStripSection = false;
let inPointDataSection = false;
let inCellDataSection = false;
let inColorSection = false;
let inNormalsSection = false;
const lines = data.split( '\n' );
for ( const i in lines ) {
const line = lines[ i ].trim();
if ( line.indexOf( 'DATASET' ) === 0 ) {
const dataset = line.split( ' ' )[ 1 ];
if ( dataset !== 'POLYDATA' ) throw new Error( 'Unsupported DATASET type: ' + dataset );
} else if ( inPointsSection ) {
// get the vertices
while ( ( result = pat3Floats.exec( line ) ) !== null ) {
if ( patWord.exec( line ) !== null ) break;
const x = parseFloat( result[ 1 ] );
const y = parseFloat( result[ 2 ] );
const z = parseFloat( result[ 3 ] );
positions.push( x, y, z );
}
} else if ( inPolygonsSection ) {
if ( ( result = patConnectivity.exec( line ) ) !== null ) {
// numVertices i0 i1 i2 ...
const numVertices = parseInt( result[ 1 ] );
const inds = result[ 2 ].split( /\s+/ );
if ( numVertices >= 3 ) {
const i0 = parseInt( inds[ 0 ] );
let k = 1;
// split the polygon in numVertices - 2 triangles
for ( let j = 0; j < numVertices - 2; ++ j ) {
const i1 = parseInt( inds[ k ] );
const i2 = parseInt( inds[ k + 1 ] );
indices.push( i0, i1, i2 );
k ++;
}
}
}
} else if ( inTriangleStripSection ) {
if ( ( result = patConnectivity.exec( line ) ) !== null ) {
// numVertices i0 i1 i2 ...
const numVertices = parseInt( result[ 1 ] );
const inds = result[ 2 ].split( /\s+/ );
if ( numVertices >= 3 ) {
// split the polygon in numVertices - 2 triangles
for ( let j = 0; j < numVertices - 2; j ++ ) {
if ( j % 2 === 1 ) {
const i0 = parseInt( inds[ j ] );
const i1 = parseInt( inds[ j + 2 ] );
const i2 = parseInt( inds[ j + 1 ] );
indices.push( i0, i1, i2 );
} else {
const i0 = parseInt( inds[ j ] );
const i1 = parseInt( inds[ j + 1 ] );
const i2 = parseInt( inds[ j + 2 ] );
indices.push( i0, i1, i2 );
}
}
}
}
} else if ( inPointDataSection || inCellDataSection ) {
if ( inColorSection ) {
// Get the colors
while ( ( result = pat3Floats.exec( line ) ) !== null ) {
if ( patWord.exec( line ) !== null ) break;
const r = parseFloat( result[ 1 ] );
const g = parseFloat( result[ 2 ] );
const b = parseFloat( result[ 3 ] );
colors.push( r, g, b );
}
} else if ( inNormalsSection ) {
// Get the normal vectors
while ( ( result = pat3Floats.exec( line ) ) !== null ) {
if ( patWord.exec( line ) !== null ) break;
const nx = parseFloat( result[ 1 ] );
const ny = parseFloat( result[ 2 ] );
const nz = parseFloat( result[ 3 ] );
normals.push( nx, ny, nz );
}
}
}
if ( patPOLYGONS.exec( line ) !== null ) {
inPolygonsSection = true;
inPointsSection = false;
inTriangleStripSection = false;
} else if ( patPOINTS.exec( line ) !== null ) {
inPolygonsSection = false;
inPointsSection = true;
inTriangleStripSection = false;
} else if ( patTRIANGLE_STRIPS.exec( line ) !== null ) {
inPolygonsSection = false;
inPointsSection = false;
inTriangleStripSection = true;
} else if ( patPOINT_DATA.exec( line ) !== null ) {
inPointDataSection = true;
inPointsSection = false;
inPolygonsSection = false;
inTriangleStripSection = false;
} else if ( patCELL_DATA.exec( line ) !== null ) {
inCellDataSection = true;
inPointsSection = false;
inPolygonsSection = false;
inTriangleStripSection = false;
} else if ( patCOLOR_SCALARS.exec( line ) !== null ) {
inColorSection = true;
inNormalsSection = false;
inPointsSection = false;
inPolygonsSection = false;
inTriangleStripSection = false;
} else if ( patNORMALS.exec( line ) !== null ) {
inNormalsSection = true;
inColorSection = false;
inPointsSection = false;
inPolygonsSection = false;
inTriangleStripSection = false;
}
}
let geometry = new BufferGeometry();
geometry.setIndex( indices );
geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
if ( normals.length === positions.length ) {
geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
}
if ( colors.length !== indices.length ) {
// stagger
if ( colors.length === positions.length ) {
geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
}
} else {
// cell
geometry = geometry.toNonIndexed();
const numTriangles = geometry.attributes.position.count / 3;
if ( colors.length === ( numTriangles * 3 ) ) {
const newColors = [];
for ( let i = 0; i < numTriangles; i ++ ) {
const r = colors[ 3 * i + 0 ];
const g = colors[ 3 * i + 1 ];
const b = colors[ 3 * i + 2 ];
newColors.push( r, g, b );
newColors.push( r, g, b );
newColors.push( r, g, b );
}
geometry.setAttribute( 'color', new Float32BufferAttribute( newColors, 3 ) );
}
}
return geometry;
}
function parseBinary( data ) {
const buffer = new Uint8Array( data );
const dataView = new DataView( data );
// Points and normals, by default, are empty
let points = [];
let normals = [];
let indices = [];
// Going to make a big array of strings
const vtk = [];
let index = 0;
function findString( buffer, start ) {
let index = start;
let c = buffer[ index ];
const s = [];
while ( c !== 10 ) {
s.push( String.fromCharCode( c ) );
index ++;
c = buffer[ index ];
}
return { start: start,
end: index,
next: index + 1,
parsedString: s.join( '' ) };
}
let state, line;
while ( true ) {
// Get a string
state = findString( buffer, index );
line = state.parsedString;
if ( line.indexOf( 'DATASET' ) === 0 ) {
const dataset = line.split( ' ' )[ 1 ];
if ( dataset !== 'POLYDATA' ) throw new Error( 'Unsupported DATASET type: ' + dataset );
} else if ( line.indexOf( 'POINTS' ) === 0 ) {
vtk.push( line );
// Add the points
const numberOfPoints = parseInt( line.split( ' ' )[ 1 ], 10 );
// Each point is 3 4-byte floats
const count = numberOfPoints * 4 * 3;
points = new Float32Array( numberOfPoints * 3 );
let pointIndex = state.next;
for ( let i = 0; i < numberOfPoints; i ++ ) {
points[ 3 * i ] = dataView.getFloat32( pointIndex, false );
points[ 3 * i + 1 ] = dataView.getFloat32( pointIndex + 4, false );
points[ 3 * i + 2 ] = dataView.getFloat32( pointIndex + 8, false );
pointIndex = pointIndex + 12;
}
// increment our next pointer
state.next = state.next + count + 1;
} else if ( line.indexOf( 'TRIANGLE_STRIPS' ) === 0 ) {
const numberOfStrips = parseInt( line.split( ' ' )[ 1 ], 10 );
const size = parseInt( line.split( ' ' )[ 2 ], 10 );
// 4 byte integers
const count = size * 4;
indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
let indicesIndex = 0;
let pointIndex = state.next;
for ( let i = 0; i < numberOfStrips; i ++ ) {
// For each strip, read the first value, then record that many more points
const indexCount = dataView.getInt32( pointIndex, false );
const strip = [];
pointIndex += 4;
for ( let s = 0; s < indexCount; s ++ ) {
strip.push( dataView.getInt32( pointIndex, false ) );
pointIndex += 4;
}
// retrieves the n-2 triangles from the triangle strip
for ( let j = 0; j < indexCount - 2; j ++ ) {
if ( j % 2 ) {
indices[ indicesIndex ++ ] = strip[ j ];
indices[ indicesIndex ++ ] = strip[ j + 2 ];
indices[ indicesIndex ++ ] = strip[ j + 1 ];
} else {
indices[ indicesIndex ++ ] = strip[ j ];
indices[ indicesIndex ++ ] = strip[ j + 1 ];
indices[ indicesIndex ++ ] = strip[ j + 2 ];
}
}
}
// increment our next pointer
state.next = state.next + count + 1;
} else if ( line.indexOf( 'POLYGONS' ) === 0 ) {
const numberOfStrips = parseInt( line.split( ' ' )[ 1 ], 10 );
const size = parseInt( line.split( ' ' )[ 2 ], 10 );
// 4 byte integers
const count = size * 4;
indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
let indicesIndex = 0;
let pointIndex = state.next;
for ( let i = 0; i < numberOfStrips; i ++ ) {
// For each strip, read the first value, then record that many more points
const indexCount = dataView.getInt32( pointIndex, false );
const strip = [];
pointIndex += 4;
for ( let s = 0; s < indexCount; s ++ ) {
strip.push( dataView.getInt32( pointIndex, false ) );
pointIndex += 4;
}
// divide the polygon in n-2 triangle
for ( let j = 1; j < indexCount - 1; j ++ ) {
indices[ indicesIndex ++ ] = strip[ 0 ];
indices[ indicesIndex ++ ] = strip[ j ];
indices[ indicesIndex ++ ] = strip[ j + 1 ];
}
}
// increment our next pointer
state.next = state.next + count + 1;
} else if ( line.indexOf( 'POINT_DATA' ) === 0 ) {
const numberOfPoints = parseInt( line.split( ' ' )[ 1 ], 10 );
// Grab the next line
state = findString( buffer, state.next );
// Now grab the binary data
const count = numberOfPoints * 4 * 3;
normals = new Float32Array( numberOfPoints * 3 );
let pointIndex = state.next;
for ( let i = 0; i < numberOfPoints; i ++ ) {
normals[ 3 * i ] = dataView.getFloat32( pointIndex, false );
normals[ 3 * i + 1 ] = dataView.getFloat32( pointIndex + 4, false );
normals[ 3 * i + 2 ] = dataView.getFloat32( pointIndex + 8, false );
pointIndex += 12;
}
// Increment past our data
state.next = state.next + count;
}
// Increment index
index = state.next;
if ( index >= buffer.byteLength ) {
break;
}
}
const geometry = new BufferGeometry();
geometry.setIndex( new BufferAttribute( indices, 1 ) );
geometry.setAttribute( 'position', new BufferAttribute( points, 3 ) );
if ( normals.length === points.length ) {
geometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
}
return geometry;
}
function Float32Concat( first, second ) {
const firstLength = first.length, result = new Float32Array( firstLength + second.length );
result.set( first );
result.set( second, firstLength );
return result;
}
function Int32Concat( first, second ) {
const firstLength = first.length, result = new Int32Array( firstLength + second.length );
result.set( first );
result.set( second, firstLength );
return result;
}
function parseXML( stringFile ) {
// Changes XML to JSON, based on https://davidwalsh.name/convert-xml-json
function xmlToJson( xml ) {
// Create the return object
let obj = {};
if ( xml.nodeType === 1 ) { // element
// do attributes
if ( xml.attributes ) {
if ( xml.attributes.length > 0 ) {
obj[ 'attributes' ] = {};
for ( let j = 0; j < xml.attributes.length; j ++ ) {
const attribute = xml.attributes.item( j );
obj[ 'attributes' ][ attribute.nodeName ] = attribute.nodeValue.trim();
}
}
}
} else if ( xml.nodeType === 3 ) { // text
obj = xml.nodeValue.trim();
}
// do children
if ( xml.hasChildNodes() ) {
for ( let i = 0; i < xml.childNodes.length; i ++ ) {
const item = xml.childNodes.item( i );
const nodeName = item.nodeName;
if ( typeof obj[ nodeName ] === 'undefined' ) {
const tmp = xmlToJson( item );
if ( tmp !== '' ) obj[ nodeName ] = tmp;
} else {
if ( typeof obj[ nodeName ].push === 'undefined' ) {
const old = obj[ nodeName ];
obj[ nodeName ] = [ old ];
}
const tmp = xmlToJson( item );
if ( tmp !== '' ) obj[ nodeName ].push( tmp );
}
}
}
return obj;
}
// Taken from Base64-js
function Base64toByteArray( b64 ) {
const Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
const revLookup = [];
const code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for ( let i = 0, l = code.length; i < l; ++ i ) {
revLookup[ code.charCodeAt( i ) ] = i;
}
revLookup[ '-'.charCodeAt( 0 ) ] = 62;
revLookup[ '_'.charCodeAt( 0 ) ] = 63;
const len = b64.length;
if ( len % 4 > 0 ) {
throw new Error( 'Invalid string. Length must be a multiple of 4' );
}
const placeHolders = b64[ len - 2 ] === '=' ? 2 : b64[ len - 1 ] === '=' ? 1 : 0;
const arr = new Arr( len * 3 / 4 - placeHolders );
const l = placeHolders > 0 ? len - 4 : len;
let L = 0;
let i, j;
for ( i = 0, j = 0; i < l; i += 4, j += 3 ) {
const tmp = ( revLookup[ b64.charCodeAt( i ) ] << 18 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] << 12 ) | ( revLookup[ b64.charCodeAt( i + 2 ) ] << 6 ) | revLookup[ b64.charCodeAt( i + 3 ) ];
arr[ L ++ ] = ( tmp & 0xFF0000 ) >> 16;
arr[ L ++ ] = ( tmp & 0xFF00 ) >> 8;
arr[ L ++ ] = tmp & 0xFF;
}
if ( placeHolders === 2 ) {
const tmp = ( revLookup[ b64.charCodeAt( i ) ] << 2 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] >> 4 );
arr[ L ++ ] = tmp & 0xFF;
} else if ( placeHolders === 1 ) {
const tmp = ( revLookup[ b64.charCodeAt( i ) ] << 10 ) | ( revLookup[ b64.charCodeAt( i + 1 ) ] << 4 ) | ( revLookup[ b64.charCodeAt( i + 2 ) ] >> 2 );
arr[ L ++ ] = ( tmp >> 8 ) & 0xFF;
arr[ L ++ ] = tmp & 0xFF;
}
return arr;
}
function parseDataArray( ele, compressed ) {
let numBytes = 0;
if ( json.attributes.header_type === 'UInt64' ) {
numBytes = 8;
} else if ( json.attributes.header_type === 'UInt32' ) {
numBytes = 4;
}
let txt, content;
// Check the format
if ( ele.attributes.format === 'binary' && compressed ) {
if ( ele.attributes.type === 'Float32' ) {
txt = new Float32Array( );
} else if ( ele.attributes.type === 'Int64' ) {
txt = new Int32Array( );
}
// VTP data with the header has the following structure:
// [#blocks][#u-size][#p-size][#c-size-1][#c-size-2]...[#c-size-#blocks][DATA]
//
// Each token is an integer value whose type is specified by "header_type" at the top of the file (UInt32 if no type specified). The token meanings are:
// [#blocks] = Number of blocks
// [#u-size] = Block size before compression
// [#p-size] = Size of last partial block (zero if it not needed)
// [#c-size-i] = Size in bytes of block i after compression
//
// The [DATA] portion stores contiguously every block appended together. The offset from the beginning of the data section to the beginning of a block is
// computed by summing the compressed block sizes from preceding blocks according to the header.
const rawData = ele[ '#text' ];
const byteData = Base64toByteArray( rawData );
let blocks = byteData[ 0 ];
for ( let i = 1; i < numBytes - 1; i ++ ) {
blocks = blocks | ( byteData[ i ] << ( i * numBytes ) );
}
let headerSize = ( blocks + 3 ) * numBytes;
const padding = ( ( headerSize % 3 ) > 0 ) ? 3 - ( headerSize % 3 ) : 0;
headerSize = headerSize + padding;
const dataOffsets = [];
let currentOffset = headerSize;
dataOffsets.push( currentOffset );
// Get the blocks sizes after the compression.
// There are three blocks before c-size-i, so we skip 3*numBytes
const cSizeStart = 3 * numBytes;
for ( let i = 0; i < blocks; i ++ ) {
let currentBlockSize = byteData[ i * numBytes + cSizeStart ];
for ( let j = 1; j < numBytes - 1; j ++ ) {
// Each data point consists of 8 bytes regardless of the header type
currentBlockSize = currentBlockSize | ( byteData[ i * numBytes + cSizeStart + j ] << ( j * 8 ) );
}
currentOffset = currentOffset + currentBlockSize;
dataOffsets.push( currentOffset );
}
for ( let i = 0; i < dataOffsets.length - 1; i ++ ) {
const data = fflate.unzlibSync( byteData.slice( dataOffsets[ i ], dataOffsets[ i + 1 ] ) ); // eslint-disable-line no-undef
content = data.buffer;
if ( ele.attributes.type === 'Float32' ) {
content = new Float32Array( content );
txt = Float32Concat( txt, content );
} else if ( ele.attributes.type === 'Int64' ) {
content = new Int32Array( content );
txt = Int32Concat( txt, content );
}
}
delete ele[ '#text' ];
if ( ele.attributes.type === 'Int64' ) {
if ( ele.attributes.format === 'binary' ) {
txt = txt.filter( function ( el, idx ) {
if ( idx % 2 !== 1 ) return true;
} );
}
}
} else {
if ( ele.attributes.format === 'binary' && ! compressed ) {
content = Base64toByteArray( ele[ '#text' ] );
// VTP data for the uncompressed case has the following structure:
// [#bytes][DATA]
// where "[#bytes]" is an integer value specifying the number of bytes in the block of data following it.
content = content.slice( numBytes ).buffer;
} else {
if ( ele[ '#text' ] ) {
content = ele[ '#text' ].split( /\s+/ ).filter( function ( el ) {
if ( el !== '' ) return el;
} );
} else {
content = new Int32Array( 0 ).buffer;
}
}
delete ele[ '#text' ];
// Get the content and optimize it
if ( ele.attributes.type === 'Float32' ) {
txt = new Float32Array( content );
} else if ( ele.attributes.type === 'Int32' ) {
txt = new Int32Array( content );
} else if ( ele.attributes.type === 'Int64' ) {
txt = new Int32Array( content );
if ( ele.attributes.format === 'binary' ) {
txt = txt.filter( function ( el, idx ) {
if ( idx % 2 !== 1 ) return true;
} );
}
}
} // endif ( ele.attributes.format === 'binary' && compressed )
return txt;
}
// Main part
// Get Dom
const dom = new DOMParser().parseFromString( stringFile, 'application/xml' );
// Get the doc
const doc = dom.documentElement;
// Convert to json
const json = xmlToJson( doc );
let points = [];
let normals = [];
let indices = [];
if ( json.PolyData ) {
const piece = json.PolyData.Piece;
const compressed = json.attributes.hasOwnProperty( 'compressor' );
// Can be optimized
// Loop through the sections
const sections = [ 'PointData', 'Points', 'Strips', 'Polys' ];// +['CellData', 'Verts', 'Lines'];
let sectionIndex = 0;
const numberOfSections = sections.length;
while ( sectionIndex < numberOfSections ) {
const section = piece[ sections[ sectionIndex ] ];
// If it has a DataArray in it
if ( section && section.DataArray ) {
// Depending on the number of DataArrays
let arr;
if ( Object.prototype.toString.call( section.DataArray ) === '[object Array]' ) {
arr = section.DataArray;
} else {
arr = [ section.DataArray ];
}
let dataArrayIndex = 0;
const numberOfDataArrays = arr.length;
while ( dataArrayIndex < numberOfDataArrays ) {
// Parse the DataArray
if ( ( '#text' in arr[ dataArrayIndex ] ) && ( arr[ dataArrayIndex ][ '#text' ].length > 0 ) ) {
arr[ dataArrayIndex ].text = parseDataArray( arr[ dataArrayIndex ], compressed );
}
dataArrayIndex ++;
}
switch ( sections[ sectionIndex ] ) {
// if iti is point data
case 'PointData':
{
const numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
const normalsName = section.attributes.Normals;
if ( numberOfPoints > 0 ) {
for ( let i = 0, len = arr.length; i < len; i ++ ) {
if ( normalsName === arr[ i ].attributes.Name ) {
const components = arr[ i ].attributes.NumberOfComponents;
normals = new Float32Array( numberOfPoints * components );
normals.set( arr[ i ].text, 0 );
}
}
}
}
break;
// if it is points
case 'Points':
{
const numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
if ( numberOfPoints > 0 ) {
const components = section.DataArray.attributes.NumberOfComponents;
points = new Float32Array( numberOfPoints * components );
points.set( section.DataArray.text, 0 );
}
}
break;
// if it is strips
case 'Strips':
{
const numberOfStrips = parseInt( piece.attributes.NumberOfStrips );
if ( numberOfStrips > 0 ) {
const connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
const offset = new Int32Array( section.DataArray[ 1 ].text.length );
connectivity.set( section.DataArray[ 0 ].text, 0 );
offset.set( section.DataArray[ 1 ].text, 0 );
const size = numberOfStrips + connectivity.length;
indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
let indicesIndex = 0;
for ( let i = 0, len = numberOfStrips; i < len; i ++ ) {
const strip = [];
for ( let s = 0, len1 = offset[ i ], len0 = 0; s < len1 - len0; s ++ ) {
strip.push( connectivity[ s ] );
if ( i > 0 ) len0 = offset[ i - 1 ];
}
for ( let j = 0, len1 = offset[ i ], len0 = 0; j < len1 - len0 - 2; j ++ ) {
if ( j % 2 ) {
indices[ indicesIndex ++ ] = strip[ j ];
indices[ indicesIndex ++ ] = strip[ j + 2 ];
indices[ indicesIndex ++ ] = strip[ j + 1 ];
} else {
indices[ indicesIndex ++ ] = strip[ j ];
indices[ indicesIndex ++ ] = strip[ j + 1 ];
indices[ indicesIndex ++ ] = strip[ j + 2 ];
}
if ( i > 0 ) len0 = offset[ i - 1 ];
}
}
}
}
break;
// if it is polys
case 'Polys':
{
const numberOfPolys = parseInt( piece.attributes.NumberOfPolys );
if ( numberOfPolys > 0 ) {
const connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
const offset = new Int32Array( section.DataArray[ 1 ].text.length );
connectivity.set( section.DataArray[ 0 ].text, 0 );
offset.set( section.DataArray[ 1 ].text, 0 );
const size = numberOfPolys + connectivity.length;
indices = new Uint32Array( 3 * size - 9 * numberOfPolys );
let indicesIndex = 0, connectivityIndex = 0;
let i = 0, len0 = 0;
const len = numberOfPolys;
while ( i < len ) {
const poly = [];
let s = 0;
const len1 = offset[ i ];
while ( s < len1 - len0 ) {
poly.push( connectivity[ connectivityIndex ++ ] );
s ++;
}
let j = 1;
while ( j < len1 - len0 - 1 ) {
indices[ indicesIndex ++ ] = poly[ 0 ];
indices[ indicesIndex ++ ] = poly[ j ];
indices[ indicesIndex ++ ] = poly[ j + 1 ];
j ++;
}
i ++;
len0 = offset[ i - 1 ];
}
}
}
break;
default:
break;
}
}
sectionIndex ++;
}
const geometry = new BufferGeometry();
geometry.setIndex( new BufferAttribute( indices, 1 ) );
geometry.setAttribute( 'position', new BufferAttribute( points, 3 ) );
if ( normals.length === points.length ) {
geometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
}
return geometry;
} else {
throw new Error( 'Unsupported DATASET type' );
}
}
// get the 5 first lines of the files to check if there is the key word binary
const meta = LoaderUtils.decodeText( new Uint8Array( data, 0, 250 ) ).split( '\n' );
if ( meta[ 0 ].indexOf( 'xml' ) !== - 1 ) {
return parseXML( LoaderUtils.decodeText( data ) );
} else if ( meta[ 2 ].includes( 'ASCII' ) ) {
return parseASCII( LoaderUtils.decodeText( data ) );
} else {
return parseBinary( data );
}
}
}
export { VTKLoader };
| mit |
m0ep/master-thesis | source/apis/moodlews_ksoap2/src/main/java/de/m0ep/moodlews/soap/AffectRecord.java | 1741 | /**
* AffectRecord.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
/**
* Modified for KSoap2 library by [email protected] using KSoap2BeanWriter
*/
package de.m0ep.moodlews.soap;
import net.patrickpollet.ksoap2.KSoap2Utils;
import net.patrickpollet.ksoap2.Soapeabilisable;
import org.ksoap2.serialization.SoapObject;
public class AffectRecord extends SoapObject implements Soapeabilisable{
private java.lang.String error;
private boolean status;
public AffectRecord(String nameSpace) {
super(nameSpace,"AffectRecord");
}
/**
* Get Custom Deserializer
*/
public Soapeabilisable fromSoapResponse (SoapObject response) {
AffectRecord ret = new AffectRecord(this.namespace);
ret.setError(KSoap2Utils.getString(response,"error") );
ret.setStatus(KSoap2Utils.getBoolean(response,"status") );
return ret;
}
/**
* Gets the error value for this AffectRecord.
*
* @return error
*/
public java.lang.String getError() {
return error;
}
/**
* Sets the error value for this AffectRecord.
*
* @param error
*/
public void setError(java.lang.String error) {
this.error = error;
this.addProperty("error",error);
}
/**
* Gets the status value for this AffectRecord.
*
* @return status
*/
public boolean isStatus() {
return status;
}
/**
* Sets the status value for this AffectRecord.
*
* @param status
*/
public void setStatus(boolean status) {
this.status = status;
this.addProperty("status",status);
}
}
| mit |
ltearno/hexa.tools | hexa.core/src/main/java/fr/lteconsulting/hexa/client/ui/miracle/printers/ListBoxExPrinter.java | 457 | package fr.lteconsulting.hexa.client.ui.miracle.printers;
import fr.lteconsulting.hexa.client.ui.miracle.TextPrinter;
import fr.lteconsulting.hexa.client.ui.widget.ListBoxEx;
public class ListBoxExPrinter implements TextPrinter
{
private final ListBoxEx lb;
private final int id;
public ListBoxExPrinter( ListBoxEx lb, int id )
{
this.lb = lb;
this.id = id;
}
@Override
public void setText( String text )
{
lb.setItemText( id, text );
}
} | mit |
HouseBreaker/High-Quality-Code | 02. Formatting Code/02. Reformat Your Own Code/Properties/AssemblyInfo.cs | 1428 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02. Reformat Your Own Code")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02. Reformat Your Own Code")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f03b46b1-77f5-40c1-8689-47de0d0c2598")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
SkillsFundingAgency/vacancy-register-api | src/Esfa.Vacancy.Application/Queries/SearchApprenticeshipVacancies/SearchApprenticeshipVacanciesRequest.cs | 948 | using System.Collections.Generic;
using MediatR;
namespace Esfa.Vacancy.Application.Queries.SearchApprenticeshipVacancies
{
public class SearchApprenticeshipVacanciesRequest : IRequest<SearchApprenticeshipVacanciesResponse>
{
public List<string> StandardLarsCodes { get; set; } = new List<string>();
public List<string> FrameworkLarsCodes { get; set; } = new List<string>();
public int PageSize { get; set; } = 100;
public int PageNumber { get; set; } = 1;
public int? PostedInLastNumberOfDays { get; set; }
public bool NationwideOnly { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public int? DistanceInMiles { get; set; }
public string SortBy { get; set; }
public bool IsGeoSearch => Latitude.HasValue || Longitude.HasValue || DistanceInMiles.HasValue;
public long? Ukprn { get; set; }
}
}
| mit |
bopes/phase-0 | week-4/add-it-up/my_solution.rb | 1901 | # Add it up!
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# I worked on this challenge [by myself, with: ].
# 0. total Pseudocode
# make sure all pseudocode is commented out!
# Input: an array of numbers
# Output: a single number (either integet or float)
# Steps to solve the problem.
=begin
1. take first number in array and add each subsequent number in the array one by one
2. Want to make sure that total numbers added are equal to array length
3. keep the sum of the numbers while adding additional numbers
4. out the final sum
=end
# 1. total initial solution
def total(array)
sum=0
i=0
while i<array.length
sum=sum+array[i]
i=i+1
end
sum
end
# 3. total refactored solution
#NO REFACTOR NEEDED
# 4. sentence_maker pseudocode
# make sure all pseudocode is commented out!
# Input: an array
# Output: A string with the first word capitalized and a period at the end.
# Steps to solve the problem.
=begin
1. join all array elements into a string, separated by a space
2. capitalize first letter of string
3. Add a period to end of string
4. output the string
=end
# 5. sentence_maker initial solution
def sentence_maker(array)
sentence = array.join(" ")
sentence.capitalize + "."
# sentence=""
# i=0
# while i<array.length
# sentence=sentence+array[i]
# if i!=array.length-1
# sentence=sentence+" "
# end
# i=i+1
# end
# sentence=sentence.capitalize+"."
end
# 6. sentence_maker refactored solution
def sentence_maker(array)
sentence = array.join(" ")
sentence.capitalize + "."
# sentence=""
# i=0
# while i<array.length
# sentence=sentence+array[i].to_s
# if i!=array.length-1
# sentence=sentence+" "
# end
# i=i+1
# end
# sentence=sentence.capitalize+"."
end
| mit |
tomer-ben-david-exercises/99-scala-solutions | src/main/scala/Solution06.scala | 623 | import org.scalatest.{FlatSpec, ShouldMatchers}
/**
* @author tomerb
* on 26/11/15
*/
//noinspection ScalaStyle
class Solution06 extends FlatSpec with ShouldMatchers {
"the solution" should "detect a palindrome" in {
val notPalindrome = List(1, 1, 2, 3, 5, 8)
val palindrome = List(1, 2, 3, 2, 1)
isPalindrome(notPalindrome) should not be true
isPalindrome(palindrome) should be (true)
}
private def isPalindrome(list: Seq[Int]): Boolean = list match {
case singleItem :: Nil => true
case head :: tail => (head == tail.last) && isPalindrome(tail.dropRight(1))
case _ => true
}
}
| mit |
ardean/jsGBC-core | src/MainInstructions.ts | 57094 | import bitInstructions from "./bitInstructions";
import SecondaryTickTable from "./secondaryTickTable";
export default [
// NOP
// 0x00:
() => { },
// LD BC, nn
// 0x01:
function () {
this.registerC = this.readMemory(this.programCounter);
this.registerB = this.readMemory(this.programCounter + 1 & 0xffff);
this.programCounter = this.programCounter + 2 & 0xffff;
},
// LD (BC), A
// 0x02:
function () {
this.writeMemory(this.registerB << 8 | this.registerC, this.registerA);
},
//INC BC
//#0x03:
function () {
var temp_var = (this.registerB << 8 | this.registerC) + 1;
this.registerB = temp_var >> 8 & 0xff;
this.registerC = temp_var & 0xff;
},
//INC B
//#0x04:
function () {
this.registerB = this.registerB + 1 & 0xff;
this.FZero = this.registerB === 0;
this.FHalfCarry = (this.registerB & 0xf) === 0;
this.FSubtract = false;
},
//DEC B
//#0x05:
function () {
this.registerB = this.registerB - 1 & 0xff;
this.FZero = this.registerB === 0;
this.FHalfCarry = (this.registerB & 0xf) === 0xf;
this.FSubtract = true;
},
//LD B, n
//#0x06:
function () {
this.registerB = this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
},
//RLCA
//#0x07:
function () {
this.FCarry = this.registerA > 0x7f;
this.registerA = this.registerA << 1 & 0xff | this.registerA >> 7;
this.FZero = this.FSubtract = this.FHalfCarry = false;
},
//LD (nn), SP
//#0x08:
function () {
var temp_var = this.readMemory(this.programCounter + 1 & 0xffff) << 8 | this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 2 & 0xffff;
this.writeMemory(temp_var, this.stackPointer & 0xff);
this.writeMemory(temp_var + 1 & 0xffff, this.stackPointer >> 8);
},
//ADD HL, BC
//#0x09:
function () {
var dirtySum = this.registersHL + (this.registerB << 8 | this.registerC);
this.FHalfCarry = (this.registersHL & 0xfff) > (dirtySum & 0xfff);
this.FCarry = dirtySum > 0xffff;
this.registersHL = dirtySum & 0xffff;
this.FSubtract = false;
},
//LD A, (BC)
//#0x0A:
function () {
this.registerA = this.readMemory(this.registerB << 8 | this.registerC);
},
//DEC BC
//#0x0B:
function () {
var temp_var = (this.registerB << 8 | this.registerC) - 1 & 0xffff;
this.registerB = temp_var >> 8;
this.registerC = temp_var & 0xff;
},
//INC C
//#0x0C:
function () {
this.registerC = this.registerC + 1 & 0xff;
this.FZero = this.registerC === 0;
this.FHalfCarry = (this.registerC & 0xf) === 0;
this.FSubtract = false;
},
//DEC C
//#0x0D:
function () {
this.registerC = this.registerC - 1 & 0xff;
this.FZero = this.registerC === 0;
this.FHalfCarry = (this.registerC & 0xf) === 0xf;
this.FSubtract = true;
},
//LD C, n
//#0x0E:
function () {
this.registerC = this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
},
//RRCA
//#0x0F:
function () {
this.registerA = this.registerA >> 1 | (this.registerA & 1) << 7;
this.FCarry = this.registerA > 0x7f;
this.FZero = this.FSubtract = this.FHalfCarry = false;
},
//STOP
//#0x10:
function () {
if (this.cartridge.useGbcMode) {
if ((this.memory[0xff4d] & 0x01) === 0x01) {
//Speed change requested.
if (this.memory[0xff4d] > 0x7f) {
// Go back to single speed mode.
console.log("Going into single clock speed mode.");
this.doubleSpeedShifter = 0;
this.memory[0xff4d] &= 0x7f; // Clear the double speed mode flag.
} else {
// Go to double speed mode.
console.log("Going into double clock speed mode.");
this.doubleSpeedShifter = 1;
this.memory[0xff4d] |= 0x80; // Set the double speed mode flag.
}
this.memory[0xff4d] &= 0xfe; // Reset the request bit.
} else {
this.stop();
}
} else {
this.stop();
}
},
//LD DE, nn
//#0x11:
function () {
this.registerE = this.readMemory(this.programCounter);
this.registerD = this.readMemory(this.programCounter + 1 & 0xffff);
this.programCounter = this.programCounter + 2 & 0xffff;
},
//LD (DE), A
//#0x12:
function () {
this.writeMemory(this.registerD << 8 | this.registerE, this.registerA);
},
//INC DE
//#0x13:
function () {
var temp_var = (this.registerD << 8 | this.registerE) + 1;
this.registerD = temp_var >> 8 & 0xff;
this.registerE = temp_var & 0xff;
},
//INC D
//#0x14:
function () {
this.registerD = this.registerD + 1 & 0xff;
this.FZero = this.registerD === 0;
this.FHalfCarry = (this.registerD & 0xf) === 0;
this.FSubtract = false;
},
//DEC D
//#0x15:
function () {
this.registerD = this.registerD - 1 & 0xff;
this.FZero = this.registerD === 0;
this.FHalfCarry = (this.registerD & 0xf) === 0xf;
this.FSubtract = true;
},
//LD D, n
//#0x16:
function () {
this.registerD = this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
},
//RLA
//#0x17:
function () {
var carry_flag = this.FCarry ? 1 : 0;
this.FCarry = this.registerA > 0x7f;
this.registerA = this.registerA << 1 & 0xff | carry_flag;
this.FZero = this.FSubtract = this.FHalfCarry = false;
},
//JR n
//#0x18:
function () {
this.programCounter = this.programCounter + (this.readMemory(this.programCounter) << 24 >> 24) + 1 & 0xffff;
},
//ADD HL, DE
//#0x19:
function () {
var dirtySum = this.registersHL + (this.registerD << 8 | this.registerE);
this.FHalfCarry = (this.registersHL & 0xfff) > (dirtySum & 0xfff);
this.FCarry = dirtySum > 0xffff;
this.registersHL = dirtySum & 0xffff;
this.FSubtract = false;
},
//LD A, (DE)
//#0x1A:
function () {
this.registerA = this.readMemory(this.registerD << 8 | this.registerE);
},
//DEC DE
//#0x1B:
function () {
var temp_var = (this.registerD << 8 | this.registerE) - 1 & 0xffff;
this.registerD = temp_var >> 8;
this.registerE = temp_var & 0xff;
},
//INC E
//#0x1C:
function () {
this.registerE = this.registerE + 1 & 0xff;
this.FZero = this.registerE === 0;
this.FHalfCarry = (this.registerE & 0xf) === 0;
this.FSubtract = false;
},
//DEC E
//#0x1D:
function () {
this.registerE = this.registerE - 1 & 0xff;
this.FZero = this.registerE === 0;
this.FHalfCarry = (this.registerE & 0xf) === 0xf;
this.FSubtract = true;
},
//LD E, n
//#0x1E:
function () {
this.registerE = this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
},
//RRA
//#0x1F:
function () {
var carry_flag = this.FCarry ? 0x80 : 0;
this.FCarry = (this.registerA & 1) === 1;
this.registerA = this.registerA >> 1 | carry_flag;
this.FZero = this.FSubtract = this.FHalfCarry = false;
},
//JR NZ, n
//#0x20:
function () {
if (!this.FZero) {
this.programCounter = this.programCounter + (this.readMemory(this.programCounter) << 24 >> 24) + 1 & 0xffff;
this.currentInstructionCycleCount += 4;
} else {
this.programCounter = this.programCounter + 1 & 0xffff;
}
},
//LD HL, nn
//#0x21:
function () {
this.registersHL = this.readMemory(this.programCounter + 1 & 0xffff) << 8 | this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 2 & 0xffff;
},
//LDI (HL), A
//#0x22:
function () {
this.writeMemory(
this.registersHL,
this.registerA
);
this.registersHL = this.registersHL + 1 & 0xffff;
},
//INC HL
//#0x23:
function () {
this.registersHL = this.registersHL + 1 & 0xffff;
},
//INC H
//#0x24:
function () {
var H = (this.registersHL >> 8) + 1 & 0xff;
this.FZero = H === 0;
this.FHalfCarry = (H & 0xf) === 0;
this.FSubtract = false;
this.registersHL = H << 8 | this.registersHL & 0xff;
},
//DEC H
//#0x25:
function () {
var H = (this.registersHL >> 8) - 1 & 0xff;
this.FZero = H === 0;
this.FHalfCarry = (H & 0xf) === 0xf;
this.FSubtract = true;
this.registersHL = H << 8 | this.registersHL & 0xff;
},
//LD H, n
//#0x26:
function () {
this.registersHL = this.readMemory(this.programCounter) << 8 | this.registersHL & 0xff;
this.programCounter = this.programCounter + 1 & 0xffff;
},
//DAA
//#0x27:
function () {
if (!this.FSubtract) {
if (this.FCarry || this.registerA > 0x99) {
this.registerA = this.registerA + 0x60 & 0xff;
this.FCarry = true;
}
if (this.FHalfCarry || (this.registerA & 0xf) > 0x9) {
this.registerA = this.registerA + 0x06 & 0xff;
this.FHalfCarry = false;
}
} else if (this.FCarry && this.FHalfCarry) {
this.registerA = this.registerA + 0x9a & 0xff;
this.FHalfCarry = false;
} else if (this.FCarry) {
this.registerA = this.registerA + 0xa0 & 0xff;
} else if (this.FHalfCarry) {
this.registerA = this.registerA + 0xfa & 0xff;
this.FHalfCarry = false;
}
this.FZero = this.registerA === 0;
},
//JR Z, n
//#0x28:
function () {
if (this.FZero) {
this.programCounter = this.programCounter + (this.readMemory(this.programCounter) << 24 >> 24) + 1 & 0xffff;
this.currentInstructionCycleCount += 4;
} else {
this.programCounter = this.programCounter + 1 & 0xffff;
}
},
//ADD HL, HL
//#0x29:
function () {
this.FHalfCarry = (this.registersHL & 0xfff) > 0x7ff;
this.FCarry = this.registersHL > 0x7fff;
this.registersHL = this.registersHL << 1 & 0xffff;
this.FSubtract = false;
},
//LDI A, (HL)
//#0x2A:
function () {
this.registerA = this.readMemory(this.registersHL);
this.registersHL = this.registersHL + 1 & 0xffff;
},
//DEC HL
//#0x2B:
function () {
this.registersHL = this.registersHL - 1 & 0xffff;
},
//INC L
//#0x2C:
function () {
var L = this.registersHL + 1 & 0xff;
this.FZero = L === 0;
this.FHalfCarry = (L & 0xf) === 0;
this.FSubtract = false;
this.registersHL = this.registersHL & 0xff00 | L;
},
//DEC L
//#0x2D:
function () {
var L = this.registersHL - 1 & 0xff;
this.FZero = L === 0;
this.FHalfCarry = (L & 0xf) === 0xf;
this.FSubtract = true;
this.registersHL = this.registersHL & 0xff00 | L;
},
//LD L, n
//#0x2E:
function () {
this.registersHL = this.registersHL & 0xff00 | this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
},
//CPL
//#0x2F:
function () {
this.registerA ^= 0xff;
this.FSubtract = this.FHalfCarry = true;
},
//JR NC, n
//#0x30:
function () {
if (!this.FCarry) {
this.programCounter = this.programCounter + (this.readMemory(this.programCounter) << 24 >> 24) + 1 & 0xffff;
this.currentInstructionCycleCount += 4;
} else {
this.programCounter = this.programCounter + 1 & 0xffff;
}
},
//LD SP, nn
//#0x31:
function () {
this.stackPointer = this.readMemory(this.programCounter + 1 & 0xffff) << 8 | this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 2 & 0xffff;
},
//LDD (HL), A
//#0x32:
function () {
this.writeMemory(
this.registersHL,
this.registerA
);
this.registersHL = this.registersHL - 1 & 0xffff;
},
//INC SP
//#0x33:
function () {
this.stackPointer = this.stackPointer + 1 & 0xffff;
},
//INC (HL)
//#0x34:
function () {
var temp_var = this.readMemory(this.registersHL) + 1 & 0xff;
this.FZero = temp_var === 0;
this.FHalfCarry = (temp_var & 0xf) === 0;
this.FSubtract = false;
this.writeMemory(
this.registersHL,
temp_var
);
},
//DEC (HL)
//#0x35:
function () {
var temp_var = this.readMemory(this.registersHL) - 1 & 0xff;
this.FZero = temp_var === 0;
this.FHalfCarry = (temp_var & 0xf) === 0xf;
this.FSubtract = true;
this.writeMemory(
this.registersHL,
temp_var
);
},
//LD (HL), n
//#0x36:
function () {
this.writeMemory(
this.registersHL,
this.readMemory(this.programCounter)
);
this.programCounter = this.programCounter + 1 & 0xffff;
},
//SCF
//#0x37:
function () {
this.FCarry = true;
this.FSubtract = this.FHalfCarry = false;
},
//JR C, n
//#0x38:
function () {
if (this.FCarry) {
this.programCounter = this.programCounter +
(this.readMemory(this.programCounter) << 24 >> 24) + 1 & 0xffff;
this.currentInstructionCycleCount += 4;
} else {
this.programCounter = this.programCounter + 1 & 0xffff;
}
},
//ADD HL, SP
//#0x39:
function () {
var dirtySum = this.registersHL + this.stackPointer;
this.FHalfCarry = (this.registersHL & 0xfff) > (dirtySum & 0xfff);
this.FCarry = dirtySum > 0xffff;
this.registersHL = dirtySum & 0xffff;
this.FSubtract = false;
},
//LDD A, (HL)
//#0x3A:
function () {
this.registerA = this.readMemory(this.registersHL);
this.registersHL = this.registersHL - 1 & 0xffff;
},
//DEC SP
//#0x3B:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
},
//INC A
//#0x3C:
function () {
this.registerA = this.registerA + 1 & 0xff;
this.FZero = this.registerA === 0;
this.FHalfCarry = (this.registerA & 0xf) === 0;
this.FSubtract = false;
},
//DEC A
//#0x3D:
function () {
this.registerA = this.registerA - 1 & 0xff;
this.FZero = this.registerA === 0;
this.FHalfCarry = (this.registerA & 0xf) === 0xf;
this.FSubtract = true;
},
//LD A, n
//#0x3E:
function () {
this.registerA = this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
},
//CCF
//#0x3F:
function () {
this.FCarry = !this.FCarry;
this.FSubtract = this.FHalfCarry = false;
},
//LD B, B
//#0x40:
function () {
//Do nothing...
},
//LD B, C
//#0x41:
function () {
this.registerB = this.registerC;
},
//LD B, D
//#0x42:
function () {
this.registerB = this.registerD;
},
//LD B, E
//#0x43:
function () {
this.registerB = this.registerE;
},
//LD B, H
//#0x44:
function () {
this.registerB = this.registersHL >> 8;
},
//LD B, L
//#0x45:
function () {
this.registerB = this.registersHL & 0xff;
},
//LD B, (HL)
//#0x46:
function () {
this.registerB = this.readMemory(this.registersHL);
},
//LD B, A
//#0x47:
function () {
this.registerB = this.registerA;
},
//LD C, B
//#0x48:
function () {
this.registerC = this.registerB;
},
//LD C, C
//#0x49:
function () {
//Do nothing...
},
//LD C, D
//#0x4A:
function () {
this.registerC = this.registerD;
},
//LD C, E
//#0x4B:
function () {
this.registerC = this.registerE;
},
//LD C, H
//#0x4C:
function () {
this.registerC = this.registersHL >> 8;
},
//LD C, L
//#0x4D:
function () {
this.registerC = this.registersHL & 0xff;
},
//LD C, (HL)
//#0x4E:
function () {
this.registerC = this.readMemory(this.registersHL);
},
//LD C, A
//#0x4F:
function () {
this.registerC = this.registerA;
},
//LD D, B
//#0x50:
function () {
this.registerD = this.registerB;
},
//LD D, C
//#0x51:
function () {
this.registerD = this.registerC;
},
//LD D, D
//#0x52:
function () {
//Do nothing...
},
//LD D, E
//#0x53:
function () {
this.registerD = this.registerE;
},
//LD D, H
//#0x54:
function () {
this.registerD = this.registersHL >> 8;
},
//LD D, L
//#0x55:
function () {
this.registerD = this.registersHL & 0xff;
},
//LD D, (HL)
//#0x56:
function () {
this.registerD = this.readMemory(this.registersHL);
},
//LD D, A
//#0x57:
function () {
this.registerD = this.registerA;
},
//LD E, B
//#0x58:
function () {
this.registerE = this.registerB;
},
//LD E, C
//#0x59:
function () {
this.registerE = this.registerC;
},
//LD E, D
//#0x5A:
function () {
this.registerE = this.registerD;
},
//LD E, E
//#0x5B:
function () {
//Do nothing...
},
//LD E, H
//#0x5C:
function () {
this.registerE = this.registersHL >> 8;
},
//LD E, L
//#0x5D:
function () {
this.registerE = this.registersHL & 0xff;
},
//LD E, (HL)
//#0x5E:
function () {
this.registerE = this.readMemory(this.registersHL);
},
//LD E, A
//#0x5F:
function () {
this.registerE = this.registerA;
},
//LD H, B
//#0x60:
function () {
this.registersHL = this.registerB << 8 | this.registersHL & 0xff;
},
//LD H, C
//#0x61:
function () {
this.registersHL = this.registerC << 8 | this.registersHL & 0xff;
},
//LD H, D
//#0x62:
function () {
this.registersHL = this.registerD << 8 | this.registersHL & 0xff;
},
//LD H, E
//#0x63:
function () {
this.registersHL = this.registerE << 8 | this.registersHL & 0xff;
},
//LD H, H
//#0x64:
function () {
//Do nothing...
},
//LD H, L
//#0x65:
function () {
this.registersHL = (this.registersHL & 0xff) * 0x101;
},
//LD H, (HL)
//#0x66:
function () {
this.registersHL = this.readMemory(this.registersHL) << 8 | this.registersHL & 0xff;
},
//LD H, A
//#0x67:
function () {
this.registersHL = this.registerA << 8 | this.registersHL & 0xff;
},
//LD L, B
//#0x68:
function () {
this.registersHL = this.registersHL & 0xff00 | this.registerB;
},
//LD L, C
//#0x69:
function () {
this.registersHL = this.registersHL & 0xff00 | this.registerC;
},
//LD L, D
//#0x6A:
function () {
this.registersHL = this.registersHL & 0xff00 | this.registerD;
},
//LD L, E
//#0x6B:
function () {
this.registersHL = this.registersHL & 0xff00 | this.registerE;
},
//LD L, H
//#0x6C:
function () {
this.registersHL = this.registersHL & 0xff00 | this.registersHL >> 8;
},
//LD L, L
//#0x6D:
function () {
//Do nothing...
},
//LD L, (HL)
//#0x6E:
function () {
this.registersHL = this.registersHL & 0xff00 | this.readMemory(this.registersHL);
},
//LD L, A
//#0x6F:
function () {
this.registersHL = this.registersHL & 0xff00 | this.registerA;
},
//LD (HL), B
//#0x70:
function () {
this.writeMemory(
this.registersHL,
this.registerB
);
},
//LD (HL), C
//#0x71:
function () {
this.writeMemory(
this.registersHL,
this.registerC
);
},
//LD (HL), D
//#0x72:
function () {
this.writeMemory(
this.registersHL,
this.registerD
);
},
//LD (HL), E
//#0x73:
function () {
this.writeMemory(
this.registersHL,
this.registerE
);
},
//LD (HL), H
//#0x74:
function () {
this.writeMemory(
this.registersHL,
this.registersHL >> 8
);
},
//LD (HL), L
//#0x75:
function () {
this.writeMemory(
this.registersHL,
this.registersHL & 0xff
);
},
//HALT
//#0x76:
function () {
//See if there's already an IRQ match:
if ((this.interruptEnabledFlags & this.interruptRequestedFlags & 0x1f) > 0) {
if (!this.cartridge.useGbcMode && !this.usedBootROM) {
//HALT bug in the DMG CPU model (Program Counter fails to increment for one instruction after HALT):
this.skipPCIncrement = true;
} else {
//CGB gets around the HALT PC bug by doubling the hidden NOP.
this.currentInstructionCycleCount += 4;
}
} else {
//CPU is stalled until the next IRQ match:
this.calculateHALTPeriod();
}
},
//LD (HL), A
//#0x77:
function () {
this.writeMemory(
this.registersHL,
this.registerA
);
},
//LD A, B
//#0x78:
function () {
this.registerA = this.registerB;
},
//LD A, C
//#0x79:
function () {
this.registerA = this.registerC;
},
//LD A, D
//#0x7A:
function () {
this.registerA = this.registerD;
},
//LD A, E
//#0x7B:
function () {
this.registerA = this.registerE;
},
//LD A, H
//#0x7C:
function () {
this.registerA = this.registersHL >> 8;
},
//LD A, L
//#0x7D:
function () {
this.registerA = this.registersHL & 0xff;
},
//LD, A, (HL)
//#0x7E:
function () {
this.registerA = this.readMemory(this.registersHL);
},
//LD A, A
//#0x7F:
function () {
//Do Nothing...
},
//ADD A, B
//#0x80:
function () {
var dirtySum = this.registerA + this.registerB;
this.FHalfCarry = (dirtySum & 0xf) < (this.registerA & 0xf);
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADD A, C
//#0x81:
function () {
var dirtySum = this.registerA + this.registerC;
this.FHalfCarry = (dirtySum & 0xf) < (this.registerA & 0xf);
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADD A, D
//#0x82:
function () {
var dirtySum = this.registerA + this.registerD;
this.FHalfCarry = (dirtySum & 0xf) < (this.registerA & 0xf);
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADD A, E
//#0x83:
function () {
var dirtySum = this.registerA + this.registerE;
this.FHalfCarry = (dirtySum & 0xf) < (this.registerA & 0xf);
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADD A, H
//#0x84:
function () {
var dirtySum = this.registerA + (this.registersHL >> 8);
this.FHalfCarry = (dirtySum & 0xf) < (this.registerA & 0xf);
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADD A, L
//#0x85:
function () {
var dirtySum = this.registerA + (this.registersHL & 0xff);
this.FHalfCarry = (dirtySum & 0xf) < (this.registerA & 0xf);
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADD A, (HL)
//#0x86:
function () {
var dirtySum = this.registerA + this.readMemory(this.registersHL);
this.FHalfCarry = (dirtySum & 0xf) < (this.registerA & 0xf);
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADD A, A
//#0x87:
function () {
this.FHalfCarry = (this.registerA & 0x8) === 0x8;
this.FCarry = this.registerA > 0x7f;
this.registerA = this.registerA << 1 & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADC A, B
//#0x88:
function () {
var dirtySum = this.registerA + this.registerB + (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) +
(this.registerB & 0xf) +
(this.FCarry ? 1 : 0) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADC A, C
//#0x89:
function () {
var dirtySum = this.registerA + this.registerC + (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) +
(this.registerC & 0xf) +
(this.FCarry ? 1 : 0) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADC A, D
//#0x8A:
function () {
var dirtySum = this.registerA + this.registerD + (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) +
(this.registerD & 0xf) +
(this.FCarry ? 1 : 0) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADC A, E
//#0x8B:
function () {
var dirtySum = this.registerA + this.registerE + (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) +
(this.registerE & 0xf) +
(this.FCarry ? 1 : 0) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADC A, H
//#0x8C:
function () {
var tempValue = this.registersHL >> 8;
var dirtySum = this.registerA + tempValue + (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) +
(tempValue & 0xf) +
(this.FCarry ? 1 : 0) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADC A, L
//#0x8D:
function () {
var tempValue = this.registersHL & 0xff;
var dirtySum = this.registerA + tempValue + (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) +
(tempValue & 0xf) +
(this.FCarry ? 1 : 0) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADC A, (HL)
//#0x8E:
function () {
var tempValue = this.readMemory(this.registersHL);
var dirtySum = this.registerA + tempValue + (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) +
(tempValue & 0xf) +
(this.FCarry ? 1 : 0) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//ADC A, A
//#0x8F:
function () {
//shift left register A one bit for some ops here as an optimization:
var dirtySum = this.registerA << 1 | (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA << 1 & 0x1e | (this.FCarry ? 1 : 0)) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//SUB A, B
//#0x90:
function () {
var dirtySum = this.registerA - this.registerB;
this.FHalfCarry = (this.registerA & 0xf) < (dirtySum & 0xf);
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//SUB A, C
//#0x91:
function () {
var dirtySum = this.registerA - this.registerC;
this.FHalfCarry = (this.registerA & 0xf) < (dirtySum & 0xf);
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//SUB A, D
//#0x92:
function () {
var dirtySum = this.registerA - this.registerD;
this.FHalfCarry = (this.registerA & 0xf) < (dirtySum & 0xf);
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//SUB A, E
//#0x93:
function () {
var dirtySum = this.registerA - this.registerE;
this.FHalfCarry = (this.registerA & 0xf) < (dirtySum & 0xf);
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//SUB A, H
//#0x94:
function () {
var dirtySum = this.registerA - (this.registersHL >> 8);
this.FHalfCarry = (this.registerA & 0xf) < (dirtySum & 0xf);
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//SUB A, L
//#0x95:
function () {
var dirtySum = this.registerA - (this.registersHL & 0xff);
this.FHalfCarry = (this.registerA & 0xf) < (dirtySum & 0xf);
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//SUB A, (HL)
//#0x96:
function () {
var dirtySum = this.registerA - this.readMemory(this.registersHL);
this.FHalfCarry = (this.registerA & 0xf) < (dirtySum & 0xf);
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//SUB A, A
//#0x97:
function () {
//number - same number === 0
this.registerA = 0;
this.FHalfCarry = this.FCarry = false;
this.FZero = this.FSubtract = true;
},
//SBC A, B
//#0x98:
function () {
var dirtySum = this.registerA - this.registerB - (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) -
(this.registerB & 0xf) -
(this.FCarry ? 1 : 0) <
0;
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = true;
},
//SBC A, C
//#0x99:
function () {
var dirtySum = this.registerA - this.registerC - (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) -
(this.registerC & 0xf) -
(this.FCarry ? 1 : 0) <
0;
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = true;
},
//SBC A, D
//#0x9A:
function () {
var dirtySum = this.registerA - this.registerD - (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) -
(this.registerD & 0xf) -
(this.FCarry ? 1 : 0) <
0;
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = true;
},
//SBC A, E
//#0x9B:
function () {
var dirtySum = this.registerA - this.registerE - (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) -
(this.registerE & 0xf) -
(this.FCarry ? 1 : 0) <
0;
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = true;
},
//SBC A, H
//#0x9C:
function () {
var temp_var = this.registersHL >> 8;
var dirtySum = this.registerA - temp_var - (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) -
(temp_var & 0xf) -
(this.FCarry ? 1 : 0) <
0;
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = true;
},
//SBC A, L
//#0x9D:
function () {
var dirtySum = this.registerA -
(this.registersHL & 0xff) -
(this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) -
(this.registersHL & 0xf) -
(this.FCarry ? 1 : 0) <
0;
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = true;
},
//SBC A, (HL)
//#0x9E:
function () {
var temp_var = this.readMemory(this.registersHL);
var dirtySum = this.registerA - temp_var - (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) -
(temp_var & 0xf) -
(this.FCarry ? 1 : 0) <
0;
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = true;
},
//SBC A, A
//#0x9F:
function () {
//Optimized SBC A:
if (this.FCarry) {
this.FZero = false;
this.FSubtract = this.FHalfCarry = this.FCarry = true;
this.registerA = 0xff;
} else {
this.FHalfCarry = this.FCarry = false;
this.FSubtract = this.FZero = true;
this.registerA = 0;
}
},
//AND B
//#0xA0:
function () {
this.registerA &= this.registerB;
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//AND C
//#0xA1:
function () {
this.registerA &= this.registerC;
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//AND D
//#0xA2:
function () {
this.registerA &= this.registerD;
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//AND E
//#0xA3:
function () {
this.registerA &= this.registerE;
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//AND H
//#0xA4:
function () {
this.registerA &= this.registersHL >> 8;
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//AND L
//#0xA5:
function () {
this.registerA &= this.registersHL;
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//AND (HL)
//#0xA6:
function () {
this.registerA &= this.readMemory(this.registersHL);
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//AND A
//#0xA7:
function () {
//number & same number = same number
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//XOR B
//#0xA8:
function () {
this.registerA ^= this.registerB;
this.FZero = this.registerA === 0;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//XOR C
//#0xA9:
function () {
this.registerA ^= this.registerC;
this.FZero = this.registerA === 0;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//XOR D
//#0xAA:
function () {
this.registerA ^= this.registerD;
this.FZero = this.registerA === 0;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//XOR E
//#0xAB:
function () {
this.registerA ^= this.registerE;
this.FZero = this.registerA === 0;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//XOR H
//#0xAC:
function () {
this.registerA ^= this.registersHL >> 8;
this.FZero = this.registerA === 0;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//XOR L
//#0xAD:
function () {
this.registerA ^= this.registersHL & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//XOR (HL)
//#0xAE:
function () {
this.registerA ^= this.readMemory(this.registersHL);
this.FZero = this.registerA === 0;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//XOR A
//#0xAF:
function () {
//number ^ same number === 0
this.registerA = 0;
this.FZero = true;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//OR B
//#0xB0:
function () {
this.registerA |= this.registerB;
this.FZero = this.registerA === 0;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//OR C
//#0xB1:
function () {
this.registerA |= this.registerC;
this.FZero = this.registerA === 0;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//OR D
//#0xB2:
function () {
this.registerA |= this.registerD;
this.FZero = this.registerA === 0;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//OR E
//#0xB3:
function () {
this.registerA |= this.registerE;
this.FZero = this.registerA === 0;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//OR H
//#0xB4:
function () {
this.registerA |= this.registersHL >> 8;
this.FZero = this.registerA === 0;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//OR L
//#0xB5:
function () {
this.registerA |= this.registersHL & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//OR (HL)
//#0xB6:
function () {
this.registerA |= this.readMemory(this.registersHL);
this.FZero = this.registerA === 0;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//OR A
//#0xB7:
function () {
//number | same number === same number
this.FZero = this.registerA === 0;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//CP B
//#0xB8:
function () {
var dirtySum = this.registerA - this.registerB;
this.FHalfCarry = (dirtySum & 0xf) > (this.registerA & 0xf);
this.FCarry = dirtySum < 0;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//CP C
//#0xB9:
function () {
var dirtySum = this.registerA - this.registerC;
this.FHalfCarry = (dirtySum & 0xf) > (this.registerA & 0xf);
this.FCarry = dirtySum < 0;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//CP D
//#0xBA:
function () {
var dirtySum = this.registerA - this.registerD;
this.FHalfCarry = (dirtySum & 0xf) > (this.registerA & 0xf);
this.FCarry = dirtySum < 0;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//CP E
//#0xBB:
function () {
var dirtySum = this.registerA - this.registerE;
this.FHalfCarry = (dirtySum & 0xf) > (this.registerA & 0xf);
this.FCarry = dirtySum < 0;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//CP H
//#0xBC:
function () {
var dirtySum = this.registerA - (this.registersHL >> 8);
this.FHalfCarry = (dirtySum & 0xf) > (this.registerA & 0xf);
this.FCarry = dirtySum < 0;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//CP L
//#0xBD:
function () {
var dirtySum = this.registerA - (this.registersHL & 0xff);
this.FHalfCarry = (dirtySum & 0xf) > (this.registerA & 0xf);
this.FCarry = dirtySum < 0;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//CP (HL)
//#0xBE:
function () {
var dirtySum = this.registerA - this.readMemory(this.registersHL);
this.FHalfCarry = (dirtySum & 0xf) > (this.registerA & 0xf);
this.FCarry = dirtySum < 0;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//CP A
//#0xBF:
function () {
this.FHalfCarry = this.FCarry = false;
this.FZero = this.FSubtract = true;
},
//RET !FZ
//#0xC0:
function () {
if (!this.FZero) {
this.programCounter = this.readMemory(this.stackPointer + 1 & 0xffff) << 8 | this.readMemory(this.stackPointer);
this.stackPointer = this.stackPointer + 2 & 0xffff;
this.currentInstructionCycleCount += 12;
}
},
//POP BC
//#0xC1:
function () {
this.registerC = this.readMemory(this.stackPointer);
this.registerB = this.readMemory(this.stackPointer + 1 & 0xffff);
this.stackPointer = this.stackPointer + 2 & 0xffff;
},
//JP !FZ, nn
//#0xC2:
function () {
if (!this.FZero) {
this.programCounter = this.readMemory(this.programCounter + 1 & 0xffff) <<
8 |
this.readMemory(this.programCounter);
this.currentInstructionCycleCount += 4;
} else {
this.programCounter = this.programCounter + 2 & 0xffff;
}
},
//JP nn
//#0xC3:
function () {
this.programCounter = this.readMemory(this.programCounter + 1 & 0xffff) <<
8 |
this.readMemory(this.programCounter);
},
//CALL !FZ, nn
//#0xC4:
function () {
if (!this.FZero) {
var temp_pc = this.readMemory(this.programCounter + 1 & 0xffff) << 8 |
this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 2 & 0xffff;
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = temp_pc;
this.currentInstructionCycleCount += 12;
} else {
this.programCounter = this.programCounter + 2 & 0xffff;
}
},
//PUSH BC
//#0xC5:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.registerB
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.registerC
);
},
//ADD, n
//#0xC6:
function () {
var dirtySum = this.registerA +
this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
this.FHalfCarry = (dirtySum & 0xf) < (this.registerA & 0xf);
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//RST 0
//#0xC7:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = 0;
},
//RET FZ
//#0xC8:
function () {
if (this.FZero) {
this.programCounter = this.readMemory(this.stackPointer + 1 & 0xffff) << 8 | this.readMemory(this.stackPointer);
this.stackPointer = this.stackPointer + 2 & 0xffff;
this.currentInstructionCycleCount += 12;
}
},
//RET
//#0xC9:
function () {
this.programCounter = this.readMemory(this.stackPointer + 1 & 0xffff) << 8 | this.readMemory(this.stackPointer);
this.stackPointer = this.stackPointer + 2 & 0xffff;
},
//JP FZ, nn
//#0xCA:
function () {
if (this.FZero) {
this.programCounter = this.readMemory(this.programCounter + 1 & 0xffff) << 8 | this.readMemory(this.programCounter);
this.currentInstructionCycleCount += 4;
} else {
this.programCounter = this.programCounter + 2 & 0xffff;
}
},
//Secondary OP Code Set:
//#0xCB:
function () {
const operationCode = this.readMemory(this.programCounter);
//Increment the program counter to the next instruction:
this.programCounter = this.programCounter + 1 & 0xffff;
//Get how many CPU cycles the current 0xCBXX op code counts for:
this.currentInstructionCycleCount += SecondaryTickTable[operationCode];
//Execute secondary OP codes for the 0xCB OP code call.
bitInstructions[operationCode].apply(this);
},
//CALL FZ, nn
//#0xCC:
function () {
if (this.FZero) {
var temp_pc = this.readMemory(this.programCounter + 1 & 0xffff) << 8 | this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 2 & 0xffff;
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = temp_pc;
this.currentInstructionCycleCount += 12;
} else {
this.programCounter = this.programCounter + 2 & 0xffff;
}
},
//CALL nn
//#0xCD:
function () {
var temp_pc = this.readMemory(this.programCounter + 1 & 0xffff) << 8 |
this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 2 & 0xffff;
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = temp_pc;
},
//ADC A, n
//#0xCE:
function () {
var tempValue = this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
var dirtySum = this.registerA + tempValue + (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) +
(tempValue & 0xf) +
(this.FCarry ? 1 : 0) >
0xf;
this.FCarry = dirtySum > 0xff;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = false;
},
//RST 0x8
//#0xCF:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = 0x8;
},
//RET !FC
//#0xD0:
function () {
if (!this.FCarry) {
this.programCounter = this.readMemory(this.stackPointer + 1 & 0xffff) << 8 | this.readMemory(this.stackPointer);
this.stackPointer = this.stackPointer + 2 & 0xffff;
this.currentInstructionCycleCount += 12;
}
},
//POP DE
//#0xD1:
function () {
this.registerE = this.readMemory(this.stackPointer);
this.registerD = this.readMemory(this.stackPointer + 1 & 0xffff);
this.stackPointer = this.stackPointer + 2 & 0xffff;
},
//JP !FC, nn
//#0xD2:
function () {
if (!this.FCarry) {
this.programCounter = this.readMemory(this.programCounter + 1 & 0xffff) <<
8 |
this.readMemory(this.programCounter);
this.currentInstructionCycleCount += 4;
} else {
this.programCounter = this.programCounter + 2 & 0xffff;
}
},
//0xD3 - Illegal
//#0xD3:
function () {
console.error("Illegal op code 0xD3 called, pausing emulation.");
},
//CALL !FC, nn
//#0xD4:
function () {
if (!this.FCarry) {
var temp_pc = this.readMemory(this.programCounter + 1 & 0xffff) << 8 | this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 2 & 0xffff;
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = temp_pc;
this.currentInstructionCycleCount += 12;
} else {
this.programCounter = this.programCounter + 2 & 0xffff;
}
},
//PUSH DE
//#0xD5:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.registerD
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.registerE
);
},
//SUB A, n
//#0xD6:
function () {
var dirtySum = this.registerA - this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
this.FHalfCarry = (this.registerA & 0xf) < (dirtySum & 0xf);
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//RST 0x10
//#0xD7:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = 0x10;
},
//RET FC
//#0xD8:
function () {
if (this.FCarry) {
this.programCounter = this.readMemory(this.stackPointer + 1 & 0xffff) << 8 | this.readMemory(this.stackPointer);
this.stackPointer = this.stackPointer + 2 & 0xffff;
this.currentInstructionCycleCount += 12;
}
},
//RETI
//#0xD9:
function () {
this.programCounter = this.readMemory(this.stackPointer + 1 & 0xffff) << 8 | this.readMemory(this.stackPointer);
this.stackPointer = this.stackPointer + 2 & 0xffff;
//Immediate for HALT:
this.IRQEnableDelay = this.IRQEnableDelay === 2 || this.readMemory(this.programCounter) === 0x76 ? 1 : 2;
},
//JP FC, nn
//#0xDA:
function () {
if (this.FCarry) {
this.programCounter = this.readMemory(this.programCounter + 1 & 0xffff) <<
8 |
this.readMemory(this.programCounter);
this.currentInstructionCycleCount += 4;
} else {
this.programCounter = this.programCounter + 2 & 0xffff;
}
},
//0xDB - Illegal
//#0xDB:
function () {
console.error("Illegal op code 0xDB called, pausing emulation.");
},
//CALL FC, nn
//#0xDC:
function () {
if (this.FCarry) {
var temp_pc = this.readMemory(this.programCounter + 1 & 0xffff) << 8 |
this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 2 & 0xffff;
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = temp_pc;
this.currentInstructionCycleCount += 12;
} else {
this.programCounter = this.programCounter + 2 & 0xffff;
}
},
//0xDD - Illegal
//#0xDD:
function () {
console.error("Illegal op code 0xDD called, pausing emulation.");
},
//SBC A, n
//#0xDE:
function () {
var temp_var = this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
var dirtySum = this.registerA - temp_var - (this.FCarry ? 1 : 0);
this.FHalfCarry = (this.registerA & 0xf) -
(temp_var & 0xf) -
(this.FCarry ? 1 : 0) <
0;
this.FCarry = dirtySum < 0;
this.registerA = dirtySum & 0xff;
this.FZero = this.registerA === 0;
this.FSubtract = true;
},
//RST 0x18
//#0xDF:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = 0x18;
},
//LDH (n), A
//#0xE0:
function () {
this.memoryHighWrite(this.readMemory(this.programCounter), this.registerA);
this.programCounter = this.programCounter + 1 & 0xffff;
},
//POP HL
//#0xE1:
function () {
this.registersHL = this.readMemory(this.stackPointer + 1 & 0xffff) << 8 | this.readMemory(this.stackPointer);
this.stackPointer = this.stackPointer + 2 & 0xffff;
},
//LD (0xFF00 + C), A
//#0xE2:
function () {
this.memoryHighWrite(this.registerC, this.registerA);
},
//0xE3 - Illegal
//#0xE3:
function () {
console.log("Illegal op code 0xE3 called, pausing emulation.");
},
//0xE4 - Illegal
//#0xE4:
function () {
console.log("Illegal op code 0xE4 called, pausing emulation.");
},
//PUSH HL
//#0xE5:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.registersHL >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.registersHL & 0xff
);
},
//AND n
//#0xE6:
function () {
this.registerA &= this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
this.FZero = this.registerA === 0;
this.FHalfCarry = true;
this.FSubtract = this.FCarry = false;
},
//RST 0x20
//#0xE7:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = 0x20;
},
//ADD SP, n
//#0xE8:
function () {
var temp_value2 = this.readMemory(this.programCounter) << 24 >> 24;
this.programCounter = this.programCounter + 1 & 0xffff;
var temp_value = this.stackPointer + temp_value2 & 0xffff;
temp_value2 = this.stackPointer ^ temp_value2 ^ temp_value;
this.stackPointer = temp_value;
this.FCarry = (temp_value2 & 0x100) === 0x100;
this.FHalfCarry = (temp_value2 & 0x10) === 0x10;
this.FZero = this.FSubtract = false;
},
//JP, (HL)
//#0xE9:
function () {
this.programCounter = this.registersHL;
},
//LD n, A
//#0xEA:
function () {
this.writeMemory(
this.readMemory(this.programCounter + 1 & 0xffff) << 8 |
this.readMemory(this.programCounter),
this.registerA
);
this.programCounter = this.programCounter + 2 & 0xffff;
},
//0xEB - Illegal
//#0xEB:
function () {
console.error("Illegal op code 0xEB called, pausing emulation.");
},
//0xEC - Illegal
//#0xEC:
function () {
console.error("Illegal op code 0xEC called, pausing emulation.");
},
//0xED - Illegal
//#0xED:
function () {
console.error("Illegal op code 0xED called, pausing emulation.");
},
//XOR n
//#0xEE:
function () {
this.registerA ^= this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
this.FZero = this.registerA === 0;
this.FSubtract = this.FHalfCarry = this.FCarry = false;
},
//RST 0x28
//#0xEF:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = 0x28;
},
//LDH A, (n)
//#0xF0:
function () {
this.registerA = this.memoryHighRead(this.readMemory(this.programCounter));
this.programCounter = this.programCounter + 1 & 0xffff;
},
//POP AF
//#0xF1:
function () {
var temp_var = this.readMemory(this.stackPointer);
this.FZero = temp_var > 0x7f;
this.FSubtract = (temp_var & 0x40) === 0x40;
this.FHalfCarry = (temp_var & 0x20) === 0x20;
this.FCarry = (temp_var & 0x10) === 0x10;
this.registerA = this.readMemory(this.stackPointer + 1 & 0xffff);
this.stackPointer = this.stackPointer + 2 & 0xffff;
},
//LD A, (0xFF00 + C)
//#0xF2:
function () {
this.registerA = this.memoryHighRead(this.registerC);
},
//DI
//#0xF3:
function () {
this.IME = false;
this.IRQEnableDelay = 0;
},
//0xF4 - Illegal
//#0xF4:
function () {
console.error("Illegal op code 0xF4 called, pausing emulation.");
},
//PUSH AF
//#0xF5:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.registerA
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
(this.FZero ? 0x80 : 0) |
(this.FSubtract ? 0x40 : 0) |
(this.FHalfCarry ? 0x20 : 0) |
(this.FCarry ? 0x10 : 0)
);
},
//OR n
//#0xF6:
function () {
this.registerA |= this.readMemory(this.programCounter);
this.FZero = this.registerA === 0;
this.programCounter = this.programCounter + 1 & 0xffff;
this.FSubtract = this.FCarry = this.FHalfCarry = false;
},
//RST 0x30
//#0xF7:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = 0x30;
},
//LDHL SP, n
//#0xF8:
function () {
var temp_var = this.readMemory(this.programCounter) << 24 >> 24;
this.programCounter = this.programCounter + 1 & 0xffff;
this.registersHL = this.stackPointer + temp_var & 0xffff;
temp_var = this.stackPointer ^ temp_var ^ this.registersHL;
this.FCarry = (temp_var & 0x100) === 0x100;
this.FHalfCarry = (temp_var & 0x10) === 0x10;
this.FZero = this.FSubtract = false;
},
//LD SP, HL
//#0xF9:
function () {
this.stackPointer = this.registersHL;
},
//LD A, (nn)
//#0xFA:
function () {
this.registerA = this.readMemory(
this.readMemory(this.programCounter + 1 & 0xffff) << 8 |
this.readMemory(this.programCounter)
);
this.programCounter = this.programCounter + 2 & 0xffff;
},
//EI
//#0xFB:
function () {
//Immediate for HALT:
this.IRQEnableDelay = this.IRQEnableDelay === 2 ||
this.readMemory(this.programCounter) === 0x76 ? 1 : 2;
},
//0xFC - Illegal
//#0xFC:
() => console.error("Illegal op code 0xFC called, pausing emulation."),
//0xFD - Illegal
//#0xFD:
() => console.error("Illegal op code 0xFD called, pausing emulation."),
//CP n
//#0xFE:
function () {
var dirtySum = this.registerA - this.readMemory(this.programCounter);
this.programCounter = this.programCounter + 1 & 0xffff;
this.FHalfCarry = (dirtySum & 0xf) > (this.registerA & 0xf);
this.FCarry = dirtySum < 0;
this.FZero = dirtySum === 0;
this.FSubtract = true;
},
//RST 0x38
//#0xFF:
function () {
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter >> 8
);
this.stackPointer = this.stackPointer - 1 & 0xffff;
this.writeMemory(
this.stackPointer,
this.programCounter & 0xff
);
this.programCounter = 0x38;
}
];
| mit |
hcorion/RoverVR | Assets/NewtonVR/NVRHead.cs | 132 | using UnityEngine;
using System.Collections;
namespace NewtonVR
{
public class NVRHead : MonoBehaviour
{
}
} | mit |
sutromedia/android-travel-guide | android-app-core/src/com/sutromedia/android/lib/model/IEntryDetail.java | 691 | package com.sutromedia.android.lib.model;
import android.location.Location;
import java.util.List;
public interface IEntryDetail {
String getId();
String getSubtitle();
String getDescription();
Location getLocation();
List<IGroup> getGroups();
String getAddress();
String getPhoneRaw();
String getPhoneFormatted();
String getWebUrl();
String getAudioUrl();
String getTwitter();
CurrencyAmount getAudioPrice();
String getPriceDetails();
String getHours();
String getTwitterAccount();
String getVideoUrl();
String getReservationUrl();
String getFacebookUrl();
String getFacebookAccount();
} | mit |
i18next/react-i18next | test/trans.render.icu.spec.js | 2966 | import React from 'react';
import { render, screen } from '@testing-library/react';
import './i18n';
import { Trans } from '../src/Trans';
describe('trans using no children but props - icu case', () => {
const TestComponent = () => (
<Trans
defaults="hello <0>{{what}}</0>"
values={{ what: 'world' }}
components={[<strong>universe</strong>]}
/>
);
it('should render translated string', () => {
const { container } = render(<TestComponent />);
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
hello
<strong>
world
</strong>
</div>
`);
});
});
describe('trans using no children but props - nested case', () => {
const TestComponent = () => (
<Trans
defaults="<0>hello <1></1> {{what}}</0>"
values={{ what: 'world' }}
components={[
<span>
placeholder
<br />
</span>,
]}
/>
);
it('should render translated string', () => {
const { container } = render(<TestComponent />);
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
<span>
hello
<br />
world
</span>
</div>
`);
});
});
describe('trans using no children but props - self closing case', () => {
const TestComponent = () => (
<Trans defaults="hello <0/>{{what}}" values={{ what: 'world' }} components={[<br />]} />
);
it('should render translated string', () => {
const { container } = render(<TestComponent />);
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
hello
<br />
world
</div>
`);
});
});
describe('Trans should use value from translation', () => {
it('should use value from translation if no data provided in component', () => {
const TestComponent = () => (
<Trans
i18nKey="testTrans5KeyWithValue"
values={{
testValue: 'dragonfly',
}}
components={[<span className="awesome-styles" />]}
/>
);
const { container } = render(<TestComponent />);
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
Result should be rendered within tag
<span
class="awesome-styles"
>
dragonfly
</span>
</div>
`);
});
it('should use value from translation if dummy data provided in component', () => {
const TestComponent = () => (
<Trans
i18nKey="testTrans5KeyWithValue"
values={{
testValue: 'dragonfly',
}}
components={[<span className="awesome-styles">test string</span>]}
/>
);
const { container } = render(<TestComponent />);
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
Result should be rendered within tag
<span
class="awesome-styles"
>
dragonfly
</span>
</div>
`);
});
});
| mit |
ignazas/ma2016 | vendor/nova-framework/system/src/Cache/RedisTaggedCache.php | 2120 | <?php
namespace Nova\Cache;
class RedisTaggedCache extends TaggedCache
{
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function forever($key, $value)
{
$this->pushForeverKeys($namespace = $this->tags->getNamespace(), $key);
$this->store->forever(sha1($namespace).':'.$key, $value);
}
/**
* Remove all items from the cache.
*
* @return void
*/
public function flush()
{
$this->deleteForeverKeys();
parent::flush();
}
/**
* Store a copy of the full key for each namespace segment.
*
* @param string $namespace
* @param string $key
* @return void
*/
protected function pushForeverKeys($namespace, $key)
{
$fullKey = $this->getPrefix().sha1($namespace).':'.$key;
foreach (explode('|', $namespace) as $segment) {
$this->store->connection()->lpush($this->foreverKey($segment), $fullKey);
}
}
/**
* Delete all of the items that were stored forever.
*
* @return void
*/
protected function deleteForeverKeys()
{
foreach (explode('|', $this->tags->getNamespace()) as $segment) {
$this->deleteForeverValues($segment = $this->foreverKey($segment));
$this->store->connection()->del($segment);
}
}
/**
* Delete all of the keys that have been stored forever.
*
* @param string $foreverKey
* @return void
*/
protected function deleteForeverValues($foreverKey)
{
$forever = array_unique($this->store->connection()->lrange($foreverKey, 0, -1));
if (count($forever) > 0) {
call_user_func_array(array($this->store->connection(), 'del'), $forever);
}
}
/**
* Get the forever reference key for the segment.
*
* @param string $segment
* @return string
*/
protected function foreverKey($segment)
{
return $this->getPrefix().$segment.':forever';
}
}
| mit |
cuescience/cuescience-shop | shop/specs/models/models.py | 7551 | from natspec_utils.stringutils import stringToUnicode as u;
from jinja2.environment import Environment
from jinja2.loaders import PackageLoader
from django_lean_modelling import helper
from django_lean_modelling.models import support
from django_lean_modelling.admin.support import AdminSupport
class Models():
def __init__(self):
self.model_support = support.ModelSupport()
self.admin_support = AdminSupport()
def generate_models(self):
"""
The code in this method is generated from: /cuescience-shop/shop/specs/models/models.natspec
Never change this method or any contents of this file, all local changes will we overwritten.
"""
# Every Product has:
model_Product = self.model_support.model_name_definition([u("Product")])
# - a title.
property_title = self.model_support.string_property_definition([u("title")], model_Product)
# The title of the product
self.model_support.comment_definition(['The', 'title', 'of', 'the', 'product'], property_title)
# - a price as decimal:
property_price = self.model_support.typed_decimal_property_definition([u("price")], model_Product)
# The price without tax. The maximum value is 9999,99
self.model_support.comment_definition(['The', 'price', 'without', 'tax.', 'The', 'maximum', 'value', 'is', '9999,99'], property_price)
# decimal places: 2
self.model_support.property_decimal_places_definition(2, property_price)
# max digits: 6
self.model_support.property_max_digits_definition(6, property_price)
# Configure standard admin.
admin_ = self.admin_support.configure_admin(model_Product)
# Every Order has:
model_Order = self.model_support.model_name_definition([u("Order")])
# - a order number.
property_order_number = self.model_support.string_property_definition([u("order"), u("number")], model_Order)
# - one Client.
property_Client = self.model_support.foreign_key_property_definition(u("Client"), model_Order)
# The client wich has ordered.
self.model_support.comment_definition(['The', 'client', 'wich', 'has', 'ordered.'], property_Client)
# - one cart.Cart.
property_cart_Cart = self.model_support.foreign_key_property_definition(u("cart.Cart"), model_Order)
# The cart contains the ordered products, quantities and total price
self.model_support.comment_definition(['The', 'cart', 'contains', 'the', 'ordered', 'products,', 'quantities', 'and', 'total', 'price'], property_cart_Cart)
# - one exclusive cuescience_payment.Payment called payment.
property_cuescience_payment_Payment_payment = self.model_support.one_to_one_with_name_property_definition(u("cuescience_payment.Payment"), [u("payment")], model_Order)
# Configure admin to:
admin_0 = self.admin_support.configure_admin(model_Order)
# - display: order number, client.
property_order_number__client = self.admin_support.display_definition([u("order"), u("number,"), u("client")], admin_0)
# - show filter for: client.
property_client = self.admin_support.filter_definition([u("client")], admin_0)
# Every Client has:
model_Client = self.model_support.model_name_definition([u("Client")])
# - a client number:
property_client_number = self.model_support.string_property_definition([u("client"), u("number")], model_Client)
# max length: 6
self.model_support.property_max_length_definition(6, property_client_number)
# - an email.
property_ = self.model_support.email_property_definition(model_Client)
# - a first name.
property_first_name = self.model_support.string_property_definition([u("first"), u("name")], model_Client)
# - a last name.
property_last_name = self.model_support.string_property_definition([u("last"), u("name")], model_Client)
# - one exclusive Address called billing address.
property_Address_billing_address = self.model_support.one_to_one_with_name_property_definition(u("Address"), [u("billing"), u("address")], model_Client)
# - one exclusive Address called shipping address.
property_Address_shipping_address = self.model_support.one_to_one_with_name_property_definition(u("Address"), [u("shipping"), u("address")], model_Client)
# Configure admin to:
admin_1 = self.admin_support.configure_admin(model_Client)
# - display: client number, first name, last name.
property_client_number__first_name__last_name = self.admin_support.display_definition([u("client"), u("number,"), u("first"), u("name,"), u("last"), u("name")], admin_1)
# - show filter for: shipping address__city.
property_shipping_address__city = self.admin_support.filter_definition([u("shipping"), u("address__city")], admin_1)
# Every Address (plural Addresses) has:
model_Address_Addresses = self.model_support.model_name_with_plural_definition([u("Address")], [u("Addresses")])
# - a street.
property_street = self.model_support.string_property_definition([u("street")], model_Address_Addresses)
# - a number:
property_number = self.model_support.string_property_definition([u("number")], model_Address_Addresses)
# The street number contains the number itself as well as extra characters, e.g. 41c
self.model_support.comment_definition(['The', 'street', 'number', 'contains', 'the', 'number', 'itself', 'as', 'well', 'as', 'extra', 'characters,', 'e.g.', '41c'], property_number)
# max length: 5
self.model_support.property_max_length_definition(5, property_number)
# - a postcode:
property_postcode = self.model_support.string_property_definition([u("postcode")], model_Address_Addresses)
# The German postcode, maybe not suitable for other countries.
self.model_support.comment_definition(['The', 'German', 'postcode,', 'maybe', 'not', 'suitable', 'for', 'other', 'countries.'], property_postcode)
# max length: 5
self.model_support.property_max_length_definition(5, property_postcode)
# - a city.
property_city = self.model_support.string_property_definition([u("city")], model_Address_Addresses)
# Configure standard admin.
admin_2 = self.admin_support.configure_admin(model_Address_Addresses)
if __name__ == '__main__':
model = Models()
model.generate_models()
env = Environment(loader=PackageLoader('shop.specs', 'templates'), trim_blocks=False)
template = env.get_template("model_template.py")
content = template.render(models=model.model_support.models)
template_admin = env.get_template("admin_template.py")
content_admin = template_admin.render(admins=model.admin_support.admins)
print model.admin_support.admins
f = open("../../%s_abstract.py" % helper.convert(model.__class__.__name__), 'w')
f.write(content)
f.close()
f1 = open("../../admin.py", 'w')
f1.write(content_admin)
f1.close() | mit |
melanchall/drymidi | DryWetMidi/Devices/Clock/MidiClockSettings.cs | 1004 | using System;
using Melanchall.DryWetMidi.Common;
namespace Melanchall.DryWetMidi.Devices
{
/// <summary>
/// Holds settings for <see cref="MidiClock"/> used by a clock driven object.
/// </summary>
public sealed class MidiClockSettings
{
#region Fields
private Func<TickGenerator> _createTickGeneratorCallback = () => new HighPrecisionTickGenerator();
#endregion
#region Properties
/// <summary>
/// Gets or sets a callback used to create tick generator for MIDI clock.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c>.</exception>
public Func<TickGenerator> CreateTickGeneratorCallback
{
get { return _createTickGeneratorCallback; }
set
{
ThrowIfArgument.IsNull(nameof(value), value);
_createTickGeneratorCallback = value;
}
}
#endregion
}
}
| mit |
lunchiatto/web | app/assets/javascripts/entities/invitation.js | 333 | window.Lunchiatto.module('Entities', function(Entities, App, Backbone, Marionette, $, _) {
Entities.Invitation = Backbone.Model.extend({
urlRoot: '/api/invitations'
});
return Entities.Invitations = Backbone.Collection.extend({
model: Entities.Invitation,
url() {
return '/api/invitations';
}
});
});
| mit |
sonvister/Binance | src/Binance/Api/RateLimit/RateLimiter.cs | 4716 | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
// ReSharper disable once CheckNamespace
namespace Binance.Api
{
public class RateLimiter : IRateLimiter
{
#region Public Properties
public int Count
{
get => _count;
set
{
if (value <= 0)
throw new ArgumentException($"{nameof(IApiRateLimiter)} configured count must be greater than 0.", nameof(Count));
_count = value;
while (_timestamps.Count > _count)
{
_timestamps.Dequeue();
}
}
}
public TimeSpan Duration { get; set; } = TimeSpan.FromSeconds(1);
#endregion Public Properties
#region Private Fields
private int _count;
private readonly SemaphoreSlim _syncLock = new SemaphoreSlim(1, 1);
private readonly Queue<long> _timestamps = new Queue<long>();
private readonly ILogger<RateLimiter> _logger;
#endregion Private Fields
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="logger"></param>
public RateLimiter(ILogger<RateLimiter> logger = null)
{
_logger = logger;
}
#endregion Constructors
#region Public Methods
public async Task DelayAsync(int count = 1, CancellationToken token = default)
{
if (count < 1)
throw new ArgumentException($"{nameof(RateLimiter)}.{nameof(DelayAsync)} {nameof(count)} must not be less than 1.", nameof(count));
if (_count == 0)
return;
ThrowIfDisposed();
// Acquire synchronization lock.
await _syncLock.WaitAsync(token)
.ConfigureAwait(false);
try
{
// Create the current timestamp.
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
do
{
// If the maximum count has not been reached.
if (_timestamps.Count < _count)
{
// Queue the current timestammp.
_timestamps.Enqueue(now);
continue;
}
// Remove the oldest timestamp.
var then = _timestamps.Dequeue();
var millisecondsDelay = 0;
try
{
// How long has it been?
var time = Convert.ToInt32(now - then);
// If elapsed time is less than allowed time...
if (time < Duration.TotalMilliseconds)
{
// ...set the delay as the time difference.
millisecondsDelay = Convert.ToInt32(Duration.TotalMilliseconds) - time;
}
}
catch (OverflowException) { /* ignore */ }
// Add the current/future timestammp.
_timestamps.Enqueue(now + millisecondsDelay);
// Delay if required.
if (millisecondsDelay <= 0)
continue;
_logger?.LogDebug($"{nameof(RateLimiter)} delaying for {millisecondsDelay} msec.");
await Task.Delay(millisecondsDelay, token)
.ConfigureAwait(false);
if (count > 1)
{
now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
} while (--count > 0);
}
catch (Exception) { /* ignore */ }
finally
{
// Release synchronization lock.
_syncLock.Release();
}
}
#endregion Public Methods
#region IDisposable
private bool _disposed;
protected void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(nameof(RateLimiter));
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
_syncLock?.Dispose();
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
}
#endregion IDisposable
}
}
| mit |
uia-worker/is105misc | bdcakecandles.go | 996 | package main
import "fmt"
func main() {
//Enter your code here. Read input from STDIN. Print output to STDOUT
var n, tall int64
fmt.Scanf("%v\n", &n)
if n >= 1 && n <= 10e+5 {
height := make([]int64, n)
tall = 0
counter := 0
for i := range height {
fmt.Scanf("%d", &height[i])
if height[i] >= 1 && height[i] <= 10e+7 {
// Calculation or comparision
//for j := range height {
if height[i] > tall {
tall = height[i]
counter = 1
//fmt.Printf("isLarger %d, height[%d]=%d, tall=%d\n", counter, i, height[i], tall)
} else if height[i] == tall {
counter++
//fmt.Printf("isEqual %d, height[%d]=%d, tall=%d\n", counter, i, height[i], tall)
}
//}
}
}
fmt.Println(counter)
}
}
| mit |
lujinda/gale | gale/iosocket.py | 1670 | #!/usr/bin/env python
#coding:utf8
# Author : tuxpy
# Email : [email protected]
# Last modified : 2015-03-26 12:55:47
# Filename : gale/socket.py
# Description :
from __future__ import unicode_literals
import gevent
from gevent import socket
class IOSocket():
def __init__(self, socket, max_buff= 4096):
self._socket = socket
self.max_buff = max_buff
self.closed = False
self._buff = b''
self.on_close_callback = None
def write(self, chunk):
self._socket.sendall(chunk)
def clone(self):
return IOSocket(self._socket, self.max_buff)
def gevent_exception(self, *args, **kwargs):
self.close()
def close(self):
if self.closed:
return
self.on_close()
self._socket.close()
self.closed = True
def set_timeout(self, secs = 60):
self._socket.settimeout(secs)
def on_close(self): # 在RequestHandler中会被赋值
if self.on_close_callback:
self.on_close_callback()
def send_string(self, string):
try:
self._socket.sendall(string)
except Exception as e:
self.close()
def is_close(self):
if self.closed:
return True
try:
if (self._socket.getpeername()): # 如果 closed是False,为了避免有时socket会异常断开,就再判断一下
return False
except:
return True
def recv(self, buffer_size):
try:
chunk = self._socket.recv(buffer_size)
return chunk
except Exception as ex:
return None
| mit |
maichong/ucp | tests/encryption.js | 474 | /**
* @copyright Maichong Software Ltd. 2016 http://maichong.it
* @date 2016-04-10
* @author Liang <[email protected]>
*/
'use strict';
const Encryption = require('../lib/encryption');
const encryption = new Encryption('123456');
let data = new Buffer('Hello world');
console.log(data, data.length);
data = encryption.encrypt(data);
console.log(data, data.length);
data = encryption.decrypt(data);
console.log(data, data.length);
console.log(data.toString());
| mit |
graphql-python/graphql-core | tests/utilities/test_print_schema.py | 26380 | from typing import cast, Any, Dict
from graphql.language import DirectiveLocation
from graphql.type import (
GraphQLArgument,
GraphQLBoolean,
GraphQLEnumType,
GraphQLField,
GraphQLFloat,
GraphQLInputObjectType,
GraphQLInt,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLScalarType,
GraphQLSchema,
GraphQLString,
GraphQLUnionType,
GraphQLInputField,
GraphQLDirective,
)
from graphql.utilities import (
build_schema,
print_schema,
print_introspection_schema,
print_value,
)
from ..utils import dedent
def expect_printed_schema(schema: GraphQLSchema) -> str:
schema_text = print_schema(schema)
# keep print_schema and build_schema in sync
assert print_schema(build_schema(schema_text)) == schema_text
return schema_text
def build_single_field_schema(field: GraphQLField):
query = GraphQLObjectType(name="Query", fields={"singleField": field})
return GraphQLSchema(query=query)
def describe_type_system_printer():
def prints_string_field():
schema = build_single_field_schema(GraphQLField(GraphQLString))
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField: String
}
"""
)
def prints_list_of_string_field():
schema = build_single_field_schema(GraphQLField(GraphQLList(GraphQLString)))
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField: [String]
}
"""
)
def prints_non_null_string_field():
schema = build_single_field_schema(GraphQLField(GraphQLNonNull(GraphQLString)))
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField: String!
}
"""
)
def prints_non_null_list_of_string_field():
schema = build_single_field_schema(
GraphQLField(GraphQLNonNull(GraphQLList(GraphQLString)))
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField: [String]!
}
"""
)
def prints_list_of_non_null_string_field():
schema = build_single_field_schema(
GraphQLField((GraphQLList(GraphQLNonNull(GraphQLString))))
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField: [String!]
}
"""
)
def prints_non_null_list_of_non_null_string_field():
schema = build_single_field_schema(
GraphQLField(GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString))))
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField: [String!]!
}
"""
)
def prints_object_field():
foo_type = GraphQLObjectType(
name="Foo", fields={"str": GraphQLField(GraphQLString)}
)
schema = GraphQLSchema(types=[foo_type])
assert expect_printed_schema(schema) == dedent(
"""
type Foo {
str: String
}
"""
)
def prints_string_field_with_int_arg():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString, args={"argOne": GraphQLArgument(GraphQLInt)}
)
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField(argOne: Int): String
}
"""
)
def prints_string_field_with_int_arg_with_default():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString,
args={"argOne": GraphQLArgument(GraphQLInt, default_value=2)},
)
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField(argOne: Int = 2): String
}
"""
)
def prints_string_field_with_string_arg_with_default():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString,
args={
"argOne": GraphQLArgument(
GraphQLString, default_value="tes\t de\fault"
)
},
)
)
assert expect_printed_schema(schema) == dedent(
r"""
type Query {
singleField(argOne: String = "tes\t de\fault"): String
}
"""
)
def prints_string_field_with_int_arg_with_default_null():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString,
args={"argOne": GraphQLArgument(GraphQLInt, default_value=None)},
)
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField(argOne: Int = null): String
}
"""
)
def prints_string_field_with_non_null_int_arg():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString,
args={"argOne": GraphQLArgument(GraphQLNonNull(GraphQLInt))},
)
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField(argOne: Int!): String
}
"""
)
def prints_string_field_with_multiple_args():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString,
args={
"argOne": GraphQLArgument(GraphQLInt),
"argTwo": GraphQLArgument(GraphQLString),
},
)
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField(argOne: Int, argTwo: String): String
}
"""
)
def prints_string_field_with_multiple_args_first_is_default():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString,
args={
"argOne": GraphQLArgument(GraphQLInt, default_value=1),
"argTwo": GraphQLArgument(GraphQLString),
"argThree": GraphQLArgument(GraphQLBoolean),
},
)
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField(argOne: Int = 1, argTwo: String, argThree: Boolean): String
}
"""
)
def prints_string_field_with_multiple_args_second_is_default():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString,
args={
"argOne": GraphQLArgument(GraphQLInt),
"argTwo": GraphQLArgument(GraphQLString, default_value="foo"),
"argThree": GraphQLArgument(GraphQLBoolean),
},
)
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField(argOne: Int, argTwo: String = "foo", argThree: Boolean): String
}
""" # noqa: E501
)
def prints_string_field_with_multiple_args_last_is_default():
schema = build_single_field_schema(
GraphQLField(
type_=GraphQLString,
args={
"argOne": GraphQLArgument(GraphQLInt),
"argTwo": GraphQLArgument(GraphQLString),
"argThree": GraphQLArgument(GraphQLBoolean, default_value=False),
},
)
)
assert expect_printed_schema(schema) == dedent(
"""
type Query {
singleField(argOne: Int, argTwo: String, argThree: Boolean = false): String
}
""" # noqa: E501
)
def prints_schema_with_description():
schema = GraphQLSchema(
description="Schema description.", query=GraphQLObjectType("Query", {})
)
assert expect_printed_schema(schema) == dedent(
'''
"""Schema description."""
schema {
query: Query
}
type Query
'''
)
def prints_custom_query_root_types():
schema = GraphQLSchema(query=GraphQLObjectType("CustomType", {}))
assert expect_printed_schema(schema) == dedent(
"""
schema {
query: CustomType
}
type CustomType
"""
)
def prints_custom_mutation_root_types():
schema = GraphQLSchema(mutation=GraphQLObjectType("CustomType", {}))
assert expect_printed_schema(schema) == dedent(
"""
schema {
mutation: CustomType
}
type CustomType
"""
)
def prints_custom_subscription_root_types():
schema = GraphQLSchema(subscription=GraphQLObjectType("CustomType", {}))
assert expect_printed_schema(schema) == dedent(
"""
schema {
subscription: CustomType
}
type CustomType
"""
)
def prints_interface():
foo_type = GraphQLInterfaceType(
name="Foo", fields={"str": GraphQLField(GraphQLString)}
)
bar_type = GraphQLObjectType(
name="Bar",
fields={"str": GraphQLField(GraphQLString)},
interfaces=[foo_type],
)
schema = GraphQLSchema(types=[bar_type])
assert expect_printed_schema(schema) == dedent(
"""
type Bar implements Foo {
str: String
}
interface Foo {
str: String
}
"""
)
def prints_multiple_interfaces():
foo_type = GraphQLInterfaceType(
name="Foo", fields={"str": GraphQLField(GraphQLString)}
)
baz_type = GraphQLInterfaceType(
name="Baz", fields={"int": GraphQLField(GraphQLInt)}
)
bar_type = GraphQLObjectType(
name="Bar",
fields={
"str": GraphQLField(GraphQLString),
"int": GraphQLField(GraphQLInt),
},
interfaces=[foo_type, baz_type],
)
schema = GraphQLSchema(types=[bar_type])
assert expect_printed_schema(schema) == dedent(
"""
type Bar implements Foo & Baz {
str: String
int: Int
}
interface Foo {
str: String
}
interface Baz {
int: Int
}
"""
)
def prints_hierarchical_interface():
foo_type = GraphQLInterfaceType(
name="Foo", fields={"str": GraphQLField(GraphQLString)}
)
baz_type = GraphQLInterfaceType(
name="Baz",
interfaces=[foo_type],
fields={
"int": GraphQLField(GraphQLInt),
"str": GraphQLField(GraphQLString),
},
)
bar_type = GraphQLObjectType(
name="Bar",
fields={
"str": GraphQLField(GraphQLString),
"int": GraphQLField(GraphQLInt),
},
interfaces=[foo_type, baz_type],
)
query = GraphQLObjectType(name="Query", fields={"bar": GraphQLField(bar_type)})
schema = GraphQLSchema(query, types=[bar_type])
assert expect_printed_schema(schema) == dedent(
"""
type Bar implements Foo & Baz {
str: String
int: Int
}
interface Foo {
str: String
}
interface Baz implements Foo {
int: Int
str: String
}
type Query {
bar: Bar
}
"""
)
def prints_unions():
foo_type = GraphQLObjectType(
name="Foo", fields={"bool": GraphQLField(GraphQLBoolean)}
)
bar_type = GraphQLObjectType(
name="Bar", fields={"str": GraphQLField(GraphQLString)}
)
single_union = GraphQLUnionType(name="SingleUnion", types=[foo_type])
multiple_union = GraphQLUnionType(
name="MultipleUnion", types=[foo_type, bar_type]
)
schema = GraphQLSchema(types=[single_union, multiple_union])
assert expect_printed_schema(schema) == dedent(
"""
union SingleUnion = Foo
type Foo {
bool: Boolean
}
union MultipleUnion = Foo | Bar
type Bar {
str: String
}
"""
)
def prints_input_type():
input_type = GraphQLInputObjectType(
name="InputType", fields={"int": GraphQLInputField(GraphQLInt)}
)
schema = GraphQLSchema(types=[input_type])
assert expect_printed_schema(schema) == dedent(
"""
input InputType {
int: Int
}
"""
)
def prints_custom_scalar():
odd_type = GraphQLScalarType(name="Odd")
schema = GraphQLSchema(types=[odd_type])
assert expect_printed_schema(schema) == dedent(
"""
scalar Odd
"""
)
def prints_custom_scalar_with_specified_by_url():
foo_type = GraphQLScalarType(
name="Foo", specified_by_url="https://example.com/foo_spec"
)
schema = GraphQLSchema(types=[foo_type])
assert expect_printed_schema(schema) == dedent(
"""
scalar Foo @specifiedBy(url: "https://example.com/foo_spec")
"""
)
def prints_enum():
rgb_type = GraphQLEnumType(
name="RGB", values=dict.fromkeys(("RED", "GREEN", "BLUE"))
)
schema = GraphQLSchema(types=[rgb_type])
assert expect_printed_schema(schema) == dedent(
"""
enum RGB {
RED
GREEN
BLUE
}
"""
)
def prints_empty_types():
schema = GraphQLSchema(
types=[
GraphQLEnumType("SomeEnum", cast(Dict[str, Any], {})),
GraphQLInputObjectType("SomeInputObject", {}),
GraphQLInterfaceType("SomeInterface", {}),
GraphQLObjectType("SomeObject", {}),
GraphQLUnionType("SomeUnion", []),
]
)
assert expect_printed_schema(schema) == dedent(
"""
enum SomeEnum
input SomeInputObject
interface SomeInterface
type SomeObject
union SomeUnion
"""
)
def prints_custom_directives():
simple_directive = GraphQLDirective(
"simpleDirective", [DirectiveLocation.FIELD]
)
complex_directive = GraphQLDirective(
"complexDirective",
[DirectiveLocation.FIELD, DirectiveLocation.QUERY],
description="Complex Directive",
args={
"stringArg": GraphQLArgument(GraphQLString),
"intArg": GraphQLArgument(GraphQLInt, default_value=-1),
},
is_repeatable=True,
)
schema = GraphQLSchema(directives=[simple_directive, complex_directive])
assert expect_printed_schema(schema) == dedent(
'''
directive @simpleDirective on FIELD
"""Complex Directive"""
directive @complexDirective(stringArg: String, intArg: Int = -1) repeatable on FIELD | QUERY
''' # noqa: E501
)
def prints_an_empty_description():
schema = build_single_field_schema(GraphQLField(GraphQLString, description=""))
assert expect_printed_schema(schema) == dedent(
'''
type Query {
""""""
singleField: String
}
'''
)
def prints_a_description_with_only_whitespace():
schema = build_single_field_schema(GraphQLField(GraphQLString, description=" "))
assert expect_printed_schema(schema) == dedent(
"""
type Query {
" "
singleField: String
}
"""
)
def one_line_prints_a_short_description():
schema = build_single_field_schema(
GraphQLField(GraphQLString, description="This field is awesome")
)
assert expect_printed_schema(schema) == dedent(
'''
type Query {
"""This field is awesome"""
singleField: String
}
'''
)
def prints_introspection_schema():
schema = GraphQLSchema()
output = print_introspection_schema(schema)
assert output == dedent(
'''
"""
Directs the executor to include this field or fragment only when the `if` argument is true.
"""
directive @include(
"""Included when true."""
if: Boolean!
) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
"""
Directs the executor to skip this field or fragment when the `if` argument is true.
"""
directive @skip(
"""Skipped when true."""
if: Boolean!
) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
"""Marks an element of a GraphQL schema as no longer supported."""
directive @deprecated(
"""
Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).
"""
reason: String = "No longer supported"
) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | ENUM_VALUE
"""Exposes a URL that specifies the behaviour of this scalar."""
directive @specifiedBy(
"""The URL that specifies the behaviour of this scalar."""
url: String!
) on SCALAR
"""
A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.
"""
type __Schema {
description: String
"""A list of all types supported by this server."""
types: [__Type!]!
"""The type that query operations will be rooted at."""
queryType: __Type!
"""
If this server supports mutation, the type that mutation operations will be rooted at.
"""
mutationType: __Type
"""
If this server support subscription, the type that subscription operations will be rooted at.
"""
subscriptionType: __Type
"""A list of all directives supported by this server."""
directives: [__Directive!]!
}
"""
The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.
Depending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.
"""
type __Type {
kind: __TypeKind!
name: String
description: String
specifiedByURL: String
fields(includeDeprecated: Boolean = false): [__Field!]
interfaces: [__Type!]
possibleTypes: [__Type!]
enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
inputFields(includeDeprecated: Boolean = false): [__InputValue!]
ofType: __Type
}
"""An enum describing what kind of type a given `__Type` is."""
enum __TypeKind {
"""Indicates this type is a scalar."""
SCALAR
"""
Indicates this type is an object. `fields` and `interfaces` are valid fields.
"""
OBJECT
"""
Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.
"""
INTERFACE
"""Indicates this type is a union. `possibleTypes` is a valid field."""
UNION
"""Indicates this type is an enum. `enumValues` is a valid field."""
ENUM
"""
Indicates this type is an input object. `inputFields` is a valid field.
"""
INPUT_OBJECT
"""Indicates this type is a list. `ofType` is a valid field."""
LIST
"""Indicates this type is a non-null. `ofType` is a valid field."""
NON_NULL
}
"""
Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.
"""
type __Field {
name: String!
description: String
args(includeDeprecated: Boolean = false): [__InputValue!]!
type: __Type!
isDeprecated: Boolean!
deprecationReason: String
}
"""
Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.
"""
type __InputValue {
name: String!
description: String
type: __Type!
"""
A GraphQL-formatted string representing the default value for this input value.
"""
defaultValue: String
isDeprecated: Boolean!
deprecationReason: String
}
"""
One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.
"""
type __EnumValue {
name: String!
description: String
isDeprecated: Boolean!
deprecationReason: String
}
"""
A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.
"""
type __Directive {
name: String!
description: String
isRepeatable: Boolean!
locations: [__DirectiveLocation!]!
args(includeDeprecated: Boolean = false): [__InputValue!]!
}
"""
A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.
"""
enum __DirectiveLocation {
"""Location adjacent to a query operation."""
QUERY
"""Location adjacent to a mutation operation."""
MUTATION
"""Location adjacent to a subscription operation."""
SUBSCRIPTION
"""Location adjacent to a field."""
FIELD
"""Location adjacent to a fragment definition."""
FRAGMENT_DEFINITION
"""Location adjacent to a fragment spread."""
FRAGMENT_SPREAD
"""Location adjacent to an inline fragment."""
INLINE_FRAGMENT
"""Location adjacent to a variable definition."""
VARIABLE_DEFINITION
"""Location adjacent to a schema definition."""
SCHEMA
"""Location adjacent to a scalar definition."""
SCALAR
"""Location adjacent to an object type definition."""
OBJECT
"""Location adjacent to a field definition."""
FIELD_DEFINITION
"""Location adjacent to an argument definition."""
ARGUMENT_DEFINITION
"""Location adjacent to an interface definition."""
INTERFACE
"""Location adjacent to a union definition."""
UNION
"""Location adjacent to an enum definition."""
ENUM
"""Location adjacent to an enum value definition."""
ENUM_VALUE
"""Location adjacent to an input object type definition."""
INPUT_OBJECT
"""Location adjacent to an input object field definition."""
INPUT_FIELD_DEFINITION
}
''' # noqa: E501
)
def describe_print_value():
def print_value_convenience_function():
assert print_value(1.5, GraphQLFloat) == "1.5"
assert print_value("foo", GraphQLString) == '"foo"'
| mit |
balasankarc/ruby-active-model-serializers | test/test_app.rb | 391 | class TestApp < Rails::Application
if Rails.version.to_s.first >= '4'
config.eager_load = false
config.secret_key_base = 'abc123'
end
config.after_initialize do
Rails.application.routes.default_url_options = { host: 'http://example.com' }
end
# Set up a logger to avoid creating a log directory on every run.
config.logger = Logger.new(nil)
end
TestApp.initialize!
| mit |
FractalFlows/Emergence | app/imports/server/helpers/articles/indexToElastic.js | 766 | import { SimpleSchema } from 'meteor/aldeed:simple-schema'
import { Meteor } from 'meteor/meteor'
import { ELASTIC_SEARCH_INDEX, ELASTIC_SEARCH_TYPE } from '/imports/both/collections/articles'
import elasticSearch from '/imports/server/helpers/elasticSearch'
export default function indexArticleToElastic({ authors, title, abstract, DOI }){
new SimpleSchema({
authors: { type: [String] },
title: { type: String },
abstract: { type: String },
DOI: { type: String },
}).validate({ authors, title, abstract, DOI })
Meteor.defer(() => {
elasticSearch.index({
index: ELASTIC_SEARCH_INDEX,
type: ELASTIC_SEARCH_TYPE,
body: {
authors,
title,
abstract,
DOI,
},
})
})
return true
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/yui/3.7.3/yui-core/yui-core-coverage.js | 131 | version https://git-lfs.github.com/spec/v1
oid sha256:4a4207fa18ec066a5e81fd8da074200f3f1977988814346c68facec9ad6777af
size 310111
| mit |
bitunified/led-config | domain/src/main/java/com/bitunified/ledconfig/parts/Part.java | 3412 | package com.bitunified.ledconfig.parts;
import com.bitunified.ledconfig.domain.I18N.Locale;
import com.bitunified.ledconfig.domain.Model;
import com.bitunified.ledconfig.domain.Relation;
import com.bitunified.ledconfig.domain.modeltypes.RealModel;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.xml.bind.annotation.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
@XmlSeeAlso({NotExistingPart.class,Relatable.class})
public class Part extends Relatable implements Serializable {
private RealModel product;
private Model configModel;
private BigDecimal price;
private String description;
private String id;
private String type;
private Map<Locale,String> translations=new HashMap<Locale, String>();
public Part(Model configModel) {
this.configModel = configModel;
}
public Part(RealModel product) {
this.product = product;
}
private String imageUrl;
private String productPage;
public Part() {
}
public String getDescription() {
if ((description==null || description.isEmpty() ) && product!=null){
return product.getName();
}
return description;
}
public void setDescription(String description) {
this.description = description;
}
public RealModel getProduct() {
return product;
}
public void setProduct(RealModel product) {
this.product = product;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
public Model getConfigModel() {
return configModel;
}
public void setConfigModel(Model configModel) {
this.configModel = configModel;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Part part = (Part) o;
return id != null ? id.equals(part.id) : part.id == null;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Map<Locale, String> getTranslations() {
return translations;
}
public void setTranslations(Map<Locale, String> translations) {
this.translations = translations;
}
public void setTranslations(Locale locale, String s) {
translations.put(locale,s);
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = "assets/images/"+imageUrl;
}
public String getProductPage() {
return productPage;
}
public void setProductPage(String productPage) {
this.productPage = productPage;
}
}
| mit |
tdreid/Guezzmo | js/script.js | 1353 | window.onload = function() {
var theNumber = _.random(1, 100);
var theList = $('#list');
var theBanner = $('#triumph');
$('#submit').click(function() {
var theGuess = $('#guess').val();
$('#guess').val('');
if (theGuess == theNumber) {
$('#submit').prop('disabled', true);
$('#guess').prop('disabled', true);
theBanner.text(
"That's right! " + theGuess + ' is the number of which I am thinking.'
);
theBanner.append(
'<br /><button onClick="location.reload(true);" >Play again</button>'
);
} else if (theGuess < theNumber) {
theList.append(
'<li>' + getRandomPhrase() + theGuess + ' is too low.</li>'
);
} else {
theList.append(
'<li>' + getRandomPhrase() + theGuess + ' is too high</li>'
);
}
});
$('#guess').keyup(function(event) {
if (event.keyCode === 13) {
$('#submit').click();
}
});
function getRandomPhrase() {
var phrases = [
'No. ',
'Nope. ',
'Guess again. ',
'Give it another try. ',
"That's not it. ",
'Well, not quite. ',
'Okay. You can try again. ',
'No reason to give up now. ',
'Nah. ',
'Naw. ',
'I hope you get it next time. '
];
var index = _.random(0, phrases.length - 1);
return phrases[index];
}
};
| mit |
lexek/chat | src/main/java/lexek/wschat/chat/model/GlobalRole.java | 594 | package lexek.wschat.chat.model;
import lexek.wschat.chat.filters.BroadcastFilter;
import lexek.wschat.chat.filters.GlobalRoleFilter;
public enum GlobalRole {
UNAUTHENTICATED(300),
USER_UNCONFIRMED(30000),
USER(200),
MOD(0),
ADMIN(0),
SUPERADMIN(0);
public final BroadcastFilter<GlobalRole> FILTER = new GlobalRoleFilter(this);
private final int messageTimeInterval;
GlobalRole(int messageTimeInterval) {
this.messageTimeInterval = messageTimeInterval;
}
public int getMessageTimeInterval() {
return messageTimeInterval;
}
}
| mit |
awalker/sophrosyne-mvc | src/Base/NullView.php | 572 | <?php
namespace Base;
/**
* Sometimes helps with debugging
*/
class NullView extends View {
/**
* Returns a new view object for the given view.
*
* @param string $file the view file to load
* @param string $module name (blank for current theme)
*/
public function __construct($file, $values = null)
{
}
/**
* Set an array of values
*
* @param array $array of values
*/
public function set($array)
{
}
/**
* Return the view's HTML
*
* @return string
*/
public function __toString()
{
return '';
}
} | mit |
yogurtthewise/SpaceBucks | src/qt/locale/bitcoin_he.ts | 122615 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="he" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About SpaceBucks</source>
<translation>אודות ביטקוין</translation>
</message>
<message>
<location line="+39"/>
<source><b>SpaceBucks</b> version</source>
<translation>גרסת <b>ביטקוין</b></translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
זוהי תוכנה ניסיונית.
מופצת תחת רישיון התוכנה MIT/X11, ראה את הקובץ המצורף COPYING או http://www.opensource.org/licenses/mit-license.php.
המוצר הזה כולל תוכנה שפותחה ע"י פרויקט OpenSSL לשימוש בתיבת הכלים OpenSSL (http://www.openssl.org/) ותוכנה קריפטוגרפית שנכתבה ע"י אריק יאנג ([email protected]) ותוכנת UPnP שנכתבה ע"י תומס ברנרד.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>זכויות יוצרים</translation>
</message>
<message>
<location line="+0"/>
<source>The SpaceBucks developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>פנקס כתובות</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>לחץ לחיצה כפולה לערוך כתובת או תוית</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>יצירת כתובת חדשה</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>העתק את הכתובת המסומנת ללוח העריכה</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>כתובת חדשה</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your SpaceBucks addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>אלה כתובת הביטקוין שלך עבור קבלת תשלומים. ייתכן ותרצה לתת כתובת שונה לכל שולח כדי שתוכל לעקוב אחר מי משלם לך.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>העתק כתובת</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>הצג &קוד QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a SpaceBucks address</source>
<translation>חתום על הודעה בכדי להוכיח כי אתה הבעלים של כתובת ביטקוין.</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>חתום על הודעה</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>מחק את הכתובת שנבחרה מהרשימה</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>יצוא הנתונים בטאב הנוכחי לקובץ</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified SpaceBucks address</source>
<translation>אמת הודעה בכדי להבטיח שהיא נחתמה עם כתובת ביטקוין מסוימת.</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>אמת הודעה</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>מחק</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your SpaceBucks addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>אלה כתובת הביטקוין שלך עבור שליחת תשלומים. תמיד בדוק את מספר ואת כתובות מקבלי התשלומים לפני שליחת מטבעות.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>העתק תוית</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>עריכה</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>שלח מטבעות</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>יצוא נתוני פנקס כתובות</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>קובץ מופרד בפסיקים (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>שגיאה ביצוא</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>לא מסוגל לכתוב לקובץ %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>תוית</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>כתובת</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ללא תוית)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>שיח סיסמא</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>הכנס סיסמא</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>סיסמה חדשה</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>חזור על הסיסמה החדשה</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>הכנס את הסיסמה החדשה לארנק. <br/>אנא השתמש בסיסמה המכילה <b>10 תוים אקראיים או יותר</b>, או <b>שמונה מילים או יותר</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>הצפן ארנק</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>הפעולה הזו דורשת את סיסמת הארנק שלך בשביל לפתוח את הארנק.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>פתיחת ארנק</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>הפעולה הזו דורשת את סיסמת הארנק שלך בשביל לפענח את הארנק.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>פענוח ארנק</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>שינוי סיסמה</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>הכנס את הסיסמות הישנה והחדשה לארנק.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>אשר הצפנת ארנק</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>אזהרה: אם אתה מצפין את הארנק ומאבד את הסיסמא, אתה <b>תאבד את כל הביטקוינים שלך</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>האם אתה בטוח שברצונך להצפין את הארנק?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>חשוב! כל גיבוי קודם שעשית לארנק שלך יש להחליף עם קובץ הארנק המוצפן שזה עתה נוצר. מסיבות אבטחה, גיבויים קודמים של קובץ הארנק הלא-מוצפן יהפכו לחסרי שימוש ברגע שתתחיל להשתמש בארנק החדש המוצפן.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>זהירות: מקש Caps Lock מופעל!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>הארנק הוצפן</translation>
</message>
<message>
<location line="-56"/>
<source>SpaceBucks will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>ביטקוין ייסגר עכשיו כדי להשלים את תהליך ההצפנה. זכור שהצפנת הארנק שלך אינו יכול להגן באופן מלא על הביטקוינים שלך מתוכנות זדוניות המושתלות על המחשב.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>הצפנת הארנק נכשלה</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>הצפנת הארנק נכשלה עקב שגיאה פנימית. הארנק שלך לא הוצפן.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>הסיסמות שניתנו אינן תואמות.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>פתיחת הארנק נכשלה</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>הסיסמה שהוכנסה לפענוח הארנק שגויה.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>פענוח הארנק נכשל</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>סיסמת הארנק שונתה בהצלחה.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>חתום על הודעה</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>מסתנכרן עם הרשת...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&סקירה</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>הצג סקירה כללית של הארנק</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&פעולות</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>דפדף בהיסטוריית הפעולות</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>ערוך את רשימת הכתובות והתויות</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>הצג את רשימת הכתובות לקבלת תשלומים</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>י&ציאה</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>סגור תוכנה</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about SpaceBucks</source>
<translation>הצג מידע על ביטקוין</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>אודות Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>הצג מידע על Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&אפשרויות</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>הצפן ארנק</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>גיבוי ארנק</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>שנה סיסמא</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>מייבא בלוקים מהדיסק...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>מחדש את אינדקס הבלוקים בדיסק...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a SpaceBucks address</source>
<translation>שלח מטבעות לכתובת ביטקוין</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for SpaceBucks</source>
<translation>שנה אפשרויות תצורה עבור ביטקוין</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>גיבוי הארנק למקום אחר</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>שנה את הסיסמה להצפנת הארנק</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>חלון ניפוי</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>פתח את לוח הבקרה לאבחון וניפוי</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>אמת הודעה...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>SpaceBucks</source>
<translation>ביטקוין</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>ארנק</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>ושלח</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>וקבל</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>וכתובות</translation>
</message>
<message>
<location line="+22"/>
<source>&About SpaceBucks</source>
<translation>אודות ביטקוין</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>הצג / הסתר</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>הצג או הסתר את החלון הראשי</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>הצפן את המפתחות הפרטיים ששייכים לארנק שלך</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your SpaceBucks addresses to prove you own them</source>
<translation>חתום על הודעות עם כתובות הביטקוין שלך כדי להוכיח שהן בבעלותך</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified SpaceBucks addresses</source>
<translation>אמת הודעות כדי להבטיח שהן נחתמו עם כתובת ביטקוין מסוימות</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&קובץ</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>ה&גדרות</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&עזרה</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>סרגל כלים טאבים</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[רשת-בדיקה]</translation>
</message>
<message>
<location line="+47"/>
<source>SpaceBucks client</source>
<translation>תוכנת ביטקוין</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to SpaceBucks network</source>
<translation><numerusform>חיבור פעיל אחד לרשת הביטקוין</numerusform><numerusform>%n חיבורים פעילים לרשת הביטקוין</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>1% מתוך 2% (משוער) בלוקים של הסטוריית פעולת עובדו </translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>הושלם עיבוד של %1 בלוקים של היסטוריית פעולות.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n שעה</numerusform><numerusform>%n שעות</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n יום</numerusform><numerusform>%n ימים</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n שבוע</numerusform><numerusform>%n שבועות</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>1% מאחור</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>הבלוק האחרון שהתקבל נוצר לפני %1</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>לאחר זאת פעולות נספות טרם יהיו גלויות</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>שגיאה</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>אזהרה</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>מידע</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>פעולה זו חורגת מגבולות הגודל. עדיין באפשרותך לשלוח אותה תמורת עמלה של %1, המיועדת לצמתים שמעבדים את הפעולה שלך ועוזרת לתמוך ברשת. האם ברצונך לשלם את העמלה?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>עדכני</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>מתעדכן...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>אשר עמלת פעולה</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>פעולה שנשלחה</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>פעולה שהתקבלה</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>תאריך: %1
כמות: %2
סוג: %3
כתובת: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>תפעול URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid SpaceBucks address or malformed URI parameters.</source>
<translation>לא ניתן לנתח URI! זה יכול להיגרם כתוצאה מכתובת ביטקוין לא תקינה או פרמטרי URI חסרי צורה תקינה.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>הארנק <b>מוצפן</b> וכרגע <b>פתוח</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>הארנק <b>מוצפן</b> וכרגע <b>נעול</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. SpaceBucks can no longer continue safely and will quit.</source>
<translation>שגיאה סופנית אירעה. ביטקוין אינו יכול להמשיך לפעול בבטחה ולכן ייסגר.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>אזעקת רשת</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>ערוך כתובת</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>ת&וית</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>התוית המשויכת לרשומה הזו בפנקס הכתובות</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&כתובת</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>הכתובת המשויכת לרשומה זו בפנקס הכתובות. ניתן לשנות זאת רק עבור כתובות לשליחה.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>כתובת חדשה לקבלה</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>כתובת חדשה לשליחה</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>ערוך כתובת לקבלה</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>ערוך כתובת לשליחה</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>הכתובת שהכנסת "%1" כבר נמצאת בפנקס הכתובות.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid SpaceBucks address.</source>
<translation>הכתובת שהוכנסה "%1" אינה כתובת ביטקוין תקינה.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>פתיחת הארנק נכשלה.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>יצירת מפתח חדש נכשלה.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>SpaceBucks-Qt</source>
<translation>SpaceBucks-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>גרסה</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>שימוש:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>אפשרויות שורת פקודה</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>אפשרויות ממשק</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>קבע שפה, למשל "he_il" (ברירת מחדל: שפת המערכת)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>התחל ממוזער</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>הצג מסך פתיחה בעת הפעלה (ברירת מחדל: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>אפשרויות</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>ראשי</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>שלם &עמלת פעולה</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start SpaceBucks after logging in to the system.</source>
<translation>הפעל את ביטקוין באופן עצמאי לאחר התחברות למערכת.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start SpaceBucks on system login</source>
<translation>התחל את ביטקוין בעת התחברות למערכת</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>אפס כל אפשרויות התוכנה לברירת המחדל.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>איפוס אפשרויות</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>רשת</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the SpaceBucks client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>פתח את פורט ביטקוין בנתב באופן אוטומטי. עובד רק אם UPnP מאופשר ונתמך ע"י הנתב.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>מיפוי פורט באמצעות UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the SpaceBucks network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>התחבר לרשת הביטקוין דרך פרוקסי SOCKS (למשל בעת התחברות דרך Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>התחבר דרך פרוקסי SOCKS</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>כתובת IP של פרוקסי:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>כתובת האינטרנט של הפרוקסי (למשל 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>פורט:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>הפורט של הפרוקסי (למשל 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>גרסת SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>גרסת SOCKS של הפרוקסי (למשל 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>חלון</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>הצג סמל מגש בלבד לאחר מזעור החלון.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>מ&זער למגש במקום לשורת המשימות</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>מזער את התוכנה במקום לצאת ממנה כשהחלון נסגר. כשאפשרות זו פעילה, התוכנה תיסגר רק לאחר בחירת יציאה מהתפריט.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>מזער בעת סגירה</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>תצוגה</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>שפת ממשק המשתמש:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting SpaceBucks.</source>
<translation>ניתן לקבוע כאן את שפת ממשק המשתמש. הגדרה זו תחול לאחר הפעלה מחדש של ביטקוין.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>יחידת מדידה להצגת כמויות:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>בחר את ברירת המחדל ליחידת החלוקה אשר תוצג בממשק ובעת שליחת מטבעות.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show SpaceBucks addresses in the transaction list or not.</source>
<translation>האם להציג כתובות ביטקוין ברשימת הפעולות או לא.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>הצג כתובות ברשימת הפעולות</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>אישור</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>ביטול</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>יישום</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>ברירת מחדל</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>אשר את איפוס האפשרויות</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>כמה מההגדרות עשויות לדרוש אתחול התוכנה כדי להיכנס לפועל.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>האם ברצונך להמשיך?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>אזהרה</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting SpaceBucks.</source>
<translation>הגדרה זו תחול לאחר הפעלה מחדש של ביטקוין.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>כתובת הפרוקסי שסופקה אינה תקינה.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>טופס</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the SpaceBucks network after a connection is established, but this process has not completed yet.</source>
<translation>המידע המוצג עשוי להיות מיושן. הארנק שלך מסתנכרן באופן אוטומטי עם רשת הביטקוין לאחר כינון חיבור, אך התהליך טרם הסתיים.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>יתרה:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>ממתין לאישור:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>ארנק</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>לא בשל:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>מאזן שנכרה וטרם הבשיל</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>פעולות אחרונות</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>היתרה הנוכחית שלך</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>הסכום הכולל של פעולות שטרם אושרו, ועוד אינן נספרות בחישוב היתרה הנוכחית</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>לא מסונכרן</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start bitcoin: click-to-pay handler</source>
<translation>לא ניתן להתחיל את ביטקוין: מפעיל לחץ-לתשלום </translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>שיח קוד QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>בקש תשלום</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>כמות:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>תוית:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>הודעה:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&שמור בשם...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>שגיאה בקידוד URI לקוד QR</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>הכמות שהוכנסה אינה תקינה, אנא ודא.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>המזהה המתקבל ארוך מדי, נסה להפחית את הטקסט בתוית / הודעה.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>שמור קוד QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>תמונות PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>שם ממשק</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>גרסת ממשק</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>מידע</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>משתמש ב-OpenSSL גרסה</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>זמן אתחול</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>רשת</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>מספר חיבורים</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>ברשת הבדיקה</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>שרשרת הבלוקים</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>מספר הבלוקים הנוכחי</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>מספר כולל משוער של בלוקים</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>זמן הבלוק האחרון</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>פתח</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>אפשרויות שורת פקודה</translation>
</message>
<message>
<location line="+7"/>
<source>Show the SpaceBucks-Qt help message to get a list with possible SpaceBucks command-line options.</source>
<translation>הצג את הודעה העזרה של bitcoin-qt כדי לקבל רשימה של אפשרויות שורת פקודה של ביטקוין.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>הצג</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>לוח בקרה</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>תאריך בניה</translation>
</message>
<message>
<location line="-104"/>
<source>SpaceBucks - Debug window</source>
<translation>ביטקוין - חלון ניפוי</translation>
</message>
<message>
<location line="+25"/>
<source>SpaceBucks Core</source>
<translation>ליבת ביטקוין</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>קובץ יומן ניפוי</translation>
</message>
<message>
<location line="+7"/>
<source>Open the SpaceBucks debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>פתח את קובץ יומן הניפוי מתיקיית הנתונים הנוכחית. זה עשוי לקחת מספר שניות עבור קובצי יומן גדולים.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>נקה לוח בקרה</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the SpaceBucks RPC console.</source>
<translation>ברוכים הבאים ללוח בקרת RPC של ביטקוין</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>השתמש בחיצים למעלה ולמטה כדי לנווט בהיסטוריה, ו- <b>Ctrl-L</b> כדי לנקות את המסך.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>הקלד <b>help</b> בשביל סקירה של הפקודות הזמינות.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>שלח מטבעות</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>שלח למספר מקבלים בו-זמנית</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>הוסף מקבל</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>הסר את כל השדות בפעולה</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>נקה הכל</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>יתרה:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 ביטקוין</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>אשר את פעולת השליחה</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>שלח</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> ל- %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>אשר שליחת מטבעות</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>האם אתה בטוח שברצונך לשלוח %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> ו- </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>כתובת המקבל אינה תקינה, אנא בדוק שנית.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>הכמות לשלם חייבת להיות גדולה מ-0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>הכמות עולה על המאזן שלך.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>הכמות הכוללת, ובכללה עמלת פעולה בסך %1, עולה על המאזן שלך.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>כתובת כפולה נמצאה, ניתן לשלוח לכל כתובת רק פעם אחת בכל פעולת שליחה.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>שגיאה: יצירת הפעולה נכשלה!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>שגיאה: הפעולה נדחתה. זה עשוי לקרות עם חלק מהמטבעות בארנק שלך כבר נוצלו, למשל אם השתמשת בעותק של wallet.dat ומטבעות נוצלו בעותק אך לא סומנו כמנוצלות כאן.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>טופס</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>כ&מות:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>שלם &ל:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>הכתובת שאליה ישלח התשלום (למשל 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>הכנס תוית לכתובת הזאת כדי להכניס לפנקס הכתובות</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>ת&וית:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>בחר כתובת מפנקס הכתובות</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>הדבר כתובת מהלוח</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>הסר את המקבל הזה</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a SpaceBucks address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>הכנס כתובת ביטקוין (למשל 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>חתימות - חתום או אמת הודעה</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>חתום על הו&דעה</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>אתה יכול לחתום על הודעות עם הכתובות שלך כדי להוכיח שהן בבעלותך. היזהר לא לחתום על משהו מעורפל, שכן התקפות פישינג עשויות לגרום לך בעורמה למסור את זהותך. חתום רק על אמרות מפורטות לחלוטין שאתה מסכים עימן.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>הכתובת איתה לחתום על ההודעה (למשל 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>בחר כתובת מפנקס הכתובות</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>הדבק כתובת מהלוח</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>הכנס כאן את ההודעה שעליך ברצונך לחתום</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>חתימה</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>העתק את החתימה הנוכחית ללוח המערכת</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this SpaceBucks address</source>
<translation>חתום על ההודעה כדי להוכיח שכתובת הביטקוין הזו בבעלותך.</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>חתום על הודעה</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>אפס את כל שדות החתימה על הודעה</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>נקה הכל</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>אמת הודעה</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>הכנס למטה את הכתובת החותמת, ההודעה (ודא שאתה מעתיק מעברי שורה, רווחים, טאבים וכו' באופן מדויק) והחתימה כדי לאמת את ההודעה. היזהר לא לפרש את החתימה כיותר ממה שמופיע בהודעה החתומה בעצמה, כדי להימנע מליפול קורבן למתקפת איש-באמצע.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>הכתובת איתה ההודעה נחתמה (למשל 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified SpaceBucks address</source>
<translation>אמת את ההודעה כדי להבטיח שהיא נחתמה עם כתובת הביטקוין הנתונה</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>אימות הודעה</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>אפס את כל שדות אימות הודעה</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a SpaceBucks address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>הכנס כתובת ביטקוין (למשל 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>לחץ "חתום על ההודעה" כדי לחולל חתימה</translation>
</message>
<message>
<location line="+3"/>
<source>Enter SpaceBucks signature</source>
<translation>הכנס חתימת ביטקוין</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>הכתובת שהוכנסה אינה תקינה.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>אנא בדוק את הכתובת ונסה שנית.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>הכתובת שהוכנסה אינה מתייחסת למפתח.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>פתיחת הארנק בוטלה.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>המפתח הפרטי עבור הכתובת שהוכנסה אינו זמין.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>החתימה על ההודעה נכשלה.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>ההודעה נחתמה.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>לא ניתן לפענח את החתימה.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>אנא בדוק את החתימה ונסה שנית.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>החתימה לא תואמת את תקציר ההודעה.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>אימות ההודעה נכשל.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>ההודעה אומתה.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The SpaceBucks developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[רשת-בדיקה]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>פתוח עד %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/מנותק</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/ממתין לאישור</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 אישורים</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>מצב</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, הופץ דרך צומת אחד</numerusform><numerusform>, הופץ דרך %n צמתים</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>תאריך</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>מקור</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>נוצר</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>מאת</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>אל</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>כתובת עצמית</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>תוית</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>זיכוי</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>מבשיל בעוד בלוק אחד</numerusform><numerusform>מבשיל בעוד %n בלוקים</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>לא התקבל</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>חיוב</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>עמלת פעולה</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>כמות נקיה</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>הודעה</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>הערה</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>זיהוי פעולה</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>מטבעות שנוצרים חייבים להבשיל למשך 120 בלוקים לפני שניתן לנצל אותם. כשיצרת את הבלוק הזה, הוא הופץ לרשת כדי להתווסף לשרשרת הבלוקים. אם הוא אינו מצליח לביע לשרשרת, המצב שלו ישתנה ל"לא התקבל" ולא ניתן יהיה לנצל אותו. זה עשוי לקרות מעת לעת אם צומת אחר יוצר בלוק בטווח של מספר שניות מהבלוק שלך.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>מידע ניפוי</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>פעולה</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>קלטים</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>כמות</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>אמת</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>שקר</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, טרם שודר בהצלחה</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>פתח למשך בלוק %n יותר</numerusform><numerusform>פתח למשך %n בלוקים נוספים</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>לא ידוע</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>פרטי הפעולה</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>חלונית זו מציגה תיאור מפורט של הפעולה</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>תאריך</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>סוג</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>כתובת</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>כמות</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>פתח למשך בלוק %n יותר</numerusform><numerusform>פתח למשך %n בלוקים נוספים</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>פתוח עד %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>לא מחובר (%1 אישורים)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>ממתין לאישור (%1 מתוך %2 אישורים)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>מאושר (%1 אישורים)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>המאזן שנכרה יהיה זמין כשהוא מבשיל בעוד בלוק אחד</numerusform><numerusform>המאזן שנכרה יהיה זמין כשהוא מבשיל בעוד %n בלוקים</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>הבלוק הזה לא נקלט על ידי אף צומת אחר, וכנראה לא יתקבל!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>נוצר אך לא התקבל</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>התקבל עם</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>התקבל מאת</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>נשלח ל</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>תשלום לעצמך</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>נכרה</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>מצב הפעולה. השהה את הסמן מעל שדה זה כדי לראות את מספר האישורים.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>התאריך והשעה בה הפעולה הזאת התקבלה.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>סוג הפעולה.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>כתובת היעד של הפעולה.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>הכמות שהתווספה או הוסרה מהיתרה.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>הכל</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>היום</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>השבוע</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>החודש</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>החודש שעבר</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>השנה</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>טווח...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>התקבל עם</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>נשלח ל</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>לעצמך</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>נכרה</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>אחר</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>הכנס כתובת או תוית לחפש</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>כמות מזערית</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>העתק כתובת</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>העתק תוית</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>העתק כמות</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>העתק מזהה פעולה</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>ערוך תוית</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>הצג פרטי פעולה</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>יצוא נתוני פעולות</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>קובץ מופרד בפסיקים (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>מאושר</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>תאריך</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>סוג</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>תוית</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>כתובת</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>כמות</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>מזהה</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>שגיאה ביצוא</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>לא מסוגל לכתוב לקובץ %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>טווח:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>אל</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>שלח מטבעות</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>יצוא הנתונים בטאב הנוכחי לקובץ</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>גבה ארנק</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>נתוני ארנק (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>גיבוי נכשל</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>הייתה שגיאה בנסיון לשמור את המידע הארנק למיקום החדש.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>גיבוי הושלם בהצלחה</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>נתוני הארנק נשמרו בהצלחה במקום החדש.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>SpaceBucks version</source>
<translation>גרסת ביטקוין</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>שימוש:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or bitcoind</source>
<translation>שלח פקודה ל -server או bitcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>רשימת פקודות</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>קבל עזרה עבור פקודה</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>אפשרויות:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>ציין קובץ הגדרות (ברירת מחדל: bitcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation>ציין קובץ pid (ברירת מחדל: bitcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>ציין תיקיית נתונים</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>קבע את גודל המטמון של מסד הנתונים במגהבייט (ברירת מחדל: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>האזן לחיבורים ב<פורט> (ברירת מחדל: 8333 או ברשת הבדיקה: 18333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>החזק לכל היותר <n> חיבורים לעמיתים (ברירת מחדל: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>התחבר לצומת כדי לדלות כתובות עמיתים, ואז התנתק</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>ציין את הכתובת הפומבית שלך</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>סף להתנתקות מעמיתים הנוהגים שלא כהלכה (ברירת מחדל: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>מספר שניות למנוע מעמיתים הנוהגים שלא כהלכה מלהתחבר מחדש (ברירת מחדל: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>אירעה שגיאה בעת הגדרת פורט RPC %u להאזנה ב-IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation>האזן לחיבורי JSON-RPC ב- <port> (ברירת מחדל: 8332 או רשת בדיקה: 18332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>קבל פקודות משורת הפקודה ו- JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>רוץ ברקע כדימון וקבל פקודות</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>השתמש ברשת הבדיקה</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>קבל חיבורים מבחוץ (ברירת מחדל: 1 ללא -proxy או -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "SpaceBucks Alert" [email protected]
</source>
<translation>%s, עליך לקבוע סיסמת RPC בקובץ הקונפיגורציה:
%s
מומלץ להשתמש בסיסמא האקראית הבאה:
rpcuser=bitcoinrpc
rpcpassword=%s
(אין צורך לזכור את הסיסמה)
אסור ששם המשתמש והסיסמא יהיו זהים.
אם הקובץ אינו קיים, צור אותו עם הרשאות קריאה לבעלים בלבד.
זה מומלץ לסמן alertnotify כדי לקבל דיווח על תקלות;
למשל: alertnotify=echo %%s | mail -s "SpaceBucks Alert" [email protected]
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>אירעה שגיאה בעת הגדרת פורט RPC %u להאזנה ב-IPv6, נסוג ל-IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>קשור עם כתובת נתונה והאזן לה תמיד. השתמש בסימון [host]:port עבוד IPv6.</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. SpaceBucks is probably already running.</source>
<translation>לא מסוגל להשיג נעילה על תיקיית הנתונים %s. כנראה שביטקוין כבר רץ.</translation>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>שגיאה: הפעולה נדחתה! זה עלול לקרות אם כמה מהמטבעות בארנק שלך כבר נוצלו, למשל אם השתמשת בעותק של wallet.dat ומטבעות נשלחו בעותק אך לא סומנו כמנוצלות כאן.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>שגיאה: הפעולה הזאת דורשת עמלת פעולה של לפחות %s עקב הכמות, המורכבות, או השימוש בכספים שהתקבלו לאחרונה!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>בצע פעולה כאשר ההודעה הרלוונטית מתקבלת(%s בשורת הפקודה משתנה על-ידי ההודעה)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>בצע פקודה כאשר פעולת ארנק משתנה (%s ב cmd יוחלף ב TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>קבע גודל מקסימלי עבור פעולות עדיפות גבוהה/עמלה נמוכה בבתים (ברירת מחדל: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>זוהי בניית ניסיון טרום-שחרור - השימוש בה על אחריותך - אין להשתמש לצורך כריה או יישומי מסחר</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>אזהרה: -paytxfee נקבע לערך מאד גבוה! זוהי עמלת הפעולה שתשלם אם אתה שולח פעולה.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>אזהרה: הפעולות המוצגות עשויות לא להיות נכונות! ייתכן ואתה צריך לשדרג, או שצמתים אחרים צריכים לשדרג.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong SpaceBucks will not work properly.</source>
<translation>אזהרה: אנא בדוק שהתאריך והשעה של המחשב שלך נכונים! אם השעון שלך אינו נכון ביטקוין לא יעבוד כראוי.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>אזהרה: שגיאה בקריאת wallet.dat! כל המתפחות נקראו באופן תקין, אך נתוני הפעולות או ספר הכתובות עלולים להיות חסרים או שגויים.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>אזהרה: קובץ wallet.dat מושחת, המידע חולץ! קובץ wallet.dat המקורח נשמר כ - wallet.{timestamp}.bak ב - %s; אם המאזן או הפעולות שגויים עליך לשחזר גיבוי.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>נסה לשחזר מפתחות פרטיים מקובץ wallet.dat מושחת.</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>אפשרויות יצירת בלוק:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>התחבר רק לצמתים המצוינים</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>התגלה מסד נתוני בלוקים לא תקין</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>גלה את כתובת ה-IP העצמית (ברירת מחדל: 1 כשמאזינים וללא -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>האם תרצה כעט לבנות מחדש את מסד נתוני הבלוקים?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>שגיאה באתחול מסד נתוני הבלוקים</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>שגיאה באתחול סביבת מסד נתוני הארנקים %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>שגיאה בטעינת מסד נתוני הבלוקים</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>שגיאה בטעינת מסד נתוני הבלוקים</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>שגיאה: מעט מקום פנוי בדיסק!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>שגיאה: הארנק נעול, אין אפשרות ליצור פעולה!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>שגיאה: שגיאת מערכת:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>האזנה נכשלה בכל פורט. השתמש ב- -listen=0 אם ברצונך בכך.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>קריאת מידע הבלוקים נכשלה</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>קריאת הבלוק נכשלה</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>סנכרון אינדקס הבלוקים נכשל</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>כתיבת אינדקס הבלוקים נכשל</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>כתיבת מידע הבלוקים נכשל</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>כתיבת הבלוק נכשלה</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>כתיבת מידע הקבצים נכשלה</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>כתיבת מסד נתוני המטבעות נכשלה</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>כתיבת אינדקס הפעולות נכשלה</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>כתיבת נתוני ביטול נכשלה</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>מצא עמיתים ע"י חיפוש DNS (ברירת מחדל: 1 ללא -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>מספר הבלוקים לבדוק בעת אתחול (ברירת מחדל: 288, 0 = כולם)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>מידת היסודיות של אימות הבלוקים (0-4, ברירת מחדל: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>בנה מחדש את אינדק שרשרת הבלוקים מקבצי ה-blk000??.dat הנוכחיים.</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>קבע את מספר תהליכוני לשירות קריאות RPC (ברירת מחדל: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>מאמת את שלמות מסד הנתונים...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>מאמת את יושרת הארנק...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>מייבא בלוקים מקובצי blk000??.dat חיצוניים</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>מידע</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>כתובת לא תקינה ל -tor: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>תחזק אינדקס פעולות מלא (ברירת מחדל: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>חוצץ קבלה מירבי לכל חיבור, <n>*1000 בתים (ברירת מחדל: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>חוצץ שליחה מירבי לכל חיבור, <n>*1000 בתים (ברירת מחדל: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>קבל רק שרשרת בלוקים התואמת נקודות ביקורת מובנות (ברירת מחדל: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>התחבר רק לצמתים ברשת <net> (IPv4, IPv6 או Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>פלוט מידע ניפוי נוסף. נובע מכך כל אפשרויות -debug* האחרות.</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>פלוט מידע נוסף לניפוי שגיאות ברשת.</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>הוסף חותמת זמן לפני פלט דיבאג</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the SpaceBucks Wiki for SSL setup instructions)</source>
<translation>אפשרויות SSL: (ראה את הויקי של ביטקוין עבור הוראות הגדרת SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>בחר את גרסת פרוקסי SOCKS להשתמש בה (4-5, ברירת מחדל: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>שלח מידע דיבאג ועקבה לקונסולה במקום לקובץ debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>שלח מידע דיבאג ועקבה לכלי דיבאג</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>קבע את גדול הבלוק המירבי בבתים (ברירת מחדל: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>קבע את גודל הבלוק המינימלי בבתים (ברירת מחדל: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>כווץ את קובץ debug.log בהפעלת הקליינט (ברירת מחדל: 1 ללא -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>ציין הגבלת זמן לחיבור במילישניות (ברירת מחדל: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>שגיאת מערכת:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>השתמש ב-UPnP כדי למפות את הפורט להאזנה (ברירת מחדל: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>השתמש ב-UPnP כדי למפות את הפורט להאזנה (ברירת מחדל: 1 בעת האזנה)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>השתמש בפרוקסי כדי להגיע לשירותים חבויים ב-tor (ברירת מחדל: כמו ב- -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>שם משתמש לחיבורי JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>אזהרה</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>אזהרה: הגרסה הזאת מיושנת, יש צורך בשדרוג!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>עליך לבנות מחדש את מסדי הנתונים תוך שימוש ב- -reindex על מנת לשנות את -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>קובץ wallet.dat מושחת, החילוץ נכשל</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>סיסמה לחיבורי JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>אפשר חיבורי JSON-RPC מכתובת האינטרנט המצוינת</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>שלח פקודות לצומת ב-<ip> (ברירת מחדל: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>בצע פקודה זו כשהבלוק הטוב ביותר משתנה (%s בפקודה יוחלף בגיבוב הבלוק)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>שדרג את הארנק לפורמט העדכני</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>קבע את גודל המאגר ל -<n> (ברירת מחדל: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>סרוק מחדש את שרשרת הבלוקים למציאת פעולות חסרות בארנק</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>השתמש ב-OpenSSL (https( עבור חיבורי JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>קובץ תעודת שרת (ברירת מחדל: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>מפתח פרטי של השרת (ברירת מחדל: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>צפנים קבילים (ברירת מחדל: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>הודעת העזרה הזו</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>לא מסוגל לקשור ל-%s במחשב זה (הקשירה החזירה שגיאה %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>התחבר דרך פרוקסי SOCKS</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>אפשר בדיקת DNS עבור -addnode, -seednode ו- -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>טוען כתובות...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>שגיאה בטעינת הקובץ wallet.dat: הארנק מושחת</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of SpaceBucks</source>
<translation>שגיאה בטעינת הקובץ wallet.dat: הארנק דורש גרסה חדשה יותר של ביטקוין</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart SpaceBucks to complete</source>
<translation>יש לכתוב מחדש את הארנק: אתחל את ביטקוין לסיום</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>שגיאה בטעינת הקובץ wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>כתובת -proxy לא תקינה: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>רשת לא ידועה צוינה ב- -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>התבקשה גרסת פרוקסי -socks לא ידועה: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>לא מסוגל לפתור כתובת -bind: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>לא מסוגל לפתור כתובת -externalip: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>כמות לא תקינה עבור -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>כמות לא תקינה</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>אין מספיק כספים</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>טוען את אינדקס הבלוקים...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>הוסף צומת להתחברות ונסה לשמור את החיבור פתוח</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. SpaceBucks is probably already running.</source>
<translation>לא ניתן לקשור ל-%s במחשב זה. ביטקוין כנראה עדיין רץ.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>עמלה להוסיף לפעולות שאתה שולח עבור כל KB</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>טוען ארנק...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>לא יכול להוריד דרגת הארנק</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>לא יכול לכתוב את כתובת ברירת המחדל</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>סורק מחדש...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>טעינה הושלמה</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>להשתמש באפשרות %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>שגיאה</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>עליך לקבוע rpcpassword=yourpassword בקובץ ההגדרות:
%s
אם הקובץ אינו קיים, צור אותו עם הרשאות קריאה לבעלים בלבד.</translation>
</message>
</context>
</TS> | mit |
efreet929/html-dom-parser | example-ariya2.js | 780 | var page = require('webpage').create();
page.settings.userAgent = 'WebKit/534.46 Mobile/9A405 Safari/7534.48.3';
page.settings.viewportSize = { width: 400, height: 600 };
page.onResourceRequested = function(requestData, request) {
if ((/http:\/\/.+?\.css$/gi).test(requestData['url'])) {
console.log('Skipping', requestData['url']);
request.abort();
}
};
page.open('http://m.bbc.co.uk/news/health', function (status) {
if (status !== 'success') {
console.log('Unable to load BBC!');
phantom.exit();
} else {
window.setTimeout(function () {
page.clipRect = { left: 0, top: 0, width: 400, height: 600 };
page.render('bbc_unstyled.png');
phantom.exit();
}, 1000);
}
}); | mit |
dkrock24/lapizzeria | class_db/forms.php | 3278 |
<?php
session_start();
include_once("../validation/conexion.php");
$conexion = login();
$action = $_POST['action'];
switch ($action) {
case 'selectPartidasGenericas':tipoForm();
break;
case 'InsertPartidaGenerica':InsertPartidaGenerica();
break;
case 'insert_marginacion':insert_marginacion();
break;
case 'UpdatePartidaGenerica':UpdatePartidaGenerica();
break;
}
//if(isset($action)){
// tipoForm($_POST['valor']);
//}
function tipoForm()
{
$id = $_POST['valor'] ;
$sql = "select file from sr_generar_partidas where id_generar ='".$id."'";
$statement = mysql_query($sql)or die(mysql_error(). " Erro al cargar los menus");
$row = array();
$row = mysql_fetch_array($statement);
echo json_encode($row);
}
function InsertPartidaGenerica(){
$usuario = $_POST['usuario'];
$tipoPartida = $_POST['tipoPartida'];
$tipo = $_POST['tipo'];
$numeroLibro= $_POST['numeroLibro'];
$tipoDcoumento = $_POST['tipoDcoumento'];
$numeroFL = $_POST['numeroFL'];
$nombre1 = $_POST['nombre1'] ;
if(isset($_POST['nombre2'])){
$nombre2 = $_POST['nombre2'];
}else{
$nombre2 = "";
}
$fecha_general = $_POST['fecha_general'];
$detalle = $_POST['detalle'];
$id="";
$fecha = date("Y-m-d");
$sql = "insert into sr_partidas_generales (id_usuario,id_tipo,nombre1,nombre2,fecha,pagina,numero_pagina,numero_libro,detalle,fecha_ingreso)values(
'$usuario','$tipoPartida','$nombre1','$nombre2','$fecha_general','$tipoDcoumento',
'$numeroFL','$numeroLibro','$detalle','$fecha')";
mysql_query($sql)or die(mysql_error()."Error al insertar partida Generecia");
$rs = mysql_query("SELECT @@identity AS id");
if ($row = mysql_fetch_row($rs))
{
$ultimo_id = trim($row[0]);
}
echo json_encode($row);
}
function insert_marginacion(){
$id_partida = $_POST['id_partida'];
$id_tipo = $_POST['id_tipo'];
$id_usuario = $_POST['id_usuario'];
$marginacion = $_POST['marginacion'];
$fecha = date("Y-m-d");
$sql = "insert into sr_marginaciones_generales (id_tipo_partida,id_partida,id_usuario,texto_marginacion,fecha_marginacion)values(
'$id_tipo','$id_partida','$id_usuario','$marginacion','$fecha'
)";
mysql_query($sql)or die(mysql_error());
}
function UpdatePartidaGenerica()
{
$tipoPartida = $_POST['tipoPartida1'];
$tipo = $_POST['tipo1'];
echo $numeroLibro= $_POST['numeroLibro1'];
$tipoDcoumento = $_POST['tipoDcoumento1'];
$numeroFL = $_POST['numeroFL1'];
$nombre1 = $_POST['nombre11'] ;
if(isset($_POST['nombre21'])){
$nombre2 = $_POST['nombre21'];
}else{
$nombre2 = "";
}
$id_partida = $_POST['id_partida1'];
$fecha_general = $_POST['fecha_general1'];
$detalle = $_POST['detalle1'];
$sql = "update sr_partidas_generales set id_tipo='$tipo', nombre1='$nombre1', nombre2='$nombre2'
, fecha='$fecha_general', pagina='$tipoDcoumento', numero_pagina='$numeroFL',
numero_libro='$numeroLibro',detalle='$detalle' where id_partida='$id_partida'";
mysql_query($sql)or die(mysql_error());
} | mit |
pubnative/pubnative-android-mediation-sdk | sdk/src/main/java/net/pubnative/sdk/core/request/PNRequestCache.java | 2497 | // The MIT License (MIT)
//
// Copyright (c) 2017 PubNative GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package net.pubnative.sdk.core.request;
import net.pubnative.sdk.core.adapter.request.PNAdapter;
import net.pubnative.sdk.core.config.model.PNNetworkModel;
import java.util.HashMap;
import java.util.Map;
public class PNRequestCache extends PNRequest {
@Override
protected int getRequestTimeout(PNNetworkModel network) {
int result = 0;
if (network != null) {
result = network.getAdCacheTimeout();
}
return result;
}
@Override
protected boolean canUseCache(PNNetworkModel network) {
// Ensure to return false so we never use cached ads when requesting for caching
return false;
}
@Override
protected void sendRequestInsight() {
Map<String, String> extras = new HashMap<String, String>();
extras.put("fetchAssets", "1");
mInsight.sendRequestInsight(extras);
}
@Override
protected void cache() {
// Do nothing, avoid from fetchAssets when failed/finished
}
@Override
protected void request(PNAdapter adapter, PNNetworkModel network, Map extras) {
if (network.isAdCacheEnabled()) {
// If the network allows ad fetchAssets, then we continue, otherwise we skip this
super.request(adapter, network, extras);
} else {
getNextNetwork();
}
}
}
| mit |
ProframFiles/FancyDraw | src/akjColor.hpp | 6707 | #pragma once
#include "akj_typedefs.hpp"
#include "FancyDrawMath.hpp"
#include <unordered_map>
#include <vector>
#include <string>
#include "akjRandom.hpp"
#include <cmath>
namespace akj{
inline float LinearToSRGB(float input)
{
if(input >= 0.0031308f)
{
return 1.055f*std::pow(input, 0.416666f)-0.055f;
}
return 12.92f*input;
}
class cWebColor
{
public:
enum eWebColor {
ALICEBLUE = 0XF0F8FF,
ANTIQUEWHITE = 0XFAEBD7,
AQUA = 0X00FFFF,
AQUAMARINE = 0X7FFFD4,
AZURE = 0XF0FFFF,
BEIGE = 0XF5F5DC,
BISQUE = 0XFFE4C4,
BLACK = 0X000000,
BLANCHEDALMOND = 0XFFEBCD,
BLUE = 0X0000FF,
BLUEVIOLET = 0X8A2BE2,
BROWN = 0XA52A2A,
BURLYWOOD = 0XDEB887,
CADETBLUE = 0X5F9EA0,
CHARTREUSE = 0X7FFF00,
CHOCOLATE = 0XD2691E,
CORAL = 0XFF7F50,
CORNFLOWERBLUE = 0X6495ED,
CORNSILK = 0XFFF8DC,
CRIMSON = 0XDC143C,
CYAN = 0X00FFFF,
DARKBLUE = 0X00008B,
DARKCYAN = 0X008B8B,
DARKGOLDENROD = 0XB8860B,
DARKGRAY = 0XA9A9A9,
DARKGREY = 0XA9A9A9,
DARKGREEN = 0X006400,
DARKKHAKI = 0XBDB76B,
DARKMAGENTA = 0X8B008B,
DARKOLIVEGREEN = 0X556B2F,
DARKORANGE = 0XFF8C00,
DARKORCHID = 0X9932CC,
DARKRED = 0X8B0000,
DARKSALMON = 0XE9967A,
DARKSEAGREEN = 0X8FBC8F,
DARKSLATEBLUE = 0X483D8B,
DARKSLATEGRAY = 0X2F4F4F,
DARKSLATEGREY = 0X2F4F4F,
DARKTURQUOISE = 0X00CED1,
DARKVIOLET = 0X9400D3,
DEEPPINK = 0XFF1493,
DEEPSKYBLUE = 0X00BFFF,
DIMGRAY = 0X696969,
DIMGREY = 0X696969,
DODGERBLUE = 0X1E90FF,
FIREBRICK = 0XB22222,
FLORALWHITE = 0XFFFAF0,
FORESTGREEN = 0X228B22,
FUCHSIA = 0XFF00FF,
GAINSBORO = 0XDCDCDC,
GHOSTWHITE = 0XF8F8FF,
GOLD = 0XFFD700,
GOLDENROD = 0XDAA520,
GRAY = 0X808080,
GREY = 0X808080,
GREEN = 0X00FF00,
GREENYELLOW = 0XADFF2F,
HONEYDEW = 0XF0FFF0,
HOTPINK = 0XFF69B4,
INDIANRED = 0XCD5C5C,
INDIGO = 0X4B0082,
IVORY = 0XFFFFF0,
KHAKI = 0XF0E68C,
LAVENDER = 0XE6E6FA,
LAVENDERBLUSH = 0XFFF0F5,
LAWNGREEN = 0X7CFC00,
LEAFGREEN = 0x008000,
LEMONCHIFFON = 0XFFFACD,
LIGHTBLUE = 0XADD8E6,
LIGHTCORAL = 0XF08080,
LIGHTCYAN = 0XE0FFFF,
LIGHTGOLDENRODYELLOW = 0XFAFAD2,
LIGHTGRAY = 0XD3D3D3,
LIGHTGREY = 0XD3D3D3,
LIGHTGREEN = 0X90EE90,
LIGHTPINK = 0XFFB6C1,
LIGHTSALMON = 0XFFA07A,
LIGHTSEAGREEN = 0X20B2AA,
LIGHTSKYBLUE = 0X87CEFA,
LIGHTSLATEGRAY = 0X778899,
LIGHTSLATEGREY = 0X778899,
LIGHTSTEELBLUE = 0XB0C4DE,
LIGHTYELLOW = 0XFFFFE0,
LIME = 0X00FF00,
LIMEGREEN = 0X32CD32,
LINEN = 0XFAF0E6,
MAGENTA = 0XFF00FF,
MAROON = 0X800000,
MEDIUMAQUAMARINE = 0X66CDAA,
MEDIUMBLUE = 0X0000CD,
MEDIUMORCHID = 0XBA55D3,
MEDIUMPURPLE = 0X9370D8,
MEDIUMSEAGREEN = 0X3CB371,
MEDIUMSLATEBLUE = 0X7B68EE,
MEDIUMSPRINGGREEN = 0X00FA9A,
MEDIUMTURQUOISE = 0X48D1CC,
MEDIUMVIOLETRED = 0XC71585,
MIDNIGHTBLUE = 0X191970,
MINTCREAM = 0XF5FFFA,
MISTYROSE = 0XFFE4E1,
MOCCASIN = 0XFFE4B5,
NAVAJOWHITE = 0XFFDEAD,
NAVY = 0X000080,
OLDLACE = 0XFDF5E6,
OLIVE = 0X808000,
OLIVEDRAB = 0X6B8E23,
ORANGE = 0XFFA500,
ORANGERED = 0XFF4500,
ORCHID = 0XDA70D6,
PALEGOLDENROD = 0XEEE8AA,
PALEGREEN = 0X98FB98,
PALETURQUOISE = 0XAFEEEE,
PALEVIOLETRED = 0XD87093,
PAPAYAWHIP = 0XFFEFD5,
PEACHPUFF = 0XFFDAB9,
PERU = 0XCD853F,
PINK = 0XFFC0CB,
PLUM = 0XDDA0DD,
POWDERBLUE = 0XB0E0E6,
PURPLE = 0X800080,
RED = 0XFF0000,
ROSYBROWN = 0XBC8F8F,
ROYALBLUE = 0X4169E1,
SADDLEBROWN = 0X8B4513,
SALMON = 0XFA8072,
SANDYBROWN = 0XF4A460,
SEAGREEN = 0X2E8B57,
SEASHELL = 0XFFF5EE,
SIENNA = 0XA0522D,
SILVER = 0XC0C0C0,
SKYBLUE = 0X87CEEB,
SLATEBLUE = 0X6A5ACD,
SLATEGRAY = 0X708090,
SLATEGREY = 0X708090,
SNOW = 0XFFFAFA,
SPRINGGREEN = 0X00FF7F,
STEELBLUE = 0X4682B4,
TAN = 0XD2B48C,
TEAL = 0X008080,
THISTLE = 0XD8BFD8,
TOMATO = 0XFF6347,
TURQUOISE = 0X40E0D0,
VIOLET = 0XEE82EE,
WHEAT = 0XF5DEB3,
WHITE = 0XFFFFFF,
WHITESMOKE = 0XF5F5F5,
YELLOW = 0XFFFF00,
YELLOWGREEN = 0X9ACD32
};
static cWebColor::eWebColor Random();
static std::string ToString(cWebColor::eWebColor enum_in);
private:
static void ToLower(std::string& s);
static std::pair<std::string, cWebColor::eWebColor>
colorPair(const char* s_in, cWebColor::eWebColor code);
class cColorTable
{
public:
cColorTable();
~cColorTable(){};
std::unordered_map<std::string, cWebColor::eWebColor > colors;
std::unordered_map<uint32_t, std::string > names;
std::unordered_map<cWebColor::eWebColor, uint32_t > colorsFromEnum;
std::vector<cWebColor::eWebColor> flatVec;
std::vector<uint32_t> redVec;
std::vector<uint32_t> greenVec;
std::vector<uint32_t> blueVec;
uint32_t size;
};
static cColorTable sColorTable;
static cRandom mRNG;
};
struct RGBAu8;
struct RGBAf
{
RGBAf(float in_r, float in_g, float in_b, float in_a)
: r(in_r), g(in_g), b(in_b), a(in_a)
{}
RGBAf()
: r(1.0f), g(0.0f), b(1.0f), a(1.0f)
{}
RGBAf(const RGBAu8& color);
RGBAf(cWebColor::eWebColor color);
float r, g, b, a;
};
struct RGBAu8
{
RGBAu8()
: r(255), g(0), b(255), a(255)
{}
RGBAu8(uint8_t in_r, uint8_t in_g, uint8_t in_b, uint8_t in_a)
: r(in_r), g(in_g), b(in_b), a(in_a)
{}
RGBAu8(uint8_t in_r, uint8_t in_g, uint8_t in_b)
: r(in_r), g(in_g), b(in_b), a(255)
{}
RGBAu8(uint32_t hex_in)
: r(static_cast<uint8_t>((0xFF000000 & hex_in) >> 24))
, g(static_cast<uint8_t>((0x00FF0000 & hex_in) >> 16))
, b(static_cast<uint8_t>((0x0000FF00 & hex_in) >> 8))
, a(static_cast<uint8_t>((0xFF & hex_in)))
{}
explicit RGBAu8(const RGBAf& color)
: r(static_cast<uint8_t>(255.999f*Clamp(0.0f, color.r, 1.0f)))
, g(static_cast<uint8_t>(255.999f*Clamp(0.0f, color.g, 1.0f)))
, b(static_cast<uint8_t>(255.999f*Clamp(0.0f, color.b, 1.0f)))
, a(static_cast<uint8_t>(255.999f*Clamp(0.0f, color.a, 1.0f)))
{}
RGBAu8(cWebColor::eWebColor color)
: a(255)
, b(static_cast<uint8_t>(0x0000FF & color))
, g(static_cast<uint8_t>((0x00FF00 & color) >> 8))
, r(static_cast<uint8_t>((0xFF0000 & color) >> 16))
{}
RGBAu8 Alpha(uint8_t alpha)
{
RGBAu8 ret = *this;
ret.a = alpha;
return ret;
}
uint32_t AsUInt() const
{
return *reinterpret_cast<const uint32_t*>(this);
}
uint8_t r, g, b, a;
};
//compiler error on wrong size
typedef char cRGBASIZE[(sizeof(RGBAu8) == 4)];
inline RGBAf::RGBAf(const RGBAu8& color)
: r(color.r*0.003922f)
, g(color.g*0.003922f)
, b(color.b*0.003922f)
, a(color.a*0.003922f)
{}
inline RGBAf::RGBAf(cWebColor::eWebColor color)
{
*this = RGBAf(RGBAu8(color));
}
} //namespace akj
| mit |
SonarSource-VisualStudio/sonarlint-visualstudio | src/Core/SonarCompositeRuleId.cs | 2336 | /*
* SonarLint for Visual Studio
* Copyright (C) 2016-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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.
*/
using System;
namespace SonarLint.VisualStudio.Core
{
public class SonarCompositeRuleId
{
private const string Separator = ":";
/// <summary>
/// Attempts to parse an error code from the VS Error List as a Sonar rule in the form "[repo key]:[rule key]"
/// </summary>
public static bool TryParse(string errorListErrorCode, out SonarCompositeRuleId ruleInfo)
{
ruleInfo = null;
if (!string.IsNullOrEmpty(errorListErrorCode))
{
var keys = errorListErrorCode.Split(new string[] {Separator}, StringSplitOptions.RemoveEmptyEntries);
if (keys.Length == 2)
{
ruleInfo = new SonarCompositeRuleId(errorListErrorCode, keys[0], keys[1]);
}
}
return ruleInfo != null;
}
private SonarCompositeRuleId(string errorListErrorCode, string repoKey, string ruleKey)
{
ErrorListErrorCode = errorListErrorCode ?? throw new ArgumentNullException(nameof(errorListErrorCode));
RepoKey = repoKey ?? throw new ArgumentNullException(nameof(repoKey));
RuleKey = ruleKey ?? throw new ArgumentNullException(nameof(ruleKey));
}
public string ErrorListErrorCode { get; }
public string RepoKey { get; }
public string RuleKey { get; }
public override string ToString() => ErrorListErrorCode;
}
}
| mit |
abhishek-kharche/BaithakAttendance | update_user.php | 1275 | <?php
@session_start();
if(!isset($_COOKIE['loggedin'])){
header("location:index.php");
}
require_once('Auth.php');
$authObject = new Auth();
# send all values from js
$first = $_POST['first_name'];
$middle = $_POST['middle_name'];
$last = $_POST['last_name'];
$uid = $_POST['user_id'];
$isRel = $_POST['isRel'];
if($isRel == "0") {
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$emailId = $_POST['emailId'];
$pwd = $_POST['passWord'];
$type = $_POST['userType'];
$result = $authObject->updateUser($first, $middle, $last, $city, $state, $country, $emailId, $pwd, intval($type), intval($uid));
# $result will contain true or false, if emailid and pwd is set then this will update user_auth too
$results = array();
while($row = mysql_fetch_assoc($result)) {
array_push($results, $row);
}
echo json_encode($results);
//echo $result_val;
}else{
$rel = $_POST['relation'];
$result = $authObject->updateRelation($first, $middle, $last, $rel, intval($uid));
# $result will contain true or false
$results = array();
while($row = mysql_fetch_assoc($result)) {
array_push($results, $row);
}
echo json_encode($results);
//echo $result_val;
}
?> | mit |
aliaksei-kavaliou/aventus-test-task | src/AppBundle/Entity/LoanPayment.php | 3459 | <?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* LoadScheduler
*
* @ORM\Table(name="load_scheduler")
* @ORM\Entity(repositoryClass="AppBundle\Repository\LoadSchedulerRepository")
*/
class LoanPayment
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var \DateTime
*
* @ORM\Column(name="payment_date", type="date")
*/
private $paymentDate;
/**
* @var float
*
* @ORM\Column(name="main_debt", type="float")
*/
private $mainDebt;
/**
* @var float
*
* @ORM\Column(name="interest", type="float")
*/
private $interest;
/**
* @var float
*
* @ORM\Column(name="payment", type="float")
*/
private $payment;
/**
* @var float
*
* @ORM\Column(name="remain", type="float")
*/
private $remain;
/**
*
* @var Loan
* @ORM\ManyToOne(targetEntity="Loan", inversedBy="payments")
*/
private $loan;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set paymentDate
*
* @param \DateTime $paymentDate
*
* @return LoanPayment
*/
public function setPaymentDate($paymentDate)
{
$this->paymentDate = $paymentDate;
return $this;
}
/**
* Get paymentDate
*
* @return \DateTime
*/
public function getPaymentDate()
{
return $this->paymentDate;
}
/**
* Set mainDebt
*
* @param float $mainDebt
*
* @return LoanPayment
*/
public function setMainDebt($mainDebt)
{
$this->mainDebt = $mainDebt;
return $this;
}
/**
* Get mainDebt
*
* @return float
*/
public function getMainDebt()
{
return $this->mainDebt;
}
/**
* Set interest
*
* @param float $interest
*
* @return LoanPayment
*/
public function setInterest($interest)
{
$this->interest = $interest;
return $this;
}
/**
* Get interest
*
* @return float
*/
public function getInterest()
{
return $this->interest;
}
/**
* Set payment
*
* @param float $payment
*
* @return LoanPayment
*/
public function setPayment($payment)
{
$this->payment = $payment;
return $this;
}
/**
* Get payment
*
* @return float
*/
public function getPayment()
{
return $this->payment;
}
/**
* Set remain
*
* @param float $remain
*
* @return LoanPayment
*/
public function setRemain($remain)
{
$this->remain = $remain;
return $this;
}
/**
* Get remain
*
* @return float
*/
public function getRemain()
{
return $this->remain;
}
/**
* Set loan
*
* @param \AppBundle\Entity\Loan $loan
*
* @return LoanPayment
*/
public function setLoan(\AppBundle\Entity\Loan $loan = null)
{
$this->loan = $loan;
return $this;
}
/**
* Get loan
*
* @return \AppBundle\Entity\Loan
*/
public function getLoan()
{
return $this->loan;
}
}
| mit |
LightningNetwork/lnd | sweep/store_mock.go | 1465 | package sweep
import (
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
)
// MockSweeperStore is a mock implementation of sweeper store. This type is
// exported, because it is currently used in nursery tests too.
type MockSweeperStore struct {
lastTx *wire.MsgTx
ourTxes map[chainhash.Hash]struct{}
}
// NewMockSweeperStore returns a new instance.
func NewMockSweeperStore() *MockSweeperStore {
return &MockSweeperStore{
ourTxes: make(map[chainhash.Hash]struct{}),
}
}
// IsOurTx determines whether a tx is published by us, based on its
// hash.
func (s *MockSweeperStore) IsOurTx(hash chainhash.Hash) (bool, error) {
_, ok := s.ourTxes[hash]
return ok, nil
}
// NotifyPublishTx signals that we are about to publish a tx.
func (s *MockSweeperStore) NotifyPublishTx(tx *wire.MsgTx) error {
txHash := tx.TxHash()
s.ourTxes[txHash] = struct{}{}
s.lastTx = tx
return nil
}
// GetLastPublishedTx returns the last tx that we called NotifyPublishTx
// for.
func (s *MockSweeperStore) GetLastPublishedTx() (*wire.MsgTx, error) {
return s.lastTx, nil
}
// ListSweeps lists all the sweeps we have successfully published.
func (s *MockSweeperStore) ListSweeps() ([]chainhash.Hash, error) {
var txns []chainhash.Hash
for tx := range s.ourTxes {
txns = append(txns, tx)
}
return txns, nil
}
// Compile-time constraint to ensure MockSweeperStore implements SweeperStore.
var _ SweeperStore = (*MockSweeperStore)(nil)
| mit |
meowmio/knotz | grunt/watch.js | 218 | module.exports.tasks = {
watch: {
js: {
files: [
'<%= server %>**/*.js'
],
tasks: ['develop'],
options: { nospawn: true }
}
}
}; | mit |
Forec/learn | 2017.1/algorithms-review/ADT/union_set.cpp | 1517 | #include <iostream>
#include <vector>
#define MAXN 1000
using namespace std;
int father[MAXN];
int find_re(int x){
if (father[x] < 0) // use rank to union
return x;
father[x] = find_re(father[x]);
return father[x];
}
int find_loop(int x){
if (father[x] < 0)
return x;
int p = x;
while (father[p] >= 0)
p = father[p];
while (x != p){
int temp = father[x];
father[x] = p;
x = father[x];
}
return x;
}
void build_set(int size){
for (int i = 0; i < size; i++)
father[i] = -1; // use positve integers to represent father, use negative integers to represent rank
}
void unionSet(int x, int y){
if ((x = find_re(x)) == (y = find_re(y)))
return;
if (father[x] < father[y]){ // since negative interger represents the inverse number of rank, the smaller node represents bigger tree
father[x] += father[y];
father[y] = x;
} else {
father[y] += father[x];
father[x] = y;
}
}
int main(){
build_set(10);
cout << find_re(3) << endl;
cout << find_re(4) << endl;
unionSet(3, 4);
unionSet(5, 6);
unionSet(7, 8);
unionSet(7, 6); // 5, 6, 7, 8 are a set
unionSet(0, 1);
unionSet(0, 2);
unionSet(0, 4); // 0, 1, 2, 3, 4 are a set
cout << find_re(0) << " " << find_loop(1) <<
" " << find_re(2) << " " << find_loop(3) <<
" " << find_re(4) << endl;
cout << find_re(7) << " " << find_loop(5) <<
" " << find_re(6) << " " << find_loop(8) << endl;
return 0;
}
| mit |
AmrARaouf/algorithm-detection | graph-source-code/545-E/11160731.cpp | 1942 | //Language: GNU C++
#include<iostream>
#include<map>
#include<string>
#include<queue>
#include<fstream>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
vector <vector < pair < pair <long long, long long> , long long > > > v;
vector <long long> l;
int main(){
long long n,m,x,y,w;
cin>>n>>m;
vector <pair < pair <long long, long long> , long long > > t;
for(long long i=0;i<n;i++)
v.push_back(t);
for(long long i=0;i<m;i++){
cin>>x>>y>>w;
v[x-1].push_back(make_pair(make_pair(y-1,-w),i+1));
v[y-1].push_back(make_pair(make_pair(x-1,-w),i+1));
l.push_back(w);
}
cin>>y;
priority_queue < pair < pair <pair <long long, long long>, long long>, long long > > q;
q.push(make_pair(make_pair(make_pair(0,0),y-1),0));
set <long long> mark;
vector <long long> r;
long long rr=0;
while(q.size()>0){
pair < pair <pair <long long, long long> , long long>, long long > p = q.top();
q.pop();
if(mark.count(p.first.second) > 0)
continue;
mark.insert(p.first.second);
if(p.second!=0){
//cout<<"% "<<p.first.first.first<<endl;
r.push_back(p.second);
rr += l[p.second-1];
}
for(long long i=0;i<v[p.first.second].size();i++){
if(mark.count(v[p.first.second][i].first.first)==0){
q.push(make_pair(make_pair(make_pair(p.first.first.first+v[p.first.second][i].first.second, v[p.first.second][i].first.second) , v[p.first.second][i].first.first),v[p.first.second][i].second));
}
}
}
cout<<rr<<endl;
if(rr > 0){
for(long long i=0;i<r.size()-1;i++)
cout<<r[i]<<" ";
cout<<r[r.size()-1]<<endl;
}
return 0;
} | mit |
asarium/FSOLauncher | Global/GlobalAssemblyInfo.cs | 432 | #region Usings
using System.Reflection;
#endregion
[assembly: AssemblyCompany("FSSCP")]
[assembly: AssemblyProduct("FSOLauncher")]
[assembly: AssemblyCopyright("Copyright © FreeSpace Source Code Project 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyVersion("0.3.0.0")] | mit |
ghh0000/testTs | build/back/handlers/methodHandler.js | 1925 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const http_1 = require("../_http/http");
const container_1 = require("../container");
/**
* @wahtItDoes holds all information about the method of a controller
*/
class MethodHandler {
constructor() {
this.hasResponseBodyDecorator = false;
this.requestBodyParams = [];
}
call(req, res, next) {
let controller = container_1.Container.get(this.controller);
let method = controller[this.methodName];
let paramsValues = this.getparamsValues(req, res);
let dataToBeSent = method.call(controller, ...paramsValues);
if (this.hasResponseBodyDecorator) {
this.sendData(res, dataToBeSent);
}
}
getparamsValues(req, res) {
let paramsValues = [];
for (let i = 0; i < this.paramsNames.length; i++) {
paramsValues[i] = this.getParamValue(this.paramsNames[i], this.paramsTypes[i], req, res);
}
return paramsValues;
}
getParamValue(paramName, paramType, req, res) {
if (this.requestBodyParams[paramName]) {
return req.body;
}
else if (paramType === http_1.Request) {
return req;
}
else if (paramType === http_1.Response) {
return res;
}
else {
return req.params[paramName] || req.body[paramName] || req.query[paramName];
}
}
sendData(res, data) {
if (data instanceof Promise) {
data.then((dataToBeSent) => {
res.json(dataToBeSent);
});
}
else {
res.json(data);
}
}
isRequest(param) {
return param.baseUrl !== undefined && param.method !== undefined;
}
isResponse(param) {
return param.send !== undefined && param.end !== undefined;
}
}
exports.MethodHandler = MethodHandler;
| mit |
928PJY/docfx | src/Microsoft.DocAsCode.Build.Engine/TemplateRenderers/TemplateRendererResource.cs | 1386 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.Engine
{
using System;
using System.Collections.Generic;
using System.IO;
public class TemplateRendererResource
{
public static readonly Dictionary<string, TemplateRendererType> TemplateRenderTypeMapping = new Dictionary<string, TemplateRendererType>(StringComparer.OrdinalIgnoreCase)
{
[".liquid"] = TemplateRendererType.Liquid,
[".tmpl"] = TemplateRendererType.Mustache
};
public string Content { get; }
public string ResourceName { get; }
public string TemplateName { get; }
public TemplateRendererType Type { get; }
public TemplateRendererResource(string resourceName, string content, string templateName)
{
var extension = Path.GetExtension(resourceName);
TemplateRendererType type;
if (!TemplateRenderTypeMapping.TryGetValue(extension, out type))
{
throw new NotSupportedException($"The template extension {extension} is not supported.");
}
Type = type;
TemplateName = templateName;
ResourceName = resourceName;
Content = content;
}
}
}
| mit |
johnvandeweghe/php-api-library-core | src/Network/In/RequestTranslator/DataTranslatorInterface.php | 592 | <?php
namespace PHPAPILibrary\Core\Network\In\RequestTranslator;
use PHPAPILibrary\Core\Data\DataInterface;
use PHPAPILibrary\Core\Network\In\Exception\UnableToTranslateRequestException;
use PHPAPILibrary\Core\Network\RequestInterface;
/**
* Interface DataTranslatorInterface
* @package PHPAPILibrary\Core\Network\In\RequestTranslator
*/
interface DataTranslatorInterface
{
/**
* @param RequestInterface $request
* @return DataInterface
* @throws UnableToTranslateRequestException
*/
public function translateData(RequestInterface $request): DataInterface;
}
| mit |
AgileMods/MateriaMuto | src/api/java/ic2/api/energy/prefab/BasicSource.java | 10578 | package ic2.api.energy.prefab;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import cpw.mods.fml.common.FMLCommonHandler;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.ForgeDirection;
import ic2.api.energy.EnergyNet;
import ic2.api.energy.event.EnergyTileLoadEvent;
import ic2.api.energy.event.EnergyTileUnloadEvent;
import ic2.api.energy.tile.IEnergySource;
import ic2.api.info.Info;
import ic2.api.item.ElectricItem;
/**
* BasicSource is a simple adapter to provide an ic2 energy source.
*
* It's designed to be attached to a tile entity as a delegate. Functionally BasicSource acts as a
* one-time configurable output energy buffer, thus providing a common use case for generators.
*
* Sub-classing BasicSource instead of using it as a delegate works as well, but isn't recommended.
* The delegate can be extended with additional functionality through a sub class though.
*
* The constraints set by BasicSource like the strict tank-like energy buffering should provide a
* more easy to use and stable interface than using IEnergySource directly while aiming for
* optimal performance.
*
* Using BasicSource involves the following steps:
* - create a BasicSource instance in your TileEntity, typically in a field
* - forward invalidate, onChunkUnload, readFromNBT, writeToNBT and updateEntity to the BasicSource
* instance.
* If you have other means of determining when the tile entity is fully loaded, notify onLoaded
* that way instead of forwarding updateEntity.
* - call addEnergy whenever appropriate, using getFreeCapacity may determine if e.g. the generator
* should run
* - optionally use getEnergyStored to display the output buffer charge level
* - optionally use setEnergyStored to sync the stored energy to the client (e.g. in the Container)
*
* Example implementation code:
* @code{.java}
* public class SomeTileEntity extends TileEntity {
* // new basic energy source, 1000 EU buffer, tier 1 (32 EU/t, LV)
* private BasicSource ic2EnergySource = new BasicSource(this, 1000, 1);
*
* @Override
* public void invalidate() {
* ic2EnergySource.invalidate(); // notify the energy source
* ...
* super.invalidate(); // this is important for mc!
* }
*
* @Override
* public void onChunkUnload() {
* ic2EnergySource.onChunkUnload(); // notify the energy source
* ...
* }
*
* @Override
* public void readFromNBT(NBTTagCompound tag) {
* super.readFromNBT(tag);
*
* ic2EnergySource.readFromNBT(tag);
* ...
* }
*
* @Override
* public void writeToNBT(NBTTagCompound tag) {
* super.writeToNBT(tag);
*
* ic2EnergySource.writeToNBT(tag);
* ...
* }
*
* @Override
* public void updateEntity() {
* ic2EnergySource.updateEntity(); // notify the energy source
* ...
* ic2EnergySource.addEnergy(5); // add 5 eu to the source's buffer this tick
* ...
* }
*
* ...
* }
* @endcode
*/
public class BasicSource extends TileEntity implements IEnergySource {
// **********************************
// *** Methods for use by the mod ***
// **********************************
/**
* Constructor for a new BasicSource delegate.
*
* @param parent1 Base TileEntity represented by this energy source.
* @param capacity1 Maximum amount of eu to store.
* @param tier1 IC2 tier, 1 = LV, 2 = MV, ...
*/
public BasicSource(TileEntity parent1, double capacity1, int tier1) {
double power = EnergyNet.instance.getPowerFromTier(tier1);
this.parent = parent1;
this.capacity = capacity1 < power ? power : capacity1;
this.tier = tier1;
this.power = power;
}
// in-world te forwards >>
/**
* Forward for the base TileEntity's updateEntity(), used for creating the energy net link.
* Either updateEntity or onLoaded have to be used.
*/
@Override
public void updateEntity() {
if (!addedToEnet) {
onLoaded();
}
}
/**
* Notification that the base TileEntity finished loading, for advanced uses.
* Either updateEntity or onLoaded have to be used.
*/
public void onLoaded() {
if (!addedToEnet &&
!FMLCommonHandler.instance().getEffectiveSide().isClient() &&
Info.isIc2Available()) {
worldObj = parent.getWorldObj();
xCoord = parent.xCoord;
yCoord = parent.yCoord;
zCoord = parent.zCoord;
MinecraftForge.EVENT_BUS.post(new EnergyTileLoadEvent(this));
addedToEnet = true;
}
}
/**
* Forward for the base TileEntity's invalidate(), used for destroying the energy net link.
* Both invalidate and onChunkUnload have to be used.
*/
@Override
public void invalidate() {
super.invalidate();
onChunkUnload();
}
/**
* Forward for the base TileEntity's onChunkUnload(), used for destroying the energy net link.
* Both invalidate and onChunkUnload have to be used.
*/
@Override
public void onChunkUnload() {
if (addedToEnet &&
Info.isIc2Available()) {
MinecraftForge.EVENT_BUS.post(new EnergyTileUnloadEvent(this));
addedToEnet = false;
}
}
/**
* Forward for the base TileEntity's readFromNBT(), used for loading the state.
*
* @param tag Compound tag as supplied by TileEntity.readFromNBT()
*/
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
NBTTagCompound data = tag.getCompoundTag("IC2BasicSource");
energyStored = data.getDouble("energy");
}
/**
* Forward for the base TileEntity's writeToNBT(), used for saving the state.
*
* @param tag Compound tag as supplied by TileEntity.writeToNBT()
*/
@Override
public void writeToNBT(NBTTagCompound tag) {
try {
super.writeToNBT(tag);
} catch (RuntimeException e) {
// happens if this is a delegate, ignore
}
NBTTagCompound data = new NBTTagCompound();
data.setDouble("energy", energyStored);
tag.setTag("IC2BasicSource", data);
}
// << in-world te forwards
// methods for using this adapter >>
/**
* Get the maximum amount of energy this source can hold in its buffer.
*
* @return Capacity in EU.
*/
public double getCapacity() {
return capacity;
}
/**
* Set the maximum amount of energy this source can hold in its buffer.
*
* @param capacity1 Capacity in EU.
*/
public void setCapacity(double capacity1) {
if (capacity1 < power) {
capacity1 = power;
}
this.capacity = capacity1;
}
/**
* Get the IC2 energy tier for this source.
*
* @return IC2 Tier.
*/
public int getTier() {
return tier;
}
/**
* Set the IC2 energy tier for this source.
*
* @param tier1 IC2 Tier.
*/
public void setTier(int tier1) {
double power = EnergyNet.instance.getPowerFromTier(tier1);
if (capacity < power) {
capacity = power;
}
this.tier = tier1;
this.power = power;
}
/**
* Determine the energy stored in the source's output buffer.
*
* @return amount in EU
*/
public double getEnergyStored() {
return energyStored;
}
/**
* Set the stored energy to the specified amount.
*
* This is intended for server -> client synchronization, e.g. to display the stored energy in
* a GUI through getEnergyStored().
*
* @param amount
*/
public void setEnergyStored(double amount) {
energyStored = amount;
}
/**
* Determine the free capacity in the source's output buffer.
*
* @return amount in EU
*/
public double getFreeCapacity() {
return capacity - energyStored;
}
/**
* Add some energy to the output buffer.
*
* @param amount maximum amount of energy to add
* @return amount added/used, NOT remaining
*/
public double addEnergy(double amount) {
if (FMLCommonHandler.instance().getEffectiveSide().isClient()) {
return 0;
}
if (amount > capacity - energyStored) {
amount = capacity - energyStored;
}
energyStored += amount;
return amount;
}
/**
* Charge the supplied ItemStack from this source's energy buffer.
*
* @param stack ItemStack to charge (null is ignored)
* @return true if energy was transferred
*/
public boolean charge(ItemStack stack) {
if (stack == null || !Info.isIc2Available()) {
return false;
}
double amount = ElectricItem.manager.charge(stack, energyStored, tier, false, false);
energyStored -= amount;
return amount > 0;
}
// << methods for using this adapter
// backwards compatibility (ignore these) >>
@Deprecated
public void onUpdateEntity() {
updateEntity();
}
@Deprecated
public void onInvalidate() {
invalidate();
}
@Deprecated
public void onOnChunkUnload() {
onChunkUnload();
}
@Deprecated
public void onReadFromNbt(NBTTagCompound tag) {
readFromNBT(tag);
}
@Deprecated
public void onWriteToNbt(NBTTagCompound tag) {
writeToNBT(tag);
}
// << backwards compatibility
// ******************************
// *** Methods for use by ic2 ***
// ******************************
// energy net interface >>
@Override
public boolean emitsEnergyTo(TileEntity receiver, ForgeDirection direction) {
return true;
}
@Override
public double getOfferedEnergy() {
return Math.min(energyStored, power);
}
@Override
public void drawEnergy(double amount) {
energyStored -= amount;
}
@Override
public int getSourceTier() {
return tier;
}
// << energy net interface
public final TileEntity parent;
protected double capacity;
protected int tier;
protected double power;
protected double energyStored;
protected boolean addedToEnet;
}
| mit |
iliangogov/Databases | 13. Entity Framework Code First/Homework/EntityFrameworkCodeFirst/Models/Student.cs | 1056 | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models
{
public class Student
{
private ICollection<Course> courses;
private ICollection<Homework> homeworks;
public Student()
{
this.courses = new HashSet<Course>();
this.homeworks = new HashSet<Homework>();
}
public int Id { get; set; }
[MinLength(2)]
[MaxLength(50)]
[Required]
public string Name { get; set; }
[Index(IsUnique = true)]
public int Number { get; set; }
public virtual ICollection<Course> Courses
{
get { return this.courses; }
set { this.courses = value; }
}
public virtual ICollection<Homework> Homeworks
{
get { return this.homeworks; }
set { this.homeworks = value; }
}
}
}
| mit |
usefulparadigm/jigso | config/environments/development.rb | 1164 | Jigso::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => 'jigso.dev' }
# config.action_mailer.delivery_method = :test # use this to NOT send emails in development mode
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
end
| mit |
jasonallenphotography/SmackOverflow | db/migrate/20160818161031_create_questions.rb | 244 | class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.string :title
t.text :body
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
| mit |
molstar/molstar | src/mol-geo/primitive/primitive.ts | 3964 | /**
* Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author Alexander Rose <[email protected]>
*/
import { Vec3, Mat4, Mat3 } from '../../mol-math/linear-algebra';
import { NumberArray } from '../../mol-util/type-helpers';
export interface Primitive {
vertices: ArrayLike<number>
normals: ArrayLike<number>
indices: ArrayLike<number>
}
const a = Vec3(), b = Vec3(), c = Vec3();
/** Create primitive with face normals from vertices and indices */
export function createPrimitive(vertices: ArrayLike<number>, indices: ArrayLike<number>): Primitive {
const count = indices.length;
const builder = PrimitiveBuilder(count / 3);
for (let i = 0; i < count; i += 3) {
Vec3.fromArray(a, vertices, indices[i] * 3);
Vec3.fromArray(b, vertices, indices[i + 1] * 3);
Vec3.fromArray(c, vertices, indices[i + 2] * 3);
builder.add(a, b, c);
}
return builder.getPrimitive();
}
export function copyPrimitive(primitive: Primitive): Primitive {
return {
vertices: new Float32Array(primitive.vertices),
normals: new Float32Array(primitive.normals),
indices: new Uint32Array(primitive.indices)
};
}
export interface PrimitiveBuilder {
add(a: Vec3, b: Vec3, c: Vec3): void
/** Shared vertices and normals, must be flat */
addQuad(a: Vec3, b: Vec3, c: Vec3, d: Vec3): void
getPrimitive(): Primitive
}
const vn = Vec3();
/** Builder to create primitive with face normals */
export function PrimitiveBuilder(triangleCount: number, vertexCount?: number): PrimitiveBuilder {
if (vertexCount === undefined) vertexCount = triangleCount * 3;
const vertices = new Float32Array(vertexCount * 3);
const normals = new Float32Array(vertexCount * 3);
const indices = new Uint32Array(triangleCount * 3);
let vOffset = 0;
let iOffset = 0;
return {
add: (a: Vec3, b: Vec3, c: Vec3) => {
Vec3.toArray(a, vertices, vOffset);
Vec3.toArray(b, vertices, vOffset + 3);
Vec3.toArray(c, vertices, vOffset + 6);
Vec3.triangleNormal(vn, a, b, c);
for (let j = 0; j < 3; ++j) {
Vec3.toArray(vn, normals, vOffset + 3 * j);
indices[iOffset + j] = vOffset / 3 + j;
}
vOffset += 9;
iOffset += 3;
},
addQuad: (a: Vec3, b: Vec3, c: Vec3, d: Vec3) => {
Vec3.toArray(a, vertices, vOffset);
Vec3.toArray(b, vertices, vOffset + 3);
Vec3.toArray(c, vertices, vOffset + 6);
Vec3.toArray(d, vertices, vOffset + 9);
Vec3.triangleNormal(vn, a, b, c);
for (let j = 0; j < 4; ++j) {
Vec3.toArray(vn, normals, vOffset + 3 * j);
}
const vOffset3 = vOffset / 3;
// a, b, c
indices[iOffset] = vOffset3;
indices[iOffset + 1] = vOffset3 + 1;
indices[iOffset + 2] = vOffset3 + 2;
// a, b, c
indices[iOffset + 3] = vOffset3 + 2;
indices[iOffset + 4] = vOffset3 + 3;
indices[iOffset + 5] = vOffset3;
vOffset += 12;
iOffset += 6;
},
getPrimitive: () => ({ vertices, normals, indices })
};
}
const tmpV = Vec3();
const tmpMat3 = Mat3();
/** Transform primitive in-place */
export function transformPrimitive(primitive: Primitive, t: Mat4) {
const { vertices, normals } = primitive;
const n = Mat3.directionTransform(tmpMat3, t);
for (let i = 0, il = vertices.length; i < il; i += 3) {
// position
Vec3.transformMat4(tmpV, Vec3.fromArray(tmpV, vertices, i), t);
Vec3.toArray(tmpV, vertices as NumberArray, i);
// normal
Vec3.transformMat3(tmpV, Vec3.fromArray(tmpV, normals, i), n);
Vec3.toArray(tmpV, normals as NumberArray, i);
}
return primitive;
} | mit |
solutious/stella | try/09_utils_try.rb | 1230 | require 'stella'
## Knows a valid hostname
Stella::Utils.valid_hostname? 'localhost'
#=> true
## Knows a invalid hostname
Stella::Utils.valid_hostname? 'localhost900000000'
#=> false
## Local IP address
Stella::Utils.local_ipaddr? '127.0.0.255'
#=> true
## Private IP address (class A)
Stella::Utils.private_ipaddr? '10.0.0.255'
#=> true
## Private IP address (class C)
Stella::Utils.private_ipaddr? '172.16.0.255'
#=> true
## Private IP address (class C)
Stella::Utils.private_ipaddr? '192.168.0.255'
#=> true
## Rudimentary test for binary data.
a = File.read('/usr/bin/less')
Stella::Utils.binary?(a)
#=> true
## Rudimentary test for text data
a = File.read('/etc/hosts')
Stella::Utils.binary?(a)
#=> false
## Knows a JPG
a = File.read('try/support/file.jpg')
Stella::Utils.jpg?(a)
#=>true
## Knows a GIF
a = File.read('try/support/file.gif')
Stella::Utils.gif?(a)
#=>true
## Knows a PNG
a = File.read('try/support/file.png')
Stella::Utils.png?(a)
#=>true
## Knows a BMP
a = File.read('try/support/file.bmp')
Stella::Utils.bmp?(a)
#=>true
## Knows an ICO
a = File.read('try/support/file.ico')
Stella::Utils.ico?(a)
#=>true
## Knows an image
a = File.read('try/support/file.ico')
Stella::Utils.image?(a)
#=>true
| mit |
fe-lix-/deckbrew-api | src/Criteria/Specifications/WithSuperType.php | 227 | <?php
namespace DeckBrew\Criteria\Specifications;
class WithSuperType extends AbstractSpecification
{
/**
* @return string
*/
public function getSpecificationType()
{
return 'supertype';
}
}
| mit |
rac2030/MakeZurich | logs/arduinoDataWriter.py | 1353 | import serial
import time
import datetime
promini = '/dev/cu.SLAB_USBtoUART'
ser = serial.Serial(promini, 9600)
repeatTime = 1000 # milliseconds
def writeData(value):
# Get the current data
today = datetime.date.today()
# Open log file 2012-6-23.log and append
with open(str(today)+'.log', 'ab') as f:
f.write(value)
# Write our integer value to our log
f.write('\n')
# Add a newline so we can retrieve the data easily later, could use spaces too.
timer = time.time() # Timer to see when we started
while True:
time.sleep(0.25) # sleep for 250 milliseconds
if time.time() - timer > repeatTime:
# If the current time is greater than the repeat time, send our 'get' command again
serial.write("t\n")
timer = time.time() # start the timer over
if ser.inWaiting() > 2: # if we have \r\n in there, we will have two characters, we want more!
value = serial.read() # Read the data from the
value = value.strip('\r\n') # Arduino will return DATA\r\n when println is used
try:
value = int(value) #This is likely where you will get 'duff' data and catch it.
writeData(value) # Write the data to a log file
except:
serial.write("t\n") # Try it again! | mit |
thexilent13/case-one-secudev | public/modules/carts/config/cart.client.config.js | 201 | 'use strict';
// Configuring the Articles module
angular.module('carts').run(['Menus',
function(Menus) {
// Set top bar menu items
//Menus.addMenuItem('topbar', 'Cart', 'cart', '/carts');
}
]);
| mit |
janstenpickle/extruder | metrics/dropwizard/src/test/scala/extruder/metrics/dropwizard/keyed/DropwizardKeyedEncodersSpec.scala | 1739 | package extruder.metrics.dropwizard.keyed
import extruder.metrics._
import extruder.metrics.data.{CounterValue, GaugeValue, TimerValue}
import io.dropwizard.metrics5.{MetricName, MetricRegistry}
import org.scalacheck.ScalacheckShapeless._
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.{Assertion, EitherValues}
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks
class DropwizardKeyedEncodersSpec extends AnyFunSuite with ScalaCheckDrivenPropertyChecks with EitherValues {
import DropwizardKeyedEncodersSpec._
test("Can encode namespaced values")(encodeNamespaced)
test("Can encode an object")(encodeObject)
def settings: DropwizardKeyedMetricSettings = new DropwizardKeyedMetricSettings {}
def encodeNamespaced: Assertion = forAll { (value: Int, name: String) =>
val reg: MetricRegistry = encode(List(name), settings, value).value.value.right.value
assert(reg.getGauges.size() === 1)
assert(reg.getGauges().get(MetricName.build(snakeCaseTransformation(name))).getValue === value.toDouble)
}
def encodeObject: Assertion = forAll { metrics: Metrics =>
val reg: MetricRegistry = encode(settings, metrics).value.value.right.value
assert(reg.getGauges.size() === 2)
assert(reg.getCounters.size() === 1)
assert(reg.getGauges.get(MetricName.build("metrics.timer")).getValue === metrics.timer.value.toDouble)
assert(reg.getGauges.get(MetricName.build("metrics.gauge")).getValue === metrics.gauge.value.toDouble)
assert(reg.getCounters.get(MetricName.build("metrics.counter")).getCount === metrics.counter.value)
}
}
object DropwizardKeyedEncodersSpec {
case class Metrics(counter: CounterValue[Long], timer: TimerValue[Int], gauge: GaugeValue[Float])
}
| mit |
moreirainacio/grupotrilhas | _frontend/quem-somos.php | 4466 | <?php
include('includes/header.php');
?>
<?php //quem-somos ?>
<section id="quem-somos-page">
<div class="container text-center">
<div class="row">
<div class="col-xs-7">
<div class="row">
<h1><img src="assets/images/title-quem-somos.png" alt="" class="title"/></h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi cupiditate dolor est libero,
molestiae quam totam. Ad amet, dignissimos dolor eligendi fugiat, in inventore ipsum, laudantium
reprehenderit repudiandae sunt voluptates. Lorem ipsum dolor sit amet, consectetur adipisicing
elit. Consectetur consequuntur corporis delectus earum eos est, facilis hic, illum inventore
libero maxime modi nulla qui recusandae temporibus velit voluptas! Cupiditate, vitae?
</p>
<div id="video">
<img src="" alt="" width="495" height="320"/>
<iframe width="460" height="285" src="https://www.youtube.com/embed/jQFo3jQzYhc" frameborder="0"
allowfullscreen></iframe>
</div>
</div>
<div class="row cases-videos">
<a href="http://www.integralpne.com.br/wp-content/uploads/2014/09/Paisagem.jpg" class="iframe" rel="quem-somos">
<img src="http://www.integralpne.com.br/wp-content/uploads/2014/09/Paisagem.jpg" alt="" width="115" height="113"/>
</a>
<a href="http://www.integralpne.com.br/wp-content/uploads/2014/09/Paisagem.jpg" class="iframe" rel="quem-somos">
<img src="http://www.integralpne.com.br/wp-content/uploads/2014/09/Paisagem.jpg" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
<a href="" class="iframe" rel="quem-somos">
<img src="" alt="" width="115" height="113"/>
</a>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-4">
<h2 class="text-center">Missão</h2>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero
</p>
</div>
<div class="col-xs-4">
<h2 class="text-center">Visão</h2>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero
</p>
</div>
<div class="col-xs-4">
<h2 class="text-center">Valor</h2>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero
</p>
</div>
</div>
<div class="row agencia">
<img src="assets/images/title-agencia.png" alt="" class="title"/>
</div>
</div>
</section>
<?php //.quem-somos ?>
<?php
include('includes/footer.php');
?>
| mit |
valcol/ScrumNinja | app/tests/acceptance/substep_definitions/When_I_put_the_date_#_in the_#_field.js | 202 | module.exports = function() {
this.Then(/^I put the date "([^"]*)" in the "([^"]*)" field$/, function (arg, arg2) {
browser.waitForExist(arg2, 1000);
browser.element(arg2).keys(arg);
});
};
| mit |
fetus-hina/testfire2.stat.ink | webapp/models/Environment.php | 1404 | <?php
/**
* @copyright Copyright (C) 2015 AIZAWA Hina
* @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
* @author AIZAWA Hina <[email protected]>
*/
namespace app\models;
use Yii;
/**
* This is the model class for table "environment".
*
* @property integer $id
* @property string $sha256sum
* @property string $text
*
* @property Battle[] $battles
* @property User[] $users
*/
class Environment extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'environment';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['sha256sum', 'text'], 'required'],
[['text'], 'string'],
[['sha256sum'], 'string', 'max' => 43],
[['sha256sum'], 'unique']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'sha256sum' => 'Sha256sum',
'text' => 'Text',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBattles()
{
return $this->hasMany(Battle::className(), ['env_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUsers()
{
return $this->hasMany(User::className(), ['env_id' => 'id']);
}
}
| mit |
calebboyd/app-builder | src/test.spec.ts | 3701 | import appBuilder, { compose, AppBuilder, functionList } from './app-builder'
describe('app-builder', () => {
let builder: any
beforeEach(() => {
builder = new AppBuilder()
})
describe('appBuilder default export', () => {
it('gets an instance', () => expect(appBuilder()).toBeInstanceOf(AppBuilder))
})
describe('use', () => {
it('adds middleware to the builder', () => {
expect(builder.middleware.length).toEqual(0)
let mw1: any, mw2: any
builder.use((mw1 = () => Promise.resolve())).use((mw2 = () => Promise.resolve()))
expect(builder.middleware.length).toEqual(2)
expect(builder.middleware[0]).toEqual(mw1)
expect(builder.middleware[1]).toEqual(mw2)
})
it('expects a function', () => {
expect(builder.use.bind(builder, {})).toThrow(Error)
})
})
describe('build', () => {
it('throws when no mw are present', () => {
expect(() => builder.build()).toThrow(Error)
})
it('returns a function', () => {
builder.use(() => Promise.resolve())
expect(typeof builder.build()).toEqual('function')
})
it('throws when a middleware is not a function', () => {
builder.middleware.push({})
expect(builder.build.bind(builder)).toThrow(Error)
})
})
describe('funcitonList', () => {
it('should execute a list of provided functions in order', async () => {
const output = { str: '' }
await compose(
functionList([
() => (output.str += 1),
() => (output.str += 2),
async () => {
output.str += await Promise.resolve(3)
},
() => (output.str += 4),
])
)()
expect(output.str).toEqual('1234')
})
})
describe('composed function', () => {
it('can short circuit', async () => {
const m = { count: 0 }
await builder
.use(async (x: any) => {
x.count++
})
.use(async (x: any) => {
x.count++
})
.build()(m)
expect(m.count).toEqual(1)
})
it('works', async () => {
let str = ''
await builder
.use(async (x: any, next: any) => {
str += 1
await next()
str += 3
})
.use(async (x: any, next: any) => {
await next()
str += 2
})
.build()({})
expect(str).toEqual('123')
})
it('is valid middleware', async () => {
const context = { str: '' }
const func = compose<typeof context>([
async function (ctx, next) {
ctx.str += 1
await next()
ctx.str += 5
},
async function (ctx, next) {
ctx.str += 2
await next()
ctx.str += 4
},
])
await func(context, (ctx, next) => {
ctx.str += 3
return next()
})
expect(context.str).toEqual('12345')
})
it('throws when next is invoked multiple times', async () => {
try {
await compose(async (x, next) => {
await next()
await next()
})()
throw new Error('failed')
} catch (error) {
expect(error.message).toEqual('Cannot call next more than once')
}
})
it('propagates errors from middleware', async () => {
const someError = new Error(Math.random().toString())
function doThrow() {
throw someError
}
let didError = false
try {
await compose(() => {
doThrow()
return Promise.resolve()
})()
} catch (error) {
didError = true
expect(error).toEqual(someError)
}
expect(didError).toBeTruthy
})
})
})
| mit |
Aloomaio/node-sodium | install.js | 11358 | /**
* Node Sodium install script to help support Windows
*
* @Author Pedro Paixao
* @email paixaop at gmail dot com
* @License MIT
*/
var https = require('https');
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var os = require('os');
var libFiles = [
'libsodium.dll',
'libsodium.exp',
'libsodium.lib',
'libsodium.pdb',
];
var includeFiles = [
'include/sodium/core.h',
'include/sodium/crypto_aead_aes256gcm.h',
'include/sodium/crypto_aead_chacha20poly1305.h',
'include/sodium/crypto_aead_xchacha20poly1305.h',
'include/sodium/crypto_auth.h',
'include/sodium/crypto_auth_hmacsha256.h',
'include/sodium/crypto_auth_hmacsha512.h',
'include/sodium/crypto_auth_hmacsha512256.h',
'include/sodium/crypto_box.h',
'include/sodium/crypto_box_curve25519xchacha20poly1305.h',
'include/sodium/crypto_box_curve25519xsalsa20poly1305.h',
'include/sodium/crypto_core_ed25519.h',
'include/sodium/crypto_core_hchacha20.h',
'include/sodium/crypto_core_hsalsa20.h',
'include/sodium/crypto_core_salsa20.h',
'include/sodium/crypto_core_salsa2012.h',
'include/sodium/crypto_core_salsa208.h',
'include/sodium/crypto_generichash.h',
'include/sodium/crypto_generichash_blake2b.h',
'include/sodium/crypto_hash.h',
'include/sodium/crypto_hash_sha256.h',
'include/sodium/crypto_hash_sha512.h',
'include/sodium/crypto_kdf.h',
'include/sodium/crypto_kdf_blake2b.h',
'include/sodium/crypto_kx.h',
'include/sodium/crypto_onetimeauth.h',
'include/sodium/crypto_onetimeauth_poly1305.h',
'include/sodium/crypto_pwhash.h',
'include/sodium/crypto_pwhash_argon2i.h',
'include/sodium/crypto_pwhash_argon2id.h',
'include/sodium/crypto_pwhash_scryptsalsa208sha256.h',
'include/sodium/crypto_scalarmult.h',
'include/sodium/crypto_scalarmult_curve25519.h',
'include/sodium/crypto_scalarmult_ed25519.h',
'include/sodium/crypto_secretbox.h',
'include/sodium/crypto_secretbox_xchacha20poly1305.h',
'include/sodium/crypto_secretbox_xsalsa20poly1305.h',
'include/sodium/crypto_secretstream_xchacha20poly1305.h',
'include/sodium/crypto_shorthash.h',
'include/sodium/crypto_shorthash_siphash24.h',
'include/sodium/crypto_sign.h',
'include/sodium/crypto_sign_ed25519.h',
'include/sodium/crypto_sign_edwards25519sha512batch.h',
'include/sodium/crypto_stream.h',
'include/sodium/crypto_stream_chacha20.h',
'include/sodium/crypto_stream_salsa20.h',
'include/sodium/crypto_stream_salsa2012.h',
'include/sodium/crypto_stream_salsa208.h',
'include/sodium/crypto_stream_xchacha20.h',
'include/sodium/crypto_stream_xsalsa20.h',
'include/sodium/crypto_verify_16.h',
'include/sodium/crypto_verify_32.h',
'include/sodium/crypto_verify_64.h',
'include/sodium/export.h',
'include/sodium/randombytes.h',
'include/sodium/randombytes_salsa20_random.h',
'include/sodium/randombytes_sysrandom.h',
'include/sodium/runtime.h',
'include/sodium/utils.h',
'include/sodium/version.h',
'include/sodium.h'
];
function recursePathList(paths) {
if (0 === paths.length) {
return;
}
var file = paths.shift();
if (!fs.existsSync(file)) {
try {
fs.mkdirSync(file, 0755);
} catch (e) {
throw new Error("Failed to create path: " + file + " with " + e.toString());
}
}
recursePathList(paths);
}
function createFullPath(fullPath) {
var normPath = path.normalize(fullPath);
var file = '';
var pathList = [];
var parts = [];
if (normPath.indexOf('/') !== -1) {
parts = normPath.split('/');
} else {
parts = normPath.split('\\');
}
for (var i = 0, max = parts.length; i < max; i++) {
if (parts[i]) {
file = path.join(file, parts[i]);
pathList.push(file);
}
}
if (0 === pathList.length)
throw new Error("Path list was empty");
else
recursePathList(pathList);
}
function exists(path) {
try {
fs.accessSync(path, fs.F_OK);
return true;
} catch (e) {
return false;
}
}
function download(url, dest, cb) {
if(exists(dest)) {
console.log('File ' + dest + ' alredy exists, run make clean if you want to download it again.');
cb(null);
}
var file = fs.createWriteStream(dest);
var request = https.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb) cb(err);
});
}
function getPlatformToolsVersion() {
var platformTools = {
2010: 'v100',
2012: 'v110',
2013: 'v120',
2015: 'v140'
}
checkMSVSVersion();
var ver = platformTools[process.env.npm_config_msvs_version];
if (!ver) {
throw new Error('Please set msvs_version');
}
return ver;
}
function downloadAll(files, baseURL, basePath, next) {
if (0 === files.length) {
next();
return;
}
var file = files.shift();
var url = baseURL + '/' + file;
var path = basePath + '/' + file;
console.log('Download: ' + url);
download(url, path, function(err) {
if (err) {
throw err;
}
downloadAll(files, baseURL, basePath, next);
});
}
function copyFile(source, target, cb) {
var cbCalled = false;
var rd = fs.createReadStream(source);
rd.on("error", function(err) {
done(err);
});
var wr = fs.createWriteStream(target);
wr.on("error", function(err) {
done(err);
});
wr.on("close", function(ex) {
done();
});
rd.pipe(wr);
function done(err) {
if (!cbCalled) {
cb(err);
cbCalled = true;
}
}
}
function copyFiles(files, next) {
if (0 === files.length) {
next();
return;
}
var file = files.shift();
var from = 'deps/build/lib/' + file;
var to = 'build/Release/' + file;
copyFile(from, to, function(err) {
if (err) {
throw err;
}
console.log('Copy ' + from + ' to ' + to);
copyFiles(files, next);
})
}
function gypConfigure(next) {
var gyp = exec('node-gyp configure');
gyp.stdout.on('data', function(data) {
process.stdout.write(data.toString());
});
gyp.stderr.on('data', function(data) {
process.stdout.write(data.toString());
});
gyp.on('close', function(code) {
console.log('Done.');
next();
});
}
function doDownloads(next) {
var baseURL = 'https://raw.githubusercontent.com/paixaop/libsodium-bin/master';
console.log('Download libsodium.lib');
var ver = getPlatformToolsVersion();
console.log('Platform Tool is ' + ver);
switch (os.arch()) {
case 'x64':
arch = 'x64';
break;
case 'ia32':
arch = 'Win32';
break;
default:
throw new Error('No pre-compiled binary available for this platform ' + os.arch());
}
// Older versions of node-sodium will try and download from the 'root' of baseURL
// Added libsodium_version to package.json to support multiple binary versions of
// libsodium
var package = require('./package.json');
if( package.libsodium_version ) {
baseURL += '/' + package.libsodium_version;
}
var libURL = baseURL + '/' + arch + '/Release/' + ver + '/dynamic';
files = libFiles.slice(0); // clone array
downloadAll(files, libURL, 'deps/build/lib', function() {
console.log('Libs for version ' + ver + ' downloaded.');
downloadAll(includeFiles, baseURL, 'deps/build', function() {
console.log('Include files downloaded.');
next();
});
});
}
function run(cmdLine, expectedExitCode, next) {
var child = spawn(cmdLine, { shell: true });
if (typeof expectedExitCode === 'undefined') {
expectedExitCode = 0;
}
child.stdout.on('data', function(data) {
process.stdout.write(data.toString());
});
child.stderr.on('data', function(data) {
process.stdout.write(data.toString());
});
child.on('exit', function(code) {
if (code !== expectedExitCode) {
throw new Error(cmdLine + ' exited with code ' + code);
}
if (!next) process.exit(0);
next();
});
}
function errorSetMSVSVersion() {
console.log('Please set your Microsoft Visual Studio version before you run npm install');
console.log('Example for Visual Studio 2015:\n');
console.log(' For you user only:\n');
console.log(' npm config set msvs_version 2015\n');
console.log(' Global:\n');
console.log(' npm config set msvs_version 2015 --global\n');
console.log('Supported values are 2010, 2012, 2013, 2015\n');
process.exit(1);
}
function errorInvalidMSVSVersion() {
console.log('Invalid msvs_version ' + msvsVersion + '\n');
console.log('Please set your Microsoft Visual Studio version before you run npm install');
console.log('Example for Visual Studio 2015:\n');
console.log(' For you user only:\n');
console.log(' npm config set msvs_version 2015\n');
console.log(' Global:\n');
console.log(' npm config set msvs_version 2015 --global\n');
console.log('Supported values are 2010, 2012, 2013, 2015\n');
process.exit(1);
}
function checkMSVSVersion() {
if (!process.env.npm_config_msvs_version) {
errorSetMSVSVersion();
}
console.log('MS Version: ' + process.env.npm_config_msvs_version);
if (process.env.npm_config_msvs_version.search(/^2010|2012|2013|2015$/)) {
errorInvalidMSVSVersion();
}
}
function isPreInstallMode() {
if (!process.argv[2] || process.argv[2].search(/^--preinstall|--install/)) {
console.log('please call install with --preinstall or --install');
process.exit(1);
}
if (process.argv[2] === '--preinstall') {
return true;
}
return false;
}
// Start
if (os.platform() !== 'win32') {
if (isPreInstallMode()) {
run('make libsodium');
} else {
run('make nodesodium');
}
} else {
checkMSVSVersion();
if (isPreInstallMode()) {
console.log('Preinstall Mode');
createFullPath("deps/build/include/sodium");
createFullPath("deps/build/lib");
createFullPath("build/Release");
doDownloads(function() {
console.log('Prebuild steps completed. Binary libsodium distribution installed in ./deps/build');
process.exit(0);
});
} else {
console.log('Install Mode');
run('node-gyp rebuild', 0, function() {
console.log('Copy lib files to Release folder');
files = libFiles.slice(0); // clone array
copyFiles(files, function() {
console.log('Done copying files.');
process.exit(0);
});
});
}
} | mit |
leechuck/abercoin | src/muscle/writescorefile.cpp | 1690 | #include "muscle.h"
#include "msa.h"
#include <errno.h>
extern float VTML_SP[32][32];
extern float NUC_SP[32][32];
static double GetColScore(const MSA &msa, unsigned uCol)
{
const unsigned uSeqCount = msa.GetSeqCount();
unsigned uPairCount = 0;
double dSum = 0.0;
for (unsigned uSeq1 = 0; uSeq1 < uSeqCount; ++uSeq1)
{
if (msa.IsGap(uSeq1, uCol))
continue;
unsigned uLetter1 = msa.GetLetterEx(uSeq1, uCol);
if (uLetter1 >= g_AlphaSize)
continue;
for (unsigned uSeq2 = uSeq1 + 1; uSeq2 < uSeqCount; ++uSeq2)
{
if (msa.IsGap(uSeq2, uCol))
continue;
unsigned uLetter2 = msa.GetLetterEx(uSeq2, uCol);
if (uLetter2 >= g_AlphaSize)
continue;
double Score;
switch (g_Alpha)
{
case ALPHA_Amino:
Score = VTML_SP[uLetter1][uLetter2];
break;
case ALPHA_DNA:
case ALPHA_RNA:
Score = NUC_SP[uLetter1][uLetter2];
break;
default:
Quit("GetColScore: invalid alpha=%d", g_Alpha);
}
dSum += Score;
++uPairCount;
}
}
if (0 == uPairCount)
return 0;
return dSum / uPairCount;
}
void WriteScoreFile(const MSA &msa)
{
FILE *f = fopen(g_pstrScoreFileName, "w");
if (0 == f)
Quit("Cannot open score file '%s' errno=%d", g_pstrScoreFileName, errno);
const unsigned uColCount = msa.GetColCount();
const unsigned uSeqCount = msa.GetSeqCount();
for (unsigned uCol = 0; uCol < uColCount; ++uCol)
{
double Score = GetColScore(msa, uCol);
fprintf(f, "%10.3f ", Score);
for (unsigned uSeq = 0; uSeq < uSeqCount; ++uSeq)
{
char c = msa.GetChar(uSeq, uCol);
fprintf(f, "%c", c);
}
fprintf(f, "\n");
}
fclose(f);
}
| mit |
framky007/Document-management-system | server/controllers/role.js | 3044 | import { verifyString, verifyIsInt } from '../helpers/validation';
import { getRoles } from '../helpers/query';
import { paginateResult } from '../helpers/pagination';
import models from '../models';
const Role = models.Role;
/**
* gets all available roles in the database
* @function getAllRoles
* @param {object} request request
* @param {object} response response
* @return {object} object - information about the status of the request
*/
const getAllRoles = (request, response) => {
const query = getRoles(request);
Role.findAndCountAll(query)
.then(roles => response.status(200).json(
paginateResult(roles, query, 'roles')
)
)
.catch(error => response.status(500).json({
error: 'An unexpected error occurred',
detailed_error: error,
more_info: 'https://dmsys.herokuapp.com/#find-matching-instances-of-role',
}));
};
/**
* creates new role
* @function createRole
* @param {object} request request
* @param {object} response response
* @return {object} object - information about the status of the request
*/
const createRole = (request, response) => {
const isString = verifyString(request.body.roleName);
if (!isString) {
return response.status(406).json({
error: 'roleName must be a string',
more_info: 'https://dmsys.herokuapp.com/#create-new-role',
});
}
Role.create({
roleName: request.body.roleName,
})
.then(role => response.status(201).json({
message: 'new role created successfully',
role,
})
)
.catch(error => response.status(409).json({
error: `Cannot create role with specified ID, ensure the roleName
doesn't already exist in the database`,
detailed_error: error.message,
roleName: (request.body.roleName).toLowerCase(),
more_info: 'https://dmsys.herokuapp.com/#create-new-role',
})
);
};
/**
* updates role name in the database
* @function updateRole
* @param {object} request request
* @param {object} response response
* @return {object} object - information about the status of the request
*/
const updateRole = (request, response) => {
verifyIsInt(request)
.then((result) => {
const verifiedParams = result.mapped();
const noErrors = result.isEmpty();
if (!noErrors) {
return response.status(412).json({ message: verifiedParams });
}
const roleId = Number(request.params.id);
if (roleId === request.decoded.data.roleId) {
return response.status(403).json({
error: 'This action is forbidden',
more_info: 'https://dmsys.herokuapp.com/#update-role',
});
}
Role.update(request.body, { where: { id: roleId } })
.then(() => response.status(200).json({
message: 'updated successfully',
})
)
.catch(error => response.status(409).json({
error: 'An unexpected error occurred',
detailed_error: error.errors,
more_info: 'https://dmsys.herokuapp.com/#update-role',
})
);
});
};
module.exports = {
getAllRoles,
createRole,
updateRole,
};
| mit |
CartoType/CartoType-Public-4-3 | src/demo/android_demo/Navigator/src/com/cartotype/FrameworkParam.java | 1457 | /*
FrameworkParam.java
Copyright (C) 2015 CartoType Ltd.
See www.cartotype.com for more information.
*/
package com.cartotype;
/**
Parameters for creating a CartoType framework when more detailed control is needed.
For example, file buffer size and the maximum number of buffers can be set.
*/
public class FrameworkParam
{
/** The map. Must not be null or empty. */
public String iMapFileName;
/** The style sheet. Must not be null or empty. */
public String iStyleSheetFileName;
/** The font file. Must not be null or empty. */
public String iFontFileName;
/** The width of the map in pixels. Must be greater than zero. */
public int iViewWidth;
/** The height of the map in pixels. Must be greater than zero. */
public int iViewHeight;
/** If non-null, an encryption key to be used when loading the map. */
public byte[] iEncryptionKey;
/** The file buffer size in bytes. If it is zero or less the default value is used. */
public int iFileBufferSizeInBytes;
/** The maximum number of file buffers. If it is zero or less the default value is used. */
public int iMaxFileBufferCount;
/**
The number of levels of the text index to load into RAM.
Use values from 1 to 5 to save RAM but make text searches slower.
The value 0 causes the default number of levels (6) to be loaded.
The value -1 disables text index loading.
*/
public int iTextIndexLevels;
}
| mit |
lextel/evolution | fuel/app/classes/controller/v2admin/members.php | 6287 | <?php
class Controller_V2admin_Members extends Controller_V2admin{
public function action_index() {
$breads = [
['name' => '用户管理'],
['name' => '会员列表', 'href'=> Uri::create('v2admin/members')],
];
$get = Input::get();
$get['is_disable'] = 0;
$memberModel = new Model_Member();
$total = $memberModel->countMember($get);
$page = new \Helper\Page();
$url = Uri::create('v2admin/members',
['member_id' => Input::get('member_id'), 'nickname' => Input::get('nickname'), 'email' => Input::get('email')],
['user_id' => ':user_id', 'nickname' => ':nickname', 'email' => ':email']);
$config = $page->setConfig($url, $total, 'page');
$pagination = Pagination::forge('mypagination', $config);
$view = View::forge('v2admin/members/index');
$breadcrumb = new Helper\Breadcrumb();
$view->set_global('breadcrumb', $breadcrumb->breadcrumb($breads), false);
$get['offset'] = $pagination->offset;
$get['limit'] = $pagination->per_page;
$view->set('members', $memberModel->index($get));
$this->template->title = "会员列表 > 用户管理";
$this->template->content = $view;
}
//冻结
public function action_black() {
$breads = [
['name' => '用户管理'],
['name' => '冻结会员', 'href'=> Uri::create('v2admin/members/black')],
];
$get = Input::get();
$get['is_disable'] = 1;
$memberModel = new Model_Member();
$total = $memberModel->countMember($get);
$page = new \Helper\Page();
$url = Uri::create('v2admin/members/black',
['member_id' => Input::get('member_id'), 'nickname' => Input::get('nickname'), 'email' => Input::get('email')],
['user_id' => ':user_id', 'nickname' => ':nickname', 'email' => ':email']);
$config = $page->setConfig($url, $total, 'page');
$pagination = Pagination::forge('mypagination', $config);
$view = View::forge('v2admin/members/black');
$breadcrumb = new Helper\Breadcrumb();
$view->set_global('breadcrumb', $breadcrumb->breadcrumb($breads), false);
$get['offset'] = $pagination->offset;
$get['limit'] = $pagination->per_page;
$view->set('members', $memberModel->index($get));
$this->template->title = "冻结会员 > 用户管理";
$this->template->content = $view;
}
public function action_view($id = null)
{
$breads = [
['name' => '用户管理'],
['name' => '会员列表' , 'href' => Uri::create('v2admin/members')],
['name' => '查看用户'],
];
$member = Model_Member::find($id);
$view = View::forge('v2admin/members/view');
$breadcrumb = new Helper\Breadcrumb();
$view->set('member', $member);
$view->set_global('breadcrumb', $breadcrumb->breadcrumb($breads), false);
$this->template->title = "Member";
$this->template->content = $view;
}
// 冻结
public function action_disable($id = null) {
$memberModel = new Model_Member();
if ($memberModel->disable($id)) {
Session::set_flash('success', e('冻结会员成功 #' . $id));
} else {
Session::set_flash('error', e('冻结会员失败 #' . $id));
}
Response::redirect('v2admin/members');
}
// 解冻
public function action_enable($id = null) {
$memberModel = new Model_Member();
if ($memberModel->enable($id)) {
Session::set_flash('success', e('解冻会员成功 #' . $id));
} else {
Session::set_flash('error', e('解冻会员失败 #' . $id));
}
Response::redirect('v2admin/members');
}
// 后台发送会员站内信息VIEW页面
public function action_smsget($id = null){
$breads = [
['name' => '用户管理'],
['name' => '物流管理' , 'href' => Uri::create('v2admin/shipping')],
['name' => '虚拟商品发送'],
];
$member = Model_Member::find('first', ['where' =>
['is_delete' => '0', 'is_disable' => '0',
'id' => $id]]);
$view = View::forge('v2admin/members/sms');
$breadcrumb = new Helper\Breadcrumb();
$view->set('member', $member);
$view->set_global('breadcrumb', $breadcrumb->breadcrumb($breads), false);
$this->template->title = "Member";
$this->template->content = $view;
}
// 系统给会员发送信息
public function action_sms($id = null){
//检测会员是否存在
$member = Model_Member::find('first', ['where' =>
['is_delete' => '0', 'is_disable' => '0',
'id' => $id]]);
Session::set_flash('error', e('未发现用户 #' . $id));
if (!$member) return Response::redirect('v2admin/shipping');
$title = Input::post('sms');
if (empty(trim($title))) return Response::redirect('v2admin/members/smsget/' . $id);
$data = [
'owner_id' => $id,
'title' => $title,
'type' => 'note',
'user_id' => 0,
'user_name' => '系统',
];
$sms = new Model_Member_Sm($data);
$sms->save();
Session::set_flash('success', e('发送信息成功 #' . $id));
return Response::redirect('v2admin/sms');
}
// 会员删除
public function action_delete($id = null) {
$memberModel = new Model_Member();
if ($memberModel->remove($id)) {
Session::set_flash('success', e('删除成功 #' . $id));
} else {
Session::set_flash('error', e('删除失败 #' . $id));
}
Response::redirect('v2admin/members');
}
}
| mit |
gjtorikian/panino-docs | lib/panino/plugins/parsers/javascript/jsd/serializer.js | 6958 | var _ = require('underscore');
// Transforms Esprima AST into string
var to_s = exports.to_s = function(ast) {
switch (ast["type"]) {
case "Program":
return _.map(ast["body"], function(s) {
return to_s(s);
}).join();
// Statements
case "BlockStatement":
return "{" + _.map(ast["body"], function(s) { to_s(s) }).join() + "}";
case "BreakStatement":
return "break" + (ast["label"] ? " " + to_s(ast["label"]) : "") + ";";
case "ContinueStatement":
return "continue" + (ast["label"] ? " " + to_s(ast["label"]) : "") + ";";
case "DoWhileStatement":
return "do " + to_s(ast["body"]) + " while (" + to_s(ast["test"]) + ");";
case "DebuggerStatement":
return "debugger;";
case "EmptyStatement":
return ";";
case "ExpressionStatement":
return to_s(ast["expression"]) + ";";
case "ForStatement":
var init = ast["init"] ? to_s(ast["init"]).replace(/;$/, "") : ""
var test = ast["test"] ? to_s(ast["test"]) : "";
var update = ast["update"] ? to_s(ast["update"]) : "";
return "for (" + init + "; " + test + "; " + update + ") " + to_s(ast["body"]);
case "ForInStatement":
var left = to_s(ast["left"]).replace(/;$/, "");
var right = to_s(ast["right"]);
return "for (" + left + " in " + right + ") " + to_s(ast["body"]);
case "IfStatement":
var alternate = ast["alternate"] ? " else " + to_s(ast["alternate"]) : "";
return "if (" + to_s(ast["test"]) + ") " + to_s(ast["consequent"]) + alternate;
case "LabeledStatement":
return to_s(ast["label"]) + ": " + to_s(ast["body"]);
case "ReturnStatement":
var arg = ast["argument"] ? to_s(ast["argument"]) : "";
return "return " + arg + ";";
case "SwitchStatement":
return "switch (" + to_s(ast["discriminant"]) + ") {" + _.map(ast["cases"], function(c) { to_s(c) }).join() + "}";
case "SwitchCase":
var test = ast["test"] ? "case " + to_s(ast["test"]) : "default";
return test + ": " + _.map(ast["consequent"], function(c) { to_s(c) }).join();
case "ThrowStatement":
return "throw " + to_s(ast["argument"]) + ";";
case "TryStatement":
var handlers = _.map(ast["handlers"], function(h) { to_s(h) }).join();
var finalizer = ast["finalizer"] ? " finally " + to_s(ast["finalizer"]) : "";
return "try " + to_s(ast["block"]) + handlers + finalizer;
case "CatchClause":
var param = ast["param"] ? to_s(ast["param"]) : "";
return " catch (" + param + ") " + to_s(ast["body"]);
case "WhileStatement":
return "while (" + to_s(ast["test"]) + ") " + to_s(ast["body"]);
case "WithStatement":
return "with (" + to_s(ast["object"]) + ") " + to_s(ast["body"]);
// Declarations
case "FunctionDeclaration":
return func(ast);
case "VariableDeclaration":
return ast["kind"] + " " + list(ast["declarations"]) + ";";
case "VariableDeclarator":
if (ast["init"])
return to_s(ast["id"]) + " = " + to_s(ast["init"]);
else
return to_s(ast["id"]);
// Expressions
case "AssignmentExpression":
return parens(ast, ast["left"]) + " " + ast["operator"] + " " + to_s(ast["right"]);
case "ArrayExpression":
return "[" + list(ast["elements"]) + "]";
case "BinaryExpression":
return binary(ast);
case "CallExpression":
return serializeCall(ast);
case "ConditionalExpression":
return parens(ast, ast["test"]) + " ? " + to_s(ast["consequent"]) + " : " + to_s(ast["alternate"]);
case "FunctionExpression":
return func(ast);
case "LogicalExpression":
return binary(ast);
case "MemberExpression":
if (ast["computed"])
return parens(ast, ast["object"]) + "[" + to_s(ast["property"]) + "]";
else
return parens(ast, ast["object"]) + "." + to_s(ast["property"]);
case "NewExpression":
return "new " + serializeCall(ast);
case "ObjectExpression":
return "{" + list(ast["properties"]) + "}";
case "Property":
return to_s(ast["key"]) + ": " + to_s(ast["value"]);
case "SequenceExpression":
return list(ast["expressions"]);
case "ThisExpression":
return "this";
case "UnaryExpression":
return ast["operator"] + parens(ast, ast["argument"]);
case "UpdateExpression":
if (ast["prefix"])
return ast["operator"] + parens(ast, ast["argument"]);
else
return parens(ast, ast["argument"]) + ast["operator"];
// Basics
case "Identifier":
return ast["name"];
case "Literal":
return ast["raw"];
default:
console.trace();
throw new Error("Unknown node type: ", ast["type"]);
}
}
// serializes function declaration or expression
function func(ast) {
var params = list(ast["params"])
var id = ast["id"] ? to_s(ast["id"]) : ""
return "function " + id + "(" + params + ") " + to_s(ast["body"])
}
// serializes list of comma-separated items
function list(array) {
return _.map(array, function(x) { to_s(x) }).join(", ");
}
// serializes call- and new-expression
function serializeCall(ast) {
return parens(ast, ast["callee"]) + "(" + list(ast["arguments"]) + ")";
}
// Handles both binary- and logical-expression
function binary(ast) {
return parens(ast, ast["left"]) + " " + ast["operator"] + " " + parens(ast, ast["right"]);
}
// serializes child node and wraps it inside parenthesis if the
// precedence rules compared to parent node would require so.
function parens(parent, child) {
if (precedence(parent) >= precedence(child))
return to_s(child);
else
return "(" + to_s(child) + ")";
}
// Returns the precedence of operator represented by given AST node
function precedence(ast) {
var p = PRECEDENCE[ast["type"]];
if ( _.isNumber(p) ) // represents Fixnum? I'm so sorry.
return p;
else if ( p && p.constructor === Object ) // p is a {} object
return p[ast["operator"]];
else
return 0;
}
// Precedence rules of JavaScript operators.
//
// Taken from: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
//
var PRECEDENCE = {
"SequenceExpression" : 17,
"AssignmentExpression" : 16,
"ConditionalExpression" : 15,
"LogicalExpression" : {
"||" : 14,
"&&" : 13,
},
"BinaryExpression" : {
"|" : 12,
"^" : 11,
"&" : 10,
"==" : 9,
"!=" : 9,
"===" : 9,
"!==" : 9,
"<" : 8,
"<=" : 8,
">" : 8,
">=" : 8,
"in" : 8,
"instanceof" : 8,
"<<" : 7,
">>" : 7,
">>>" : 7,
"+" : 6,
"-" : 6,
"*" : 5,
"/" : 5,
"%" : 5,
},
"UnaryExpression" : 4,
"UpdateExpression" : 3,
"CallExpression" : 2,
"MemberExpression" : 1,
"NewExpression" : 1,
} | mit |
dematerializer/unicode-emoji-data | src/check-data.js | 1884 | const matchAnyTrailingVariationSelector = /\s(FE0E|FE0F)$/g;
export default function checkData({ data, reference }) {
const report = {
sequencesInDataButNotInReference: [],
sequencesInReferenceButNotInData: [],
};
report.sequencesInDataButNotInReference = data.reduce((sequencesInDataButNotInReference, datum) => {
// Compare insentitive to any trailing variation selector
// because I believe the use of trailing variation selectors
// in emoji-list.html does not represent current vendor support.
const sequence = datum.presentation.variation ? datum.presentation.variation.emoji : datum.presentation.default;
const sequenceWithoutVariation = sequence.replace(matchAnyTrailingVariationSelector, '');
const contains = reference.find(referenceSequence => referenceSequence.includes(sequenceWithoutVariation));
if (!contains) {
return [...sequencesInDataButNotInReference, sequence];
}
return sequencesInDataButNotInReference;
}, []);
report.sequencesInReferenceButNotInData = reference.reduce((sequencesInReferenceButNotInData, referenceSequence) => {
const referenceSequenceWithoutVariation = referenceSequence.replace(matchAnyTrailingVariationSelector, '');
const contains = data.find((datum) => {
// Compare insentitive to any trailing variation selector
// because I believe the use of trailing variation selectors
// in emoji-list.html does not represent current vendor support.
const sequence = datum.presentation.variation ? datum.presentation.variation.emoji : datum.presentation.default;
const sequenceWithoutVariation = sequence.replace(matchAnyTrailingVariationSelector, '');
return sequenceWithoutVariation.includes(referenceSequenceWithoutVariation);
});
if (!contains) {
return [...sequencesInReferenceButNotInData, referenceSequence];
}
return sequencesInReferenceButNotInData;
}, []);
return report;
}
| mit |
arelenglish/responsive-website-rails | db/schema.rb | 1761 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20140407033948) do
create_table "posts", force: true do |t|
t.string "title"
t.text "body"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "name"
t.string "photo"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
| mit |
Ruggedy-Limited/ruggedy-vma | resources/views/workspaces/create.blade.php | 1203 | @extends('layouts.main')
@section ('breadcrumb')
<a href="{{ route('home') }}">
<button type="button" class="btn round-btn pull-right c-yellow">
<i class="fa fa-times fa-lg" aria-hidden="true"></i>
</button>
</a>
{!! Breadcrumbs::render('dynamic') !!}
@endsection
@section('content')
<div class="row">
<div class="col-md-4 col-sm-4 animated fadeIn">
<h3>Add Workspace</h3>
<br>
{!! Form::open(['url' => route('workspace.store')]) !!}
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class' => 'black-form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('description', 'Description') !!}
{!! Form::textarea('description', null, ['class' => 'black-form-control', 'rows' => '3']) !!}
</div>
<button class="primary-btn" type="submit">Create Workspace</button>
{!! Form::close() !!}
</div>
<div class="col-md-2"></div>
<div class="col-md-6 animated fadeInUp">
</div>
</div>
@endsection
| mit |
fightinjoe/fightinjoe-merb-blog | app/controllers/users.rb | 477 | require File.join(File.dirname(__FILE__), '..', '..', "lib", "authenticated_system", "authenticated_dependencies")
class Users < Application
provides :xml
before :login_required
def new
only_provides :html
@user = User.new(params[:user] || {})
display @user
end
def create
cookies.delete :auth_token
@user = User.new(params[:user])
if @user.save
redirect_back_or_default('/')
else
render :new
end
end
end | mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.