language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 3,212 | 4.75 | 5 | [
"MIT"
] | permissive | # Lesson 2 - Types
#
# Most languages are "strictly typed" which means
# a variable can only hold one type of information.
# Basic types called primitive types. While the available primitive types
# can vary from language to language they are usually whole numbers, floating
# point numbers, boolean numbers, and *strings
def types():
# Ints are whole numbers that can be positive or negative
# In some languages the keyword unsigned can be used to specify
# if the variable can store negative values. Some languages use
# specifiers like long and short to specify how much data the value
# can use
val1: int = 10
# Floats are floating point numbers. Some languages have subtypes like
# decimal which uses a different way of representing the floating point
# number in memory. Some languages also allow unsigned to be used to designate
# if a floating point number can store negative values or not.
#
# Floating point numbers are very common, especially in game engines, but
# can be inaccurate due to how they have to be stored and how hardware can
# handle them. For example 12.5 can actually be 12.49999999999 in some systems.
# Due to this floating point numbers can accrue errors over time and are generally
# not good for systems that have to be deterministic.
val2: float = 12.3
# Bool or booleans represent values that can only be true or false.
val3: bool = True
val4: str = "This is a string. Strings represent a line of textual characters. They are usually " \
"used to display information, but due to their free form nature are also used to store" \
"random data (including images and other binary information at times)"
# If you try to preform an operation like add on values that are
# do not support adding together like string and bool you will get an
# exception
val1 = val4 + val3
pass
# Types like arrays, lists, maps, and objects are considered complex types. These types are usually
# more complex or larger in size then most primitive types
def complexTypes():
# Arrays hold a fixed number of elements of the same type. Their main advantage
# is they are very fast and efficient. Their main issue is they are of a fixed
# size.
#
# A variant of an array is called a list. Unlike arrays that are of fixed size,
# lists can change their size at run time. This comes at a cost of speed and
# efficiency
val1: list = [1, 2, 3, 4, 7]
# Most languages access elements on a 0 based index.
print(val1[0]) # Prints 1
print(val1[2]) # Prints 3
# Dictionary or maps are a type of collection that hold
# key value pairs. Unlike lists or arrays values are accessed
# via the assigned key. This makes them very flexible for data access
# when you have to care about the actual data you are accessing and can
# be just as fast as arrays for accessing but require more memory and
# can be hard to iterate through in some languages
val2: dict = {"testVal1": 100, "testVal2": 300}
print(val2["testVal2"]) # Prints 300
pass
if __name__ == '__main__':
types()
complexTypes()
|
C++ | UTF-8 | 1,091 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "PatternFinder.hpp"
#include "ObjectsStore.hpp"
#include "EngineClasses.hpp"
// This class contains the class which allows the generator access to global objects list.
class FUObjectItem
{
public:
UObject* Object;
int32_t Flags;
int32_t ClusterIndex;
int32_t SerialNumber;
};
class TUObjectArray
{
public:
FUObjectItem* Objects;
int32_t MaxElements;
int32_t NumElements;
};
class FUObjectArray
{
public:
int32_t Dummy1;
int32_t Dummy2;
int32_t Dummy3;
int32_t Dummy4;
TUObjectArray ObjObjects;
};
FUObjectArray* GlobalObjects = nullptr;
bool ObjectsStore::Initialize()
{
// TODO: Here you need to tell the class where the global object list is. You can use the function 'FindPattern()' to make this dynamic.
GlobalObjects = reinterpret_cast<decltype(GlobalObjects)>(0x12341234);
return true;
}
void* ObjectsStore::GetAddress()
{
return GlobalObjects;
}
size_t ObjectsStore::GetObjectsNum() const
{
return GlobalObjects->ObjObjects.NumElements;
}
UEObject ObjectsStore::GetById(size_t id) const
{
return GlobalObjects->ObjObjects.Objects[id].Object;
}
|
C++ | UTF-8 | 4,502 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "../utils.h"
#include "../plugin.h"
#include <libgfx/utility.h>
#include "render.h"
#include <fstream>
#include <cmath>
namespace CG {
class LSystem2D : public Plugin
{
public:
img::EasyImage image(const ini::Configuration &conf)
{
int size;
img::Color bgColor;
std::vector<double> lineColor;
std::string filename;
try {
size = conf["General"]["size"];
bgColor = extractColor(conf["General"]["backgroundcolor"]);
lineColor = conf["2DLSystem"]["color"];
filename = conf["2DLSystem"]["inputfile"].as_string_or_die();
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return img::EasyImage();
}
// parse L2D file
LParser::LSystem2D lSystem;
std::ifstream ifs(filename.c_str());
assert(ifs);
try {
ifs >> lSystem;
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return img::EasyImage();
}
ifs.close();
// convert LSystem2D to set of lines
GFX::Lines2D lines;
drawLSystem(lSystem, lines);
// set the line color
for (std::size_t i = 0; i < lines.size(); ++i)
lines[i].color = GFX::Color(lineColor);
return draw_lines(lines, size, bgColor);
}
private:
img::Color extractColor(const ini::Entry &entry) const
{
try {
std::vector<double> rgb = entry;
return img::Color(rgb.at(0) * 255, rgb.at(1) * 255, rgb.at(2) * 255);
} catch (const std::exception &e) {
std::cerr << "Could not parse color (using default black)" << std::endl;
}
return img::Color(0, 0, 0);
}
struct LSystemState
{
LSystemState(GFX::Real startingAngle) : angle(startingAngle)
{
}
void push()
{
stack.push_back(std::make_pair(angle, pos));
}
void pop()
{
angle = stack.back().first;
pos = stack.back().second;
stack.pop_back();
}
GFX::Real angle;
GFX::Point2D pos;
std::vector<std::pair<GFX::Real, GFX::Point2D> > stack;
};
void drawLSystem(const LParser::LSystem2D &lSystem, const std::string &commands, GFX::Lines2D &lines, int iteration, LSystemState &state)
{
if (iteration > 0) {
// recursive calls...
for (std::size_t i = 0; i < commands.size(); ++i)
switch (commands[i]) {
case '-':
state.angle -= GFX::deg2rad(lSystem.get_angle());
break;
case '+':
state.angle += GFX::deg2rad(lSystem.get_angle());
break;
case '(':
state.push();
break;
case ')':
state.pop();
break;
default:
drawLSystem(lSystem, lSystem.get_replacement(commands[i]), lines, iteration - 1, state);
}
} else {
// reached deepest recursive level -> draw the lines
for (std::size_t i = 0; i < commands.size(); ++i) {
switch (commands[i]) {
case '-':
state.angle -= GFX::deg2rad(lSystem.get_angle());
break;
case '+':
state.angle += GFX::deg2rad(lSystem.get_angle());
break;
case '(':
state.push();
break;
case ')':
state.pop();
break;
default:
{
// compute new position
GFX::Point2D newPos(state.pos.x + std::cos(state.angle), state.pos.y + std::sin(state.angle));
// draw a line?
if (lSystem.draw(commands[i]))
lines.push_back(GFX::Line2D(state.pos, newPos));
// move to new position
state.pos = newPos;
}
break;
}
}
}
}
void drawLSystem(const LParser::LSystem2D &lSystem, GFX::Lines2D &lines)
{
LSystemState state(GFX::deg2rad(lSystem.get_starting_angle()));
drawLSystem(lSystem, lSystem.get_initiator(), lines, lSystem.get_nr_iterations(), state);
}
};
PLUGIN_FACTORY("2DLSystem", LSystem2D)
}
|
Shell | UTF-8 | 403 | 3.109375 | 3 | [
"MIT"
] | permissive | #!/sbin/busybox sh
internal_sd="/data/media/0"
bak_dir=${internal_sd}/_appbak
echo "NOTICE: This tool should only be used to restore data after a Wipe."
echo "Your existing app/data will be overwritten!"
# Check for backup file
if [ ! -e ${bak_dir}/bak.tar.gz ]; then
echo Backup file not found. Exiting.
exit -1
fi
# Start restoring
echo Start restoring...
tar -zxvf ${bak_dir}/bak.tar.gz -C /
|
Java | UTF-8 | 675 | 3.375 | 3 | [] | no_license | package practice.ch15;
import confuse.ch15.FiveTuple;
class SixTuple<A, B, C, D, E, F> extends FiveTuple<A, B, C, D, E> {
public final F sixth;
public SixTuple(A a, B b, C c, D d, E e, F f) {
super(a, b, c, d, e);
sixth = f;
}
public String toString() {
return "(" + first + ", " + second + ", " + third + ", " + fourth +
", " + fifth + ", " + sixth + ")";
}
}
public class Practice3 {
public static void main(String[] args) {
SixTuple<Integer, String, Integer, Integer, Integer, Integer> sixTuple =
new SixTuple<>(1, "sdf", 2, 3, 4, 5);
System.out.println(sixTuple);
}
}
|
Java | UTF-8 | 1,099 | 2.046875 | 2 | [
"MIT",
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.net.http;
import android.os.SystemClock;
/**
* {@hide}
* Debugging tool
*/
class Timer {
private long mStart;
private long mLast;
public Timer() {
mStart = mLast = SystemClock.uptimeMillis();
}
public void mark(String message) {
long now = SystemClock.uptimeMillis();
if (HttpLog.LOGV) {
HttpLog.v(message + " " + (now - mLast) + " total " + (now - mStart));
}
mLast = now;
}
}
|
Markdown | UTF-8 | 2,454 | 2.953125 | 3 | [
"MIT"
] | permissive | # Blockchain Data
Blockchain has the potential to change the way that the world approaches data. Develop Blockchain skills by understanding the data model behind Blockchain by developing your own simplified private blockchain.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
### Prerequisites
Installing Node and NPM is pretty straightforward using the installer package available from the (Node.js® web site)[https://nodejs.org/en/].
This uses [ExpressJS](https://expressjs.com) which will be installed when running `npm install`. See configuration section below.
### Configuring your project
- Install requirements
```
npm install
```
- Run server
```
npm run dev
```
### Endpoints
#### ID Validation Request
##### Method
POST
##### Endpoint
http://localhost:8000/requestValidation
##### Paramaters
address - a valid bitcoin address
#### ID Signature Validation
##### Method
POST
##### Endpoint
http://localhost:8000/message-signature/validate
##### Paramaters
address - a valid bitcoin address
signature - a valid signed message using address and message from last step
#### Star Registration
##### Method
POST
##### Endpoint
http://localhost:8000/message-signature/validate
##### Paramaters
address - a valid bitcoin address
star - Containing dec, ra and story (max 500 bytes)
#### Get block by height
##### Method
GET
##### Endpoint
http://localhost:8000/block/:height
##### Paramaters
height- block height
#### Get block by address
##### Method
GET
##### Endpoint
http://localhost:8000/stars/address:address
##### Paramaters
address - address used for registration
#### Get block by hash
##### Method
GET
##### Endpoint
http://localhost:8000/stars/hash:hash
##### Paramaters
hash - hash of the block
#### Code of honor
Credits for resources that helped me finish the project:
- [ibrunotome](https://github.com/ibrunotome/udacity-blockchain-developer-nanodegree/tree/master/project4) from github, whose implementation of this project guided me along the way. I used some of ibrunotome's code as helper code especially with using express.js framework concepts.
- Udacity project 4 concepts section
- Stack Overflow [conversion to hex](https://stackoverflow.com/questions/20580045/javascript-character-ascii-to-hex) question
|
Ruby | UTF-8 | 1,802 | 2.75 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #define API for the data set
module SwitchBoard
class AbstractDataset
attr_accessor :persistance
def set_persistance(persistance)
@persistance = persistance
end
#Returns the next Model/ID that is available from the dataset
def get_next(limit = 1)
raise "#{__method__} not implemented in #{self.class.name}"
end
#get the IDs that are now locked by other lockers
def get_locked
raise "#{__method__} not implemented in #{self.class.name}"
end
#setup a new switchboard, a coordination persistence schema
def switchboard
raise "#{__method__} not implemented in #{self.class.name}"
end
#Add a new locker to the switchboard for future coordination
def register_locker(uid, name)
raise "#{__method__} not implemented in #{self.class.name}"
end
#list all the lockers registerd for this switchboard
def list_lockers
raise "#{__method__} not implemented in #{self.class.name}"
end
#list retrive data of a specific locker
def locker(uid)
raise "#{__method__} not implemented in #{self.class.name}"
end
#Set ID of an object as locked for a specific uid
def lock_id(locker_uid, id_to_lock, expire_in_sec = 60)
raise "#{__method__} not implemented in #{self.class.name}"
end
#Set ID of an object as locked for a specific uid
def unlock_id(locker_uid, id_to_unlock)
raise "#{__method__} not implemented in #{self.class.name}"
end
#Check to see if a certain ID is locked or not
def id_locked?(uid)
raise "#{__method__} not implemented in #{self.class.name}"
end
#Retrive all the locked ids in the switchboard
def get_all_locked_ids
raise "#{__method__} not implemented in #{self.class.name}"
end
end
end |
C | UTF-8 | 2,037 | 2.625 | 3 | [
"MIT"
] | permissive | #include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "textlandslide"
// mknod DEVICE_NAME c major minor
// The license type
MODULE_LICENSE("GPL");
// The author -- visible when you use modinfo
MODULE_AUTHOR("Surbhit Awasthi");
// The description -- modinfo
MODULE_DESCRIPTION("A character device LKM!");
// The version of the module
MODULE_VERSION("0.1");
static int dev_open(struct inode *, struct file *);
static int dev_release(struct inode *, struct file *);
static ssize_t dev_read(struct file *, char *, size_t, loff_t *);
static ssize_t dev_write(struct file *, const char *, size_t, loff_t *);
static struct file_operations fops = {
.open = dev_open,
.read = dev_read,
.write = dev_write,
.release = dev_release,
};
static int major;
static int __init code_init(void) {
major = register_chrdev(0, DEVICE_NAME, &fops);
if(major < 0) {
printk(KERN_ALERT "text landslide: load failed\n");
return major;
}
printk(KERN_INFO "text landslide module loaded: %d\n",major);
return 0;
}
static void __exit code_exit(void) {
unregister_chrdev(major, DEVICE_NAME);
printk(KERN_INFO "text landslide module has been unloaded\n");
}
static int dev_open(struct inode *inodep, struct file *filep) {
printk(KERN_INFO "text landslide device opened\n");
return 0;
}
static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, loff_t *offset) {
printk(KERN_INFO "Sorry, text landslide is read only\n");
return -EFAULT;
}
static int dev_release(struct inode *inodep, struct file *filep) {
printk(KERN_INFO "text landslide device closed\n");
return 0;
}
static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset) {
int errors = 0;
char *message = "linux kernel modules are cool... ";
int message_len = strlen(message);
errors = copy_to_user(buffer, message, message_len);
return errors == 0 ? message_len : -EFAULT;
}
module_init(code_init);
module_exit(code_exit);
|
C# | UTF-8 | 709 | 2.546875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace ORM.Entities
{
/// <summary>
/// This ORM entity represents a question which stores in the database.
/// </summary>
public class Question
{
public Question()
{
Answers = new List<Answer>();
}
public int Id { get; set; }
[ForeignKey("Theme")]
public int ThemeId { get; set; }
public virtual Theme Theme { get; set; }
public int? TestId { get; set; }
public string Text { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
} |
Markdown | UTF-8 | 3,209 | 3.109375 | 3 | [] | no_license | # ResponsiveDrawerDojoWidget
A Responsive Drawer Dojo Widget to be used with the ArcGIS JS API.
This Widget was designed to be used w/ an app that uses a full-width MapView or SceneView.
## Demos:
- Left-side drawer w/ header: https://chipdenton.github.io/ResponsiveDrawerDojoWidget/Demo/
- Left-side drawer w/o header: https://chipdenton.github.io/ResponsiveDrawerDojoWidget/Demo2/
- Right-side drawer w/o header: https://chipdenton.github.io/ResponsiveDrawerDojoWidget/Demo3/
## Notes:
* If using a MapView, use API 4.11! There is an issue with padding on MapViews in 4.12 that will cause issues with this widget. If you use a SceneView, then 4.12 should work without any issues.
* Due to the nature of this app, this app includes the following CSS that will affect your entire web page (but this shouldn't be an issue for a vast majority of web pages):
```
html, body {
padding: 0 !important;
margin: 0 !important;
height: 100% !important;
width: 100% !important;
}
```
* For the drawer and transparent overlay to work correctly, do NOT give your viewDiv a z-index CSS property/value
* Make sure to set the background-color and color properties of the div where the expand button is to be placed to match its surroundings or else it may look bad on your app w/ its default colors
* Set your viewDiv's height to 100% - height of header (ex: `height: calc(100% - 32px)`)
## To Use:
* Clone/copy the contents of ResponsiveDrawer.js and the folder ResponsiveDrawer (w/ its contents)
* Keep the folder and js file siblings to one another
* For the moment, you must manually link to the ResponsiveDrawer.css file in your main html file
* Import like any other dojo widget
* When initialized there are 2 required parameters and many optional parameters:
* REQUIRED:
* view -> a reference to the MapView/SceneView used in the app
* content -> HTML content that should appear in the the drawer
* OPTIONAL:
* container -> where the Expand Icon/Button should be located on DOM. If left out, the widget will be added to the top-left or top-right of view depending on the drawer's side.
* headerHeight: CSS string -> if you have a header on the page, use this to specify how tall it is so that the drawer knows how tall to be (defaults to '0px')
* backgroundColor: CSS string -> use this to specify a background color for the drawer. Useful to make it match a header. (defaults to 'white')
* color: CSS string -> use this to specify a color property for the drawer. Useful to make it match a header. (defaults to 'black')
* width: number -> how wide should the drawer be in pixels. (defaults to 220)
* sideBorder: CSS string -> use to style the drawer's right border on a left drawer or left border on a right drawer. Useful to make it match the bottomBorder of a header. (defaults to '0px solid black' aka no border)
* leftDrawer: boolean -> true = left-sided drawer; false = right-sided drawer (defaults to true)
* If you have any content in your app/header that you don't want shown when on a tablet or a phone; give those elements the convience classes of 'hide-on-tablet' or 'hide-on-phone'
## Please let me know if you have any problems or suggestions!
|
SQL | UTF-8 | 793 | 3.28125 | 3 | [] | no_license | create table users (
id bigserial primary key,
email text not null unique
);
create table vacation_requests (
id bigserial primary key,
user_id bigint not null references users(id),
vacation_type text not null check (vacation_type in ('Yearly')),
start_date date not null,
end_date date not null,
substitute text, -- замена на период отпуска
status text not null check (status in ('New', 'Declined', 'Accepted', 'Sent', 'Vacation')),
decline_reason varchar(1000)
);
-- default naming conventions https://gist.github.com/popravich/d6816ef1653329fb1745
create index vr_user_id_end_date_idx on vacation_requests(user_id, end_date);
create index vr_status_start_date_idx on vacation_requests(status, start_date); |
Java | UTF-8 | 238 | 2.0625 | 2 | [] | no_license | /**
*
*/
package br.com.alura.designpatterns.cap6;
import java.util.Calendar;
/**
* @author eltonf
*
*/
public class CalendarSistema implements Relogio {
@Override
public Calendar hoje() {
return Calendar.getInstance();
}
}
|
Java | UTF-8 | 16,402 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pig.test.utils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.joda.time.DateTime;
import org.apache.pig.ResourceSchema;
import org.apache.pig.ResourceSchema.ResourceFieldSchema;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;
import org.apache.pig.data.DefaultBagFactory;
import org.apache.pig.data.DefaultTuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.data.Tuple;
public class GenRandomData {
public static ResourceFieldSchema getRandMapFieldSchema() throws IOException {
ResourceFieldSchema bytefs = new ResourceFieldSchema();
bytefs.setType(DataType.BYTEARRAY);
ResourceSchema mapSchema = new ResourceSchema();
mapSchema.setFields(new ResourceFieldSchema[]{bytefs});
ResourceFieldSchema mapfs = new ResourceFieldSchema();
mapfs.setSchema(mapSchema);
mapfs.setType(DataType.MAP);
return mapfs;
}
public static Map<String, Object> genRandMap(Random r, int numEnt) {
Map<String,Object> ret = new HashMap<String, Object>();
if(r==null){
ret.put("random", "RANDOM");
return ret;
}
for(int i=0;i<numEnt;i++){
ret.put(genRandString(r), new DataByteArray(genRandString(r).getBytes()));
}
return ret;
}
public static String genRandString(Random r){
if(r==null) return "RANDOM";
char[] chars = new char[10];
for(int i=0;i<10;i++){
chars[i] = (char)(r.nextInt(26)+65);
}
return new String(chars);
}
public static String genRandLargeString(Random r, int size){
if(r==null) return "RANDOM";
if(size <= 10) return genRandString(r);
char[] chars = new char[size];
for(int i=0;i<size;i++){
chars[i] = (char)(r.nextInt(26)+65);
}
return new String(chars);
}
public static DataByteArray genRandDBA(Random r){
if(r==null) return new DataByteArray("RANDOM".getBytes());
byte[] bytes = new byte[10];
r.nextBytes(bytes);
return new DataByteArray(bytes);
}
public static DataByteArray genRandTextDBA(Random r){
if(r==null) return new DataByteArray("RANDOM".getBytes());
return new DataByteArray(genRandString(r).getBytes());
}
public static ResourceFieldSchema getSmallTupleFieldSchema() throws IOException{
ResourceFieldSchema stringfs = new ResourceFieldSchema();
stringfs.setType(DataType.CHARARRAY);
ResourceFieldSchema intfs = new ResourceFieldSchema();
intfs.setType(DataType.INTEGER);
ResourceSchema tupleSchema = new ResourceSchema();
tupleSchema.setFields(new ResourceFieldSchema[]{stringfs, intfs});
ResourceFieldSchema tuplefs = new ResourceFieldSchema();
tuplefs.setSchema(tupleSchema);
tuplefs.setType(DataType.TUPLE);
return tuplefs;
}
public static Tuple genRandSmallTuple(Random r, int limit){
if(r==null){
Tuple t = new DefaultTuple();
t.append("RANDOM");
return t;
}
Tuple t = new DefaultTuple();
t.append(genRandString(r));
t.append(r.nextInt(limit));
return t;
}
public static Tuple genRandSmallTuple(String s, Integer value){
Tuple t = new DefaultTuple();
t.append(s);
t.append(value);
return t;
}
public static DataBag genRandSmallTupDataBagWithNulls(Random r, int num, int limit){
if(r==null) {
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
Tuple t = new DefaultTuple();
t.append("RANDOM");
db.add(t);
return db;
}
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
for(int i=0;i<num;i++){
// the first tuple is used as a sample tuple
// in some tests to deduce return type - so
// don't introduce nulls into first tuple
if(i == 0) {
db.add(genRandSmallTuple(r, limit));
continue;
} else {
int rand = r.nextInt(num);
if(rand <= (0.2 * num) ) {
db.add(genRandSmallTuple((String)null, rand));
} else if (rand > (0.2 * num) && rand <= (0.4 * num)) {
db.add(genRandSmallTuple(genRandString(r), null));
} else if (rand > (0.4 * num) && rand <= (0.6 * num)) {
db.add(genRandSmallTuple(null, null));
} else {
db.add(genRandSmallTuple(r, limit));
}
}
}
return db;
}
public static ResourceFieldSchema getSmallTupDataBagFieldSchema() throws IOException {
ResourceFieldSchema tuplefs = getSmallTupleFieldSchema();
ResourceSchema bagSchema = new ResourceSchema();
bagSchema.setFields(new ResourceFieldSchema[]{tuplefs});
ResourceFieldSchema bagfs = new ResourceFieldSchema();
bagfs.setSchema(bagSchema);
bagfs.setType(DataType.BAG);
return bagfs;
}
public static DataBag genRandSmallTupDataBag(Random r, int num, int limit){
if(r==null) {
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
Tuple t = new DefaultTuple();
t.append("RANDOM");
db.add(t);
return db;
}
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
for(int i=0;i<num;i++){
db.add(genRandSmallTuple(r, limit));
}
return db;
}
public static Tuple genRandSmallBagTuple(Random r, int num, int limit){
if(r==null){
Tuple t = new DefaultTuple();
t.append("RANDOM");
return t;
}
Tuple t = new DefaultTuple();
t.append(genRandSmallTupDataBag(r, num, limit));
t.append(genRandDBA(r));
t.append(genRandString(r));
t.append(r.nextDouble());
t.append(r.nextFloat());
t.append(r.nextInt());
t.append(r.nextLong());
t.append(genRandMap(r, num));
t.append(genRandSmallTuple(r, 100));
t.append(new Boolean(r.nextBoolean()));
t.append(new DateTime(r.nextLong()));
return t;
}
public static ResourceFieldSchema getSmallBagTextTupleFieldSchema() throws IOException{
ResourceFieldSchema dbafs = new ResourceFieldSchema();
dbafs.setType(DataType.BYTEARRAY);
ResourceFieldSchema stringfs = new ResourceFieldSchema();
stringfs.setType(DataType.CHARARRAY);
ResourceFieldSchema intfs = new ResourceFieldSchema();
intfs.setType(DataType.INTEGER);
ResourceFieldSchema bagfs = getSmallTupDataBagFieldSchema();
ResourceFieldSchema floatfs = new ResourceFieldSchema();
floatfs.setType(DataType.FLOAT);
ResourceFieldSchema doublefs = new ResourceFieldSchema();
doublefs.setType(DataType.DOUBLE);
ResourceFieldSchema longfs = new ResourceFieldSchema();
longfs.setType(DataType.LONG);
ResourceFieldSchema mapfs = new ResourceFieldSchema();
mapfs.setType(DataType.MAP);
ResourceFieldSchema tuplefs = getSmallTupleFieldSchema();
ResourceFieldSchema boolfs = new ResourceFieldSchema();
boolfs.setType(DataType.BOOLEAN);
ResourceFieldSchema dtfs = new ResourceFieldSchema();
dtfs.setType(DataType.DATETIME);
ResourceSchema outSchema = new ResourceSchema();
outSchema.setFields(new ResourceFieldSchema[]{bagfs, dbafs, stringfs, doublefs, floatfs,
intfs, longfs, mapfs, tuplefs, boolfs, dtfs});
ResourceFieldSchema outfs = new ResourceFieldSchema();
outfs.setSchema(outSchema);
outfs.setType(DataType.TUPLE);
return outfs;
}
public static Tuple genRandSmallBagTextTuple(Random r, int num, int limit){
if(r==null){
Tuple t = new DefaultTuple();
t.append("RANDOM");
return t;
}
Tuple t = new DefaultTuple();
t.append(genRandSmallTupDataBag(r, num, limit));
//TODO Fix
//The text representation of byte array and char array
//cannot be disambiguated without annotation. For now,
//the tuples will not contain byte array
t.append(genRandTextDBA(r));
t.append(genRandString(r));
t.append(r.nextDouble());
t.append(r.nextFloat());
t.append(r.nextInt());
t.append(r.nextLong());
t.append(genRandMap(r, num));
t.append(genRandSmallTuple(r, 100));
t.append(new Boolean(r.nextBoolean()));
t.append(new DateTime(r.nextLong()));
return t;
}
public static DataBag genRandFullTupDataBag(Random r, int num, int limit){
if(r==null) {
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
Tuple t = new DefaultTuple();
t.append("RANDOM");
db.add(t);
return db;
}
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
for(int i=0;i<num;i++){
db.add(genRandSmallBagTuple(r, num, limit));
}
return db;
}
public static ResourceFieldSchema getFullTupTextDataBagFieldSchema() throws IOException{
ResourceFieldSchema tuplefs = getSmallBagTextTupleFieldSchema();
ResourceSchema outBagSchema = new ResourceSchema();
outBagSchema.setFields(new ResourceFieldSchema[]{tuplefs});
ResourceFieldSchema outBagfs = new ResourceFieldSchema();
outBagfs.setSchema(outBagSchema);
outBagfs.setType(DataType.BAG);
return outBagfs;
}
public static DataBag genRandFullTupTextDataBag(Random r, int num, int limit){
if(r==null) {
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
Tuple t = new DefaultTuple();
t.append("RANDOM");
db.add(t);
return db;
}
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
for(int i=0;i<num;i++){
db.add(genRandSmallBagTextTuple(r, num, limit));
}
return db;
}
public static Tuple genRandSmallBagTupleWithNulls(Random r, int num, int limit){
if(r==null){
Tuple t = new DefaultTuple();
t.append("RANDOM");
return t;
}
Tuple t = new DefaultTuple();
t.append(genRandSmallTupDataBag(r, num, limit));
t.append(genRandDBA(r));
t.append(genRandString(r));
t.append(r.nextDouble());
t.append(r.nextFloat());
t.append(r.nextInt());
t.append(r.nextLong());
t.append(genRandMap(r, num));
t.append(genRandSmallTuple(r, 100));
t.append(new Boolean(r.nextBoolean()));
t.append(new DateTime(r.nextLong()));
t.append(null);
return t;
}
public static Tuple genRandSmallBagTextTupleWithNulls(Random r, int num, int limit){
if(r==null){
Tuple t = new DefaultTuple();
t.append("RANDOM");
return t;
}
Tuple t = new DefaultTuple();
t.append(genRandSmallTupDataBag(r, num, limit));
//TODO Fix
//The text representation of byte array and char array
//cannot be disambiguated without annotation. For now,
//the tuples will not contain byte array
t.append(genRandTextDBA(r));
t.append(genRandString(r));
t.append(r.nextDouble());
t.append(r.nextFloat());
t.append(r.nextInt());
t.append(r.nextLong());
t.append(genRandMap(r, num));
t.append(genRandSmallTuple(r, 100));
t.append(new Boolean(r.nextBoolean()));
t.append(new DateTime(r.nextLong()));
t.append(null);
return t;
}
public static DataBag genFloatDataBag(Random r, int column, int row) {
DataBag db = DefaultBagFactory.getInstance().newDefaultBag();
for (int i=0;i<row;i++) {
Tuple t = TupleFactory.getInstance().newTuple();
for (int j=0;j<column;j++) {
t.append(r.nextFloat()*1000);
}
db.add(t);
}
return db;
}
public static ResourceFieldSchema getFloatDataBagFieldSchema(int column) throws IOException {
ResourceFieldSchema intfs = new ResourceFieldSchema();
intfs.setType(DataType.INTEGER);
ResourceSchema tupleSchema = new ResourceSchema();
ResourceFieldSchema[] fss = new ResourceFieldSchema[column];
for (int i=0;i<column;i++) {
fss[i] = intfs;
}
tupleSchema.setFields(fss);
ResourceFieldSchema tuplefs = new ResourceFieldSchema();
tuplefs.setSchema(tupleSchema);
tuplefs.setType(DataType.TUPLE);
ResourceSchema bagSchema = new ResourceSchema();
bagSchema.setFields(new ResourceFieldSchema[]{tuplefs});
ResourceFieldSchema bagfs = new ResourceFieldSchema();
bagfs.setSchema(bagSchema);
bagfs.setType(DataType.BAG);
return bagfs;
}
public static Tuple genMixedTupleToConvert(Random r) {
Tuple t = TupleFactory.getInstance().newTuple();
t.append(r.nextInt());
t.append(r.nextInt());
long l = 0;
while (l<=Integer.MAX_VALUE && l>=Integer.MIN_VALUE)
l = r.nextLong();
t.append(l);
t.append(r.nextFloat()*1000);
t.append(r.nextDouble()*10000);
t.append(genRandString(r));
t.append("K"+genRandString(r));
t.append("K"+genRandString(r));
t.append("K"+genRandString(r));
if (r.nextFloat()>0.5)
t.append("true");
else
t.append("false");
t.append(new DateTime(r.nextLong()));
return t;
}
public static ResourceFieldSchema getMixedTupleToConvertFieldSchema() throws IOException {
ResourceFieldSchema stringfs = new ResourceFieldSchema();
stringfs.setType(DataType.CHARARRAY);
ResourceFieldSchema intfs = new ResourceFieldSchema();
intfs.setType(DataType.INTEGER);
ResourceFieldSchema longfs = new ResourceFieldSchema();
longfs.setType(DataType.LONG);
ResourceFieldSchema floatfs = new ResourceFieldSchema();
floatfs.setType(DataType.FLOAT);
ResourceFieldSchema doublefs = new ResourceFieldSchema();
doublefs.setType(DataType.DOUBLE);
ResourceFieldSchema boolfs = new ResourceFieldSchema();
boolfs.setType(DataType.BOOLEAN);
ResourceFieldSchema dtfs = new ResourceFieldSchema();
dtfs.setType(DataType.DATETIME);
ResourceSchema tupleSchema = new ResourceSchema();
tupleSchema.setFields(new ResourceFieldSchema[]{stringfs, longfs, intfs, doublefs, floatfs, stringfs, intfs, doublefs, floatfs, boolfs, dtfs});
ResourceFieldSchema tuplefs = new ResourceFieldSchema();
tuplefs.setSchema(tupleSchema);
tuplefs.setType(DataType.TUPLE);
return tuplefs;
}
}
|
C++ | UTF-8 | 356 | 2.625 | 3 | [] | no_license | #include<stdio.h>
void nhap(int a[],int &n)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
}
int so(int a)
{
if(a%2==0) return 1;
return 0;
}
int kq(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
if(so(a[i])==so(a[i+1])) return i+1;
}
return -1;
}
int main()
{
int a[101],n;
nhap(a,n);
int ans=kq(a,n);
printf("%d",ans);
return 0;
}
|
Java | UTF-8 | 4,747 | 2.4375 | 2 | [] | no_license | /*
This file is part of the BlueJ program.
Copyright (C) 1999-2009,2010,2013,2016 Michael Kolling and John Rosenberg
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
This file is subject to the Classpath exception as provided in the
LICENSE.txt file that accompanied this code.
*/
package bluej.graph;
import java.util.*;
import bluej.pkgmgr.Package;
import bluej.pkgmgr.target.Target;
import bluej.utility.Debug;
import javafx.application.Platform;
import javafx.scene.shape.Rectangle;
import threadchecker.OnThread;
import threadchecker.Tag;
/**
* The diagram's marquee (a rectangular drag area for selecting graph elements).
*
* @author fisker
* @author Michael Kolling
*/
@OnThread(Tag.FXPlatform)
public final class Marquee
{
private final Package graph;
private int drag_start_x, drag_start_y;
private Rectangle currentRect;
private final SelectionSet selected;
private boolean active = false;
private final ArrayList<Target> previouslySelected = new ArrayList<>();
/**
* Create a marquee for a given graph.
*/
public Marquee(Package graph, SelectionSet selection)
{
this.graph = graph;
this.selected = selection;
currentRect = new Rectangle();
currentRect.setVisible(false);
}
/**
* Start a marquee selection at point x, y.
*/
public void start(int x, int y)
{
previouslySelected.clear();
previouslySelected.addAll(selected.getSelected());
drag_start_x = x;
drag_start_y = y;
currentRect.setX(x);
currentRect.setY(y);
currentRect.setWidth(0);
currentRect.setHeight(0);
currentRect.setVisible(false);
active = true;
}
/**
* Place the marquee from its starting point to the coordinate (drag_x,
* drag_y). The marquee must have been started before this method is called.
*
* @param drag_x The x coordinate of the current drag position
* @param drag_y The y coordinate of the current drag position
* @return The set of graph elements selected by this marquee
*/
public void move(int drag_x, int drag_y)
{
int x = drag_start_x;
int y = drag_start_y;
int w = drag_x - drag_start_x;
int h = drag_y - drag_start_y;
//Rectangle can't handle negative numbers, modify coordinates
if (w < 0)
x = x + w;
if (h < 0)
y = y + h;
w = Math.abs(w);
h = Math.abs(h);
currentRect.setX(x);
currentRect.setY(y);
currentRect.setWidth(w);
currentRect.setHeight(h);
if (w != 0 || h != 0)
{
currentRect.setVisible(true);
}
findSelectedVertices(x, y, w, h);
}
/**
* Find, and add, all vertices that intersect the specified area.
*/
private void findSelectedVertices(int x, int y, int w, int h)
{
//clear the currently selected
selected.clear();
selected.addAll(previouslySelected);
//find the intersecting vertices
for (Target v : graph.getVertices()) {
if (v.getBoundsInEditor().intersects(x, y, w, h)) {
selected.add(v);
}
}
// If none of them are focused, focus one, otherwise keyboard
// actions won't work:
if (!selected.isEmpty() && !selected.getSelected().stream().anyMatch(Target::isFocused))
selected.getAnyVertex().requestFocus();
}
/**
* Stop a current marquee selection.
*/
public void stop()
{
currentRect.setVisible(false);
active = false;
}
/**
* Tell whether this marquee is currently active.
*/
public boolean isActive()
{
return active;
}
/**
* Return the currently visible rectangle of this marquee.
* If the marquee is not currently drawn, return null.
*
* @return The marquee's rectangle, or null if not visible.
*/
public Rectangle getRectangle()
{
return currentRect;
}
} |
Java | UTF-8 | 3,583 | 2.25 | 2 | [] | no_license | /*
* 所有权归603实验室所有
*/
package edu.hdu.lab.services.impl;
import edu.hdu.lab.mapper.LifeMapper;
import edu.hdu.lab.pojo.Life;
import edu.hdu.lab.pojo.LifeExample;
import edu.hdu.lab.services.LifeService;
import edu.hdu.lab.utils.Constants;
import edu.hdu.lab.utils.LocationUtils;
import edu.hdu.lab.utils.WebUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author justin
*/
@Service("LifeService")
public class LifeServiceImpl
implements LifeService{
private Logger logger = Logger.getLogger(this.getClass());
@Autowired
private LifeMapper lifeMapper;
public List<Life> getAllLifeInfos() {
return
lifeMapper.selectByExample(new LifeExample());
}
public List<Life> getLifeInfosByParams(Map<String, Object> paramsMap) {
List<Life> lifeList = lifeMapper.getLifeInfoByParams(paramsMap);
String distance = WebUtils.ifNull(paramsMap.get(Constants.LIFE_PARAM_DISTANCE), "").toString();
String myLocation = WebUtils.ifNull(paramsMap.get(Constants.LIFE_PARAM_MYLOCATION), "").toString();
List<Life> resultList = null;
if (distance.equals("") || myLocation.equals(""))
resultList = lifeList;
else {
resultList = new ArrayList<Life>();
try {
//按照所要求的距离限制进行筛选
for (Life e : lifeList) {
Double myLongitude = Double.valueOf(myLocation.split(Constants.LOCATION_SEPERATOR)[0]);
Double myLatitude = Double.valueOf(myLocation.split(Constants.LOCATION_SEPERATOR)[1]);
Double eLongitude = Double.valueOf(e.getLocation().split(Constants.LOCATION_SEPERATOR)[0]);
Double eLatitude = Double.valueOf(e.getLocation().split(Constants.LOCATION_SEPERATOR)[1]);
Double realDistance = LocationUtils.getDistanceBetweenPlaces(myLongitude, myLatitude, eLongitude, eLatitude);
Double requestedDistance = Double.valueOf(distance);
logger.debug("realDistance=" + realDistance);
if (realDistance <= requestedDistance) {
e.setDistance(realDistance);
resultList.add(e);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.info("Distance Calculation Failed! distance=" + distance + " myLocation=" + myLocation);
}
}
return resultList;
}
public int addLife(Life life) {
return
lifeMapper.insert(life);
}
public int deleteLife(int id) {
return
lifeMapper.deleteByPrimaryKey(id);
}
public int updateLife(Life life) {
return
lifeMapper.updateByPrimaryKeySelective(life);
}
public int addDiscount(int id, String discountTexts) {
Life life = new Life();
life.setDiscount(discountTexts);
life.setId(id);
return updateLife(life);
}
public int updateDiscount(int id, String discountTexts) {
return
addDiscount(id, discountTexts);
}
public int deleteDiscount(int id) {
return
updateDiscount(id, "");
}
}
|
TypeScript | UTF-8 | 2,183 | 2.78125 | 3 | [] | no_license | import { TOGGLE_SHOW_FILTER } from "./demo.actions";
import { UPDATE_FOOD } from "./demo.actions";
//Do NOT Delete this import
import { DemoActions, DemoActionTypes } from "./demo.actions.creator";
import { DemoState, initialDemoState } from "./store";
//Change import in demos.modules.ts to use this:
// import { demo_slice, reducer } from "./state/demo.reducer.typed";
//Reducer
//TODO: Use this until before Action Creators
// export function reducer(state: DemoState = initialDemoState, action) {
// switch (action.type) {
// case TOGGLE_SHOW_FILTER:
// {
// return {
// ...state,
// showFilter: action.payload
// };
// }
// break;
// case UPDATE_FOOD:
// {
// return {
// ...state,
// favFood: action.payload
// };
// }
// break;
// default:
// return state;
// }
//TODO: Use this until starting with Action Creators
export function reducer(
state: DemoState = initialDemoState,
action: DemoActions
) {
switch (action.type) {
case DemoActionTypes.ToggleShowFilter: {
return {
...state,
showFilter: action.payload
};
}
case DemoActionTypes.UpdateFood: {
return {
...state,
favFood: action.payload
};
}
case DemoActionTypes.SetCurrentVoucher: {
return {
...state,
currVoucherId: action.payload
};
}
case DemoActionTypes.ClearCurrentVoucher: {
return {
...state,
currVoucherId: null
};
}
case DemoActionTypes.InitializeVoucher: {
return {
...state,
currVoucherId: 0
};
}
case DemoActionTypes.LoadSuccess: {
return {
...state,
vouchers: action.payload
};
}
case DemoActionTypes.DeleteVoucherSuccess:
return {
...state,
products: state.vouchers.filter(v => v.ID !== action.payload),
currentProductId: null,
error: ""
};
case DemoActionTypes.DeleteVoucherErr:
return {
...state,
error: action.payload
};
default:
return state;
}
}
|
Go | UTF-8 | 463 | 3.265625 | 3 | [] | no_license | package main
import "fmt"
func main(){
var nilai32 int32 = 128
var nilai64 int64 = int64(nilai32)
//overflow
var nilai8 int8 = int8(nilai32)
fmt.Println(nilai32)
fmt.Println(nilai64)
fmt.Println(nilai8)
//String Conversion
var kata = "ABC"
//Automatically set to byte because the ascii number < 128, in this case only
//var ascii = huruf[0] OR ascii := huruf[0]
var ascii byte = kata[0]
var huruf = string(ascii)
fmt.Println(huruf)
}
|
Java | UTF-8 | 3,575 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | /**
*
*/
package com.ouchat.xmpplistener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.carbons.Carbon;
import org.jivesoftware.smackx.carbons.CarbonManager;
import org.jivesoftware.smackx.packet.DelayInfo;
import com.ouchat.smack.SmackImpl;
import com.ouchat.util.Logout;
import com.way.db.ChatProvider.ChatConstants;
/**
* @ClassName: XmppMessageListener
* @Description: TODO 处理消息的
* @author ou
* @date 2014年12月5日 下午1:37:57
*
*/
public class XmppMessageListener implements PacketListener {
SmackImpl mSmack;
public XmppMessageListener(SmackImpl smack) {
mSmack = smack;
};
/*
* (non-Javadoc)
*
* @see
* org.jivesoftware.smack.PacketListener#processPacket(org.jivesoftware.
* smack.packet.Packet)
*/
@Override
public void processPacket(Packet arg0) {
try {
if (arg0 instanceof Message) {// 如果是消息类型
Message msg = (Message) arg0;
String chatMessage = msg.getBody();
Logout.d("ouou", "11收到的新消息处理 :" + msg.toXML());
// try to extract a carbon
Carbon cc = CarbonManager.getCarbon(msg);
if (cc != null
&& cc.getDirection() == Carbon.Direction.received) {// 收到的消息
Logout.d("ouou", "收到的新消息处理 :" + cc.toXML());
msg = (Message) cc.getForwarded().getForwardedPacket();
chatMessage = msg.getBody();
// fall through
} else if (cc != null
&& cc.getDirection() == Carbon.Direction.sent) {// 如果是自己发送的消息,则添加到数据库后直接返回
Logout.d("ouou", "我大宋的消息处理 :" + cc.toXML());
msg = (Message) cc.getForwarded().getForwardedPacket();
chatMessage = msg.getBody();
if (chatMessage == null)
return;
String fromJID = mSmack.getJabberID(msg.getTo());
mSmack.addChatMessageToDB(ChatConstants.OUTGOING, fromJID,
chatMessage, ChatConstants.DS_SENT_OR_READ,
System.currentTimeMillis(), msg.getPacketID(), "");
// always return after adding
return;// 记得要返回
}
if (chatMessage == null) {
return;// 如果消息为空,直接返回了
}
if (msg.getType() == Message.Type.error) {
chatMessage = "<Error> " + chatMessage;// 错误的消息类型
}
long ts;// 消息时间戳
DelayInfo timestamp = (DelayInfo) msg.getExtension("delay",
"urn:xmpp:delay");
if (timestamp == null)
timestamp = (DelayInfo) msg.getExtension("x",
"jabber:x:delay");
if (timestamp != null)
ts = timestamp.getStamp().getTime();
else
ts = System.currentTimeMillis();
String fromJID = mSmack.getJabberID(msg.getFrom());// 消息来自对象
Object object = msg.getProperty(ChatConstants.NICKNAME);
String nickNameString = "";
if (object != null) {
nickNameString = (String) object;
}
mSmack.addChatMessageToDB(ChatConstants.INCOMING, fromJID,
chatMessage, ChatConstants.DS_NEW, ts,
msg.getPacketID(), nickNameString);// 存入数据库,并标记为新消息DS_NEW
mSmack.getService().newMessage(fromJID, chatMessage);// 通知service,处理是否需要显示通知栏,
}
} catch (Exception e) {
// SMACK silently discards exceptions dropped from
// processPacket :(
Logout.e("failed to process packet:");
e.printStackTrace();
}
}
}
|
Python | UTF-8 | 5,141 | 3.03125 | 3 | [] | no_license | import gensim
import gensim.downloader as api
from sklearn.cluster import DBSCAN, KMeans
import numpy
import time
class Model:
def __init__(self, data_path):
start = time.time()
# https://radimrehurek.com/gensim/models/word2vec.html
print("Loading model", data_path)
# https://github.com/RaRe-Technologies/gensim-data
self.model: gensim.models.KeyedVectors = api.load(data_path)
end = time.time()
print("Model loaded in", end - start, "seconds")
def words_to_vectors(self, words):
return [self.model.get_vector(w) for w in words]
def group_clusters(self, words, labelled_vectors):
clusters = {}
for index, label in enumerate(labelled_vectors.tolist()):
if str(label) not in clusters:
clusters[str(label)] = []
clusters[str(label)].append(words[index])
return list(clusters.values())
def cluster(self, words, guess):
print("Default clustering for", words)
cluster = words.copy()
while len(cluster) > min(guess, len(words)):
no_match = self.model.doesnt_match(cluster)
cluster.remove(no_match)
# print("cluster", cluster)
# return numpy.array([(c, 0) for c in cluster])
return cluster
def average_group_similarity(self, words):
return numpy.mean([self.model.similarity(x, y) for x in words for y in words if x is not y])
def rank_clusters(self, clusters):
return [self.average_group_similarity(v) if len(v) > 1 else 0 for v in clusters]
def get_most_similar_cluster(self, clusters):
ranked = self.rank_clusters(clusters)
return clusters[ranked.index(max(ranked))]
# def find_matches(self, positive, negative):
# # https://radimrehurek.com/gensim/models/keyedvectors.html
# # TODO: adding negatives seems to bias model against ENGLISH, find english only model
# return self.model.most_similar(negative=negative, topn=10)
# # return self.model.most_similar(positive, topn=10)
def filter_words(self, matches, board):
# remove words that are superstrings of words on the board or have spaces
filtered = [m for m in matches if "_" not in m and not board.is_superstring(m)]
# TODO: remove function words?
# might be useful: https://github.com/dariusk/corpora/tree/master/data/words
return filtered
def find_farthest_word(self, matches, negative_words):
distances = [(m, self.model.distances(m, negative_words)) for m in matches]
farthest = max(distances, key=lambda k: numpy.mean(k[1]))
return farthest[0]
def find_most_similar(self, words):
similar = self.model.most_similar(positive=words, topn=10)
return [s[0] for s in similar]
def run(self, board):
words = board.get_good_options()
# 1. find best cluster of options
best_cluster = self.cluster(words, board.guess)
# grouped = self.group_clusters(words, clusters)
# print("Clusters of size > 1:")
# for c in [cluster for cluster in grouped if len(cluster) > 1]:
# print(c)
# best_cluster = self.get_most_similar_cluster(grouped)
print("For cluster", best_cluster)
# 2. find matches for cluster
# sorted_words = board.sort(best_cluster)
matches = self.find_most_similar(best_cluster)
# 3. filter/sanitize matches
filtered = self.filter_words(matches, board)
print("Filtered matches:", filtered)
# 4. return match thats farthest from the negative words
farthest = self.find_farthest_word(filtered, board.get_bad_options())
print("GUESS:", farthest)
class KMeansModel(Model):
def __init__(self, data_path, cluster_size):
super(KMeansModel, self).__init__(data_path)
self.cluster_size = cluster_size
def cluster(self, words, guess):
print("Running KMeans...")
vectors = self.words_to_vectors(words)
# get # of groups, should leave enough for one group of N
cluster_count = len(vectors) - guess + 1
labelled = KMeans(n_clusters=cluster_count).fit_predict(vectors)
return labelled
class DBSCANModel(Model):
# https://www.geeksforgeeks.org/difference-between-k-means-and-dbscan-clustering/
# https://scikit-learn.org/stable/modules/clustering.html#dbscan
# https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html#sklearn.cluster.DBSCAN.fit_predict
# https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
# a group is a group when there are `min_samples` other points `eps` distance away
# label of -1 === noise
# TODO: figure out good values for eps and min_samples that result in non- -1 values
# eps=4 is way too high, <3 is too low, or maybe these words are just too sparse
def cluster(self, words, guess):
print("Running DBSCAN...")
vectors = self.words_to_vectors(words)
labelled = DBSCAN(eps=3.1, min_samples=1).fit_predict(vectors)
return labelled
|
Java | UTF-8 | 1,242 | 2.65625 | 3 | [
"MIT"
] | permissive | package cn.bearever.mingbase.chain.core;
import android.content.Context;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
/**
* 异步链的包装类,用来控制调用者可以访问的方法,主要目的是执行了`error*`方法之后就只能执行`go*`方法。
*
* @author : luoming luomingbear@163.com
* @date : 2019/8/5
**/
public class AsyncChainLinkGo {
private AsyncChainLink link;
/**
* 构造函数
*
* @param link {@link AsyncChainLink}
*/
public AsyncChainLinkGo(AsyncChainLink link) {
this.link = link;
}
/**
* 开始执行
*/
public void go(AppCompatActivity activity) {
link.go(activity);
}
/**
* 开始执行
*
* @param fragment 绑定生命周期的fragment
*/
public void go(Fragment fragment) {
link.go(fragment);
}
/**
* 开始执行
*
* @param view 绑定生命周期的view
*/
public void go(View view) {
link.go(view);
}
/**
* 开始执行
*
* @param context 绑定生命周期的context
*/
public void go(Context context) {
link.go(context);
}
}
|
Java | UTF-8 | 2,192 | 2.203125 | 2 | [
"Apache-2.0"
] | permissive | /*
* (C) Copyright IBM Corp. 2020, 2023.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.watson.assistant.v1.model;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/** AgentAvailabilityMessage. */
public class AgentAvailabilityMessage extends GenericModel {
protected String message;
/** Builder. */
public static class Builder {
private String message;
/**
* Instantiates a new Builder from an existing AgentAvailabilityMessage instance.
*
* @param agentAvailabilityMessage the instance to initialize the Builder with
*/
private Builder(AgentAvailabilityMessage agentAvailabilityMessage) {
this.message = agentAvailabilityMessage.message;
}
/** Instantiates a new builder. */
public Builder() {}
/**
* Builds a AgentAvailabilityMessage.
*
* @return the new AgentAvailabilityMessage instance
*/
public AgentAvailabilityMessage build() {
return new AgentAvailabilityMessage(this);
}
/**
* Set the message.
*
* @param message the message
* @return the AgentAvailabilityMessage builder
*/
public Builder message(String message) {
this.message = message;
return this;
}
}
protected AgentAvailabilityMessage() {}
protected AgentAvailabilityMessage(Builder builder) {
message = builder.message;
}
/**
* New builder.
*
* @return a AgentAvailabilityMessage builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the message.
*
* <p>The text of the message.
*
* @return the message
*/
public String message() {
return message;
}
}
|
Java | UTF-8 | 775 | 2.125 | 2 | [] | no_license | package com.mysoft.sc;
import com.serotonin.messaging.OutgoingRequestMessage;
import com.serotonin.util.queue.ByteQueue;
/**
* 生成请求数据帧类(网络协议部分)
* @author yangfan ej
*
*/
public class ScIpSerialMessageRequest extends ScIpSerialMessage implements OutgoingRequestMessage,ScIncomingRequestMessage{
public static ScIpSerialMessageRequest createScIpMessageRequest(ByteQueue queue){
ScMessage lqm=ScMessage.createScMessage(queue);
ScIpSerialMessageRequest lqr=new ScIpSerialMessageRequest(lqm);
return lqr;
}
public ScIpSerialMessageRequest(ScMessage lqMessage) {
super(lqMessage);
// TODO Auto-generated constructor stub
}
@Override
public boolean expectsResponse() {
// TODO Auto-generated method stub
return true;
}
}
|
Markdown | UTF-8 | 5,334 | 3.15625 | 3 | [] | no_license | summary: demo
id: 20200212-02-杨金月
0ries: webpage
tags:
status: Published
authors: 杨金月
Feedback Link: http://www.sctu.edu.cn
# JS实现3D旋转相册
3D旋转相册是通过perspective属性的盒子1产生向网页内部的延伸感,并让装有图片沿z轴平移后的盒子2在拥有perspective属性的盒子1内凭借transform属性产生的3d效果沿盒子2y轴旋转转动来实现的。
## 1.属性介绍
### 1) perspective属性:
多少像素的3D元素是从视图的perspective属性定义。这个属性允许你改变3D元素是怎样查看透视图。定义时的perspective属性,它是一个元素的子元素,透视图,而不是元素本身。
注意:perspective 属性只影响 3D 转换元素。
### 2) transform属性:
应用于元素的2D或3D转换。这个属性允许你将元素旋转,缩放,移动,倾斜等。
语法:
```js
transform: none|transform-functions
```

transform中的x、y、z、轴的含义如图所示:

## 2.实现方法
1) 设置一个div,为其加上perspective的属性(撑开空间),方便后边观察效果
```css
#perspective{
perspective: 700px;
}/*此属性是实现旋转木马的要点,能产生空间上的距离/延伸感。在此盒子中放置图片的盒子便可以实现向网页内部延伸的感觉*/
```

2) 设置装有图片盒子的容器wrap,使其居中显示,并加上position:relative的属性,让其内的图片定位。并加上transform属性。
```css
#wrap{
position: relative;
width: 200px;
height: 200px;
margin: 150px auto;
border: 1px solid black;
transform-style: preserve-3d; /*实现3d效果的关键步骤,与boxshadow配合使用可以忽略层级问题,之后会说到*/
transform: rotateX(0deg) rotateY(0deg) ;//为盒子的3d效果和旋转效果做准备。
}
```
3) 加入图片,设置样式,使用position:absolute;使其重叠。以数组的形式获取,并根据其数组长度length来计算图片的旋转角度。
```css
#wrap img{
position: absolute;
width: 200px;
}
```
```html
<script>
var oImg = document.getElementsByTagName('img');
var Deg = 360/oImg.length;
oWrap = document.getElementById('wrap'); /*顺便拿一下容器*/
</script>
```
4) 遍历数组,使其沿y轴旋转Deg度。此处使用了原型,使用foreach方法遍历了数组,让其内每个图片都执行了function(el,index)。使用index下标区分开了数组内每个图片需要旋转的不同度数(第一张0°(Deg * 0) 第二张Deg度 (Deg * 1) 第三张(Deg * 2)度…)
```js
/*oImg表示数组对象,function(el,index)表示数组内每个对象要执行的函数,index为其下标。*/
Array.prototype.forEach.call(oImg,function(el,index){
el.style.transform = "rotateY("+Deg*index+"deg)translateZ(350px)";
// el.style.zIndex = -index;
el.style.transition = "transform 1s "+ index*0.1 +"s";
});
```

5) 做完上一步操作后,让盒子其内图片沿Z轴平移translateZ(350px)属性便能初步看到3d效果,但此时会发现容器内图片数组出现了层级问题(Zindex)导致了理应在后面的图片能被显示出来。

```js
/*加上沿z扩散*/
<script>
Array.prototype.forEach.call(oImg,function(el,index){
el.style.transform = "rotateY("+Deg*index+"deg)translateZ(350px)"; //沿z轴扩散350px
})
</script>
```
-------执行完毕后--------加上属性观察效果---------
```css
#wrap{
width: 200px;
height: 200px;
position: relative;
margin:150px auto;
transform-style: preserve-3d; /*实现3d效果的关键步骤,与boxshadow配合使用可以忽略层级问题*/
}
#wrap img{
position: absolute;
width: 200px;
box-shadow: 0px 0px 1px #000000; /* 用box-shadow配合transform-style: preserve-3d;可以忽略层级问题 *
}
```

6) 这时候为装有图片的盒子加上transform:rotateX(-15deg);便能看到较为完整的3d效果了,此时实现盒子绕y轴转动便可实现旋转木马的效果。

7) 单纯使盒子转动就可以实现图像,我们使用setinterval来不断使其旋转。但如果想使用鼠标拖动实现旋转木马,则需要再加一些代码,使装有盒子的容器(wrap)能够根据鼠标坐标变化绕容器(wrap)自身y轴转动。
```js
var nowX ,nowY,//当前鼠标坐标
lastX ,lastY ,//上一次鼠标坐标
minusX,minusY ,//距离差
roX = -10,roY = 0;//总旋转度数
window.onmousedown = function(ev){
var ev = ev;//获得事件源
lastX = ev.clientX;lastY = ev.clientY;
this.onmousemove = function(ev){
var ev = ev;//获得事件源
nowX = ev.clientX;nowY = ev.clientY;//获得当前坐标
minusX = nowX - lastX;minusY = nowY - lastY;//坐标差
roY += minusX;//累计差值
roX -= minusY;//累计差值
oWrap.style.transform = "rotateX("+roX+"deg)"
+"rotateY("+roY+"deg)";
lastX = nowX;lastY = nowY;//移动末期现坐标变为旧坐标
}
this.onmouseup = function(){
this.onmousemove = null;//取消鼠标移动的影响
// this.onmousedown = null;
}
}
}
```
|
Go | UTF-8 | 2,522 | 3.21875 | 3 | [
"MIT"
] | permissive | package game
import (
"pacman/dir"
)
type gameStruct struct {
game Game
icon rune
colour Colour
location dir.Location
direction dir.Direction
points int
start dir.Location
}
// NewElement gameStruct instance
func NewElement(game Game, icon rune, loc dir.Location, dir dir.Direction, points int) Element {
return &gameStruct{game: game,
icon: icon,
colour: DefaultColour,
location: loc,
direction: dir,
points: points,
start: loc}
}
// AddToGame adds a new type of this element to the game
func (el *gameStruct) AddToGame(game Game) {
el.game = game
}
// IsForceField checks if a wall is a force field
func (el *gameStruct) IsForceField() bool {
return IsForceField(el.icon)
}
// IsGate checks if a wall is a gate
func (el *gameStruct) IsGate() bool {
return IsGate(el.icon)
}
// Location of this element
func (el *gameStruct) Location() dir.Location {
return el.location
}
// SetLocation of this element
func (el *gameStruct) SetLocation(loc dir.Location) {
loc.Wrap(el.game.Dimensions())
el.location = loc
}
// Direction of this element
func (el *gameStruct) Direction() dir.Direction {
return el.direction
}
// SetDirection of this element
func (el *gameStruct) SetDirection(dir dir.Direction) {
el.direction = dir
}
// Icon for this element
func (el *gameStruct) Icon() rune {
return el.icon
}
// Colour for this element
func (el *gameStruct) Colour() Colour {
return el.colour
}
// SetIcon for this element
func (el *gameStruct) SetIcon(icon rune) {
el.icon = icon
}
// SetColour for this element
func (el *gameStruct) SetColour(colour Colour) {
el.colour = colour
}
// Tick activates this elements turn
func (el *gameStruct) Tick() {
// Base elements have no behaviour
}
// Score in points for this elements
func (el *gameStruct) Score() int {
return el.points
}
// Restart the element in its initial placing
func (el *gameStruct) Restart() {
el.SetLocation(el.start)
}
// TriggerEffect for this element colliding with the other
func (el *gameStruct) TriggerEffect(element Element) {
// Base elements have no effect on other elements
}
// GetGame for accessing Game context
func (el *gameStruct) GetGame() Game {
return el.game
}
// CollectElements from lists or lists into a flattened list
func CollectElements(lists ...[]Element) []Element {
var elements []Element
for _, slice := range lists {
for _, piece := range slice {
if piece != nil {
elements = append(elements, piece)
}
}
}
return elements
}
|
C++ | UTF-8 | 2,364 | 3.28125 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "MessageBus.hpp"
MessageBus g_bus;
const string Topic = "Drive";
const string CallBackTopic = "DriveOk";
//TEST CODE
struct Subject{
Subject(){
g_bus.Attach([this]{DriveOk();},CallBackTopic);
}
void SendReq(const string& topic){
g_bus.SendReq<void, int>(50, topic);
}
void DriveOk(){
cout<<"drive ok"<<endl;
}
};
struct Car{
Car(){
g_bus.Attach([this](int speed){Drive(speed);}, Topic);
}
void Drive(int speed){
cout << "Car drive " << speed << endl;
g_bus.SendReq<void>(CallBackTopic);
}
};
struct Bus{
Bus(){
g_bus.Attach([this](int speed){Drive(speed);});
}
void Drive(int speed){
cout << "Bus drive " << speed << endl;
g_bus.SendReq<void>(CallBackTopic);
}
};
struct Truck{
Truck(){
g_bus.Attach([this](int speed){Drive(speed);});
}
void Drive(int speed){
cout << "Truck drive " << speed << endl;
g_bus.SendReq<void>(CallBackTopic);
}
};
void TestBus(){
Subject subject;
Car car;
Bus bus;
Truck truck;
subject.SendReq(Topic);
subject.SendReq("");
}
//TEST CODE
void TestMsgBus(){
MessageBus bus;
// 注册消息
bus.Attach([](int a){cout << "no reference" << a << endl; });
bus.Attach([](int& a){cout << "lvalue reference" << a << endl; });
bus.Attach([](int&& a){cout << "rvalue reference" << a << endl; });
bus.Attach([](const int& a){cout << "const lvalue reference" << a << endl; });
bus.Attach([](int a){cout << "no reference has return value and key" << a << endl;return a;}, "a");
int i = 2;
// 发送消息
bus.SendReq<void, int>(2);
bus.SendReq<int, int>(2, "a");
bus.SendReq<void, int&>( i);
bus.SendReq<void, const int&>(2);
bus.SendReq<void, int&&>(2);
// 移除消息
bus.Remove<void, int>();
bus.Remove<int, int>("a");
bus.Remove<void, int&>();
bus.Remove<void, const int&>();
bus.Remove<void, int&&>();
// 发送消息
bus.SendReq<void, int>(2);
bus.SendReq<int, int>(2, "a");
bus.SendReq<void, int&>(i);
bus.SendReq<void, const int&>(2);
bus.SendReq<void, int&&>(2);
}
int main() {
TestBus();
std::cout<<"----------------------------"<<std::endl;
TestMsgBus();
return 0;
}
|
Java | UTF-8 | 975 | 2.125 | 2 | [] | no_license | package com.example.michaelbabenkov.popularmovies.ui.settings;
import android.app.Fragment;
import android.os.Bundle;
import android.view.Menu;
import com.example.michaelbabenkov.popularmovies.R;
import com.example.michaelbabenkov.popularmovies.ui.base.SinglePaneActivity;
/**
* Created by michaelbabenkov on 13/07/15.
*/
public class SettingsActivity extends SinglePaneActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
protected int setResourceXml() {
return R.layout.activity_single_pane;
}
@Override
protected Fragment onCreatePane() {
return new SettingsFragment();
}
}
|
JavaScript | UTF-8 | 5,714 | 2.6875 | 3 | [] | no_license | // --- NAV-class function ----
$(function(){
$("a").each(function(){
if ($(this).attr("href") === window.location.pathname){
$(this).addClass("active");
}
});
});
let hamb = document.getElementById('hamburger');
let links = document.querySelector('.links');
let itemHTML = document.getElementById('one');
let itemCSS = document.getElementById('two');
let itemJS = document.getElementById('three');
let itemR = document.getElementById('four');
let itemh2 = document.getElementById('h2');
let itemh22 = document.getElementById('h22');
let itemh222 = document.getElementById('h222');
let itemh2222 = document.getElementById('h2222');
let count = 0;
function toggle() {
console.log("Nu kur tas PNG????");
count % 2 === 0 ? hamb.src = "../img/x-png.png" : hamb.src = "../img/hamburger.png";
if (count % 2 === 0) {
links.style.display = "flex";
links.style.position = "absolute";
links.style.flexDirection = "column";
links.style.top = "50px";
links.style.right = "5%";
links.style.alignItems = "center";
links.style.width = "150px";
links.style.background = "#000";
links.style.height = "160px";
links.style.justifyContent = "space-around";
links.style.border = "2px solid #7FC2EB"
links.style.borderRadius = "6px";
links.style.paddingLeft = "0";
}
count % 2 === 0 ? links.style.display = 'relative' : links.style.display = 'none';
count += 1;
}
// Boxes style chaning on mouse activity
function increaseHTML() {
itemHTML.style.width = '45%';
// itemHTML.style.height = '34%';
itemHTML.style.textShadow = "2px 2px 3px black";
itemHTML.style.opacity = '0.9';
itemh2.style.display = 'flex';
itemh2.style.background = 'rgba(0, 0, 0, 0.7)';
};
itemHTML.onmouseover = increaseHTML;
function decreaseHTML() {
itemHTML.style.width = '370px';
// itemHTML.style.height = '32%';
itemh2.style.display = 'none';
};
itemHTML.onmouseout = decreaseHTML;
function increaseCSS() {
itemCSS.style.width = '35%';
// itemCSS.style.height = '34%';
itemCSS.style.color = "white";
itemCSS.style.textShadow = "2px 2px 3px black";
itemCSS.style.opacity = '0.9';
itemh22.style.display = 'flex';
itemh22.style.background = 'rgba(0, 0, 0, 0.7)';
};
itemCSS.onmouseover = increaseCSS;
function decreaseCSS() {
itemCSS.style.width = '370px';
// itemCSS.style.height = '32%';
itemh22.style.display = 'none';
};
itemCSS.onmouseout = decreaseCSS;
function increaseJS() {
itemJS.style.width = '45%';
// itemJS.style.height = '34%';
itemJS.style.textShadow = "2px 2px 3px black";
itemJS.style.opacity = '0.9';
itemh222.style.display = 'flex';
itemh222.style.background = 'rgba(0, 0, 0, 0.7)';
};
itemJS.onmouseover = increaseJS;
function decreaseJS() {
itemJS.style.width = '370px';
// itemJS.style.height = '32%';
itemh222.style.display = 'none';
};
itemJS.onmouseout = decreaseJS;
function increaseR() {
itemR.style.width = '45%';
// itemR.style.height = '34%';
itemR.style.textShadow = "2px 2px 3px black";
itemR.style.opacity = '0.9';
itemh2222.style.display = 'flex';
itemh2222.style.background = 'rgba(0, 0, 0, 0.7)';
};
itemR.onmouseover = increaseR;
function decreaseR() {
itemR.style.width = '370px';
// itemR.style.height = '32%';
itemh2222.style.display = 'none';
};
itemR.onmouseout = decreaseR;
// function changeBackground() {
// itemTwo.style.backgroundColor = 'darkgreen';
// };
// itemTwo.onmouseup = changeBackground;
// function changeText() {
// itemThree.textContent = 'The mouse has left the element';
// itemThree.style.backgroundColor = "darkblue";
// };
// itemThree.onmouseout = changeText;
// function showItem() {
// itemFive.style.display = 'block';
// };
// itemFour.onmousedown = showItem;
// --- HTML event handler: ------------------------
// function checkUserName() {
// let msg = document.getElementById("feedback");
// let userN = document.getElementById("username");
// if (userN.value.length<5) {
// msg.textContent = "User name must be 5 chars or more...";
// } else {
// msg.textContent = "";
// };
// };
// --- DOM event hadler: ------------------------
// function checkUserName() {
// let msg = document.getElementById("feedback");
// if (this.value.length<5) {
// msg.textContent = "User name must be 5 chars or more...";
// } else {
// msg.textContent = "";
// };
// };
// let userN = document.getElementById("username");
// userN.onblur = checkUserName;
// // --- EVENT LISTENER: ------------------------
// userN.addEventListener('click', checkUserName, false);
// // --- EVENT Listener on UL element!!!! ---------
// function changeB() {
// let cont = document.getElementById("container");
// cont.style.backgroundColor = "lightgreen";
// document.body.style.backgroundColor = "grey";
// };
// let unlist = document.getElementById('container');
// unlist.addEventListener('click', changeB, true);
// /// RESET -> last ---------------------
// let reset = function() {
// itemOne.style.width = ''
// itemTwo .style.backgroundColor = ''
// itemThree .style.backgroundColor = ''
// itemThree.innerHTML = 'The mouse must leave the box to change the text'
// itemFive.style.display = "none"
// let cont = document.getElementById("container");
// cont.style.backgroundColor = "pink";
// document.body.style.backgroundColor = "green";
// };
// resetButton.onclick = reset;
// // FOCUS on input form (when page loaded): ----------------------------------
// function setup() {
// let userNN = document.getElementById('username');
// userNN.focus();
// };
// window.addEventListener('load', setup, false); |
Java | UTF-8 | 5,544 | 1.859375 | 2 | [
"Apache-2.0"
] | permissive | package io.quarkus.maven;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;
import java.util.function.Consumer;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import io.quarkus.bootstrap.app.CuratedApplication;
import io.quarkus.bootstrap.classloading.QuarkusClassLoader;
import io.quarkus.bootstrap.model.ApplicationModel;
import io.quarkus.maven.dependency.ArtifactCoords;
import io.quarkus.paths.PathCollection;
import io.quarkus.paths.PathList;
import io.quarkus.runtime.LaunchMode;
// in the PROCESS_RESOURCES phase because we want the config to be available
// by the time code gen providers are triggered (the resources plugin copies the config files
// to the destination location at the beginning of this phase)
@Mojo(name = "generate-code", defaultPhase = LifecyclePhase.PROCESS_RESOURCES, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, threadSafe = true)
public class GenerateCodeMojo extends QuarkusBootstrapMojo {
/**
* Skip the execution of this mojo
*/
@Parameter(defaultValue = "false", property = "quarkus.generate-code.skip", alias = "quarkus.prepare.skip")
private boolean skipSourceGeneration = false;
@Parameter(defaultValue = "NORMAL", property = "launchMode")
String mode;
@Override
protected boolean beforeExecute() throws MojoExecutionException, MojoFailureException {
if (mavenProject().getPackaging().equals(ArtifactCoords.TYPE_POM)) {
getLog().info("Type of the artifact is POM, skipping build goal");
return false;
}
if (skipSourceGeneration) {
getLog().info("Skipping Quarkus code generation");
return false;
}
return true;
}
@Override
protected void doExecute() throws MojoExecutionException, MojoFailureException {
generateCode(getParentDirs(mavenProject().getCompileSourceRoots()),
path -> mavenProject().addCompileSourceRoot(path.toString()), false);
}
void generateCode(PathCollection sourceParents,
Consumer<Path> sourceRegistrar,
boolean test) throws MojoFailureException, MojoExecutionException {
final LaunchMode launchMode;
if (test) {
launchMode = LaunchMode.TEST;
} else if (mavenSession().getGoals().contains("quarkus:dev")) {
// if the command was 'compile quarkus:dev' then we'll end up with prod launch mode but we want dev
launchMode = LaunchMode.DEVELOPMENT;
} else {
launchMode = LaunchMode.valueOf(mode);
}
if (getLog().isDebugEnabled()) {
getLog().debug("Bootstrapping Quarkus application in mode " + launchMode);
}
ClassLoader originalTccl = Thread.currentThread().getContextClassLoader();
CuratedApplication curatedApplication = null;
QuarkusClassLoader deploymentClassLoader = null;
try {
curatedApplication = bootstrapApplication(launchMode);
deploymentClassLoader = curatedApplication.createDeploymentClassLoader();
Thread.currentThread().setContextClassLoader(deploymentClassLoader);
final Class<?> codeGenerator = deploymentClassLoader.loadClass("io.quarkus.deployment.CodeGenerator");
final Method initAndRun = codeGenerator.getMethod("initAndRun", QuarkusClassLoader.class, PathCollection.class,
Path.class, Path.class,
Consumer.class, ApplicationModel.class, Properties.class, String.class,
boolean.class);
initAndRun.invoke(null, deploymentClassLoader, sourceParents,
generatedSourcesDir(test), buildDir().toPath(),
sourceRegistrar, curatedApplication.getApplicationModel(), getBuildSystemProperties(false),
launchMode.name(),
test);
} catch (Exception any) {
throw new MojoExecutionException("Quarkus code generation phase has failed", any);
} finally {
// in case of test mode, we can't share the bootstrapped app with the testing plugins, so we are closing it right away
if (test && curatedApplication != null) {
curatedApplication.close();
}
Thread.currentThread().setContextClassLoader(originalTccl);
if (deploymentClassLoader != null) {
deploymentClassLoader.close();
}
}
}
protected PathCollection getParentDirs(List<String> sourceDirs) {
if (sourceDirs.size() == 1) {
return PathList.of(Path.of(sourceDirs.get(0)).getParent());
}
final PathList.Builder builder = PathList.builder();
for (int i = 0; i < sourceDirs.size(); ++i) {
final Path parentDir = Path.of(sourceDirs.get(i)).getParent();
if (!builder.contains(parentDir)) {
builder.add(parentDir);
}
}
return builder.build();
}
private Path generatedSourcesDir(boolean test) {
return test ? buildDir().toPath().resolve("generated-test-sources") : buildDir().toPath().resolve("generated-sources");
}
}
|
Python | UTF-8 | 4,389 | 2.828125 | 3 | [] | no_license | from __future__ import division
__author__ = 'Venkatesh'
import math
from optimizers.decs import Decisions
from models.model import Model
class DTLZ1(Model):
no_decisions = 10
no_objectives = 2
decisions = []
name = "DTLZ1"
def __init__(self,decs=10,objs=2):
self.no_decisions = decs
self.no_objectives = objs
lo = [0]
hi = [1]
for i in range(self.no_decisions):
self.decisons.append(Decisions(lo[0],hi[0]))
def g(self,can):
g_val = 0
for x in can[self.no_objectives-1:]:
g_val += math.pow((x-0.5),2) - math.cos(20*math.pi*(x-0.5))
g_val += self.no_decisions-self.no_objectives+1
g_val *= 100
return g_val
def objs(self,can):
objectives = []
g_val = self.g(can)
for i in range(self.no_objectives):
val = 0.5*(1 + g_val)
x = 0
for _ in range(self.no_objectives - 1 - i):
val *= can[_]
x += 1
if not i == 0:
val *= (1-can[self.no_objectives - i])
objectives.append(val)
return objectives
def score(self,can):
return sum(self.objs(can))
class DTLZ3(Model):
no_decisions = 20
no_objectives = 4
decisions = []
name = "DTLZ3"
def __init__(self,decs=10,objs=2):
self.no_decisions = decs
self.no_objectives = objs
lo = [0]
hi = [1]
for i in range(self.no_decisions):
self.decisons.append(Decisions(lo[0],hi[0]))
def g(self,can):
g_val = 0
for x in can[self.no_objectives-1:]:
g_val += math.pow((x-0.5),2) - math.cos(20*math.pi*(x-0.5))
g_val += self.no_decisions-self.no_objectives+1
g_val *= 100
return g_val
def score(self,can):
return sum(self.objs(can))
def objs(self,can):
objectives = []
g_val = self.g(can)
for i in range(self.no_objectives):
val = (1 + g_val)
for x in range(self.no_objectives - 1 - i):
val *= math.cos(can[x]*(math.pi/2))
if i > 0:
val *= math.sin(can[self.no_objectives - i]*(math.pi/2))
objectives.append(val)
return objectives
class DTLZ5(Model):
no_decisions = 30
no_objectives = 6
decisions = []
name = "DTLZ5"
def __init__(self,decs=10,objs=2):
self.no_decisions = decs
self.no_objectives = objs
lo = [0]
hi = [1]
for i in range(self.no_decisions):
self.decisons.append(Decisions(lo[0],hi[0]))
def g(self,can):
g_val = 0
for x in can[self.no_objectives-1:]:
g_val += math.pow((x-0.5),2)
return g_val
def score(self,can):
return sum(self.objs(can))
def theta(self,x,g_val):
return (math.pi/(4 * (1 + g_val))) * (1 + (2 * g_val * x))
def objs(self,can):
objectives = []
g_val = self.g(can)
for i in range(self.no_objectives):
val = (1 + g_val)
for x in range(self.no_objectives - 1 - i):
val *= math.cos(self.theta(can[x],g_val)*(math.pi/2))
if i > 0:
val *= math.sin(self.theta(can[self.no_objectives - i],g_val)*(math.pi/2))
objectives.append(val)
return objectives
class DTLZ7(Model):
no_decisions = 40
no_objectives = 8
decisions = []
name = "DTLZ7"
def __init__(self,decs=10,objs=2):
self.no_decisions = decs
self.no_objectives = objs
lo = [0]
hi = [1]
for i in range(self.no_decisions):
self.decisons.append(Decisions(lo[0],hi[0]))
def score(self,can):
return abs(sum(self.objs(can)))
def fm(self,can):
objectives = []
g = 1 + 9/(self.no_decisions-self.no_objectives+1) * sum(can[self.no_objectives-1:])
for i in range(self.no_objectives - 1):
objectives.append(can[i])
def calch():
h = self.no_objectives
for x in range(self.no_objectives-1): # no of objectives
h += (objectives[x]/(1+g))*(1 + math.sin(3*math.pi*objectives[x]))
return h
objectives.append((1+g)*calch())
return objectives
def objs(self,can):
return self.fm(can)
|
Markdown | UTF-8 | 2,268 | 3 | 3 | [] | no_license | # SLACK-HACK
A product using SLACK and hosted in AWS and Heroku to display unread messages of different channels in a single webpage.
## Description
The product involves the Authorization - access via SLACK to get involved into the database and get the information about the messages and workspace involved, channels present in user's database. Using different APIs we access the data and re-direct the user to a website . In this way the ease of usage is increased and the complexity to get access to the messages is reduced. It allows us to get the unread messages as our first priority and make ease of usage efficient reducing the complexity of the access of messages. We can get all our unread messages in a single screen in a single click, also we can multitask and engage and get connected to more than one channel in a workspaces.
##Flow of SLACK-HACK
### Website---> https://obscure-sands-20176.herokuapp.com


### Authorization-access--->

After the option clicked in the webpage we get directed to access the authorization of the user which is done by the SLACK itself seeking the credentials of the user and verifying the user's presence in database.
### Re-directing--->

### Display of unread messages in a single interface.
The unread messages are displayed in a single webpage.
## Usage
Go to the SLACK-HACK webpage and signup using SLACK, and then enter the credentials for slack. If you don't have a slack account then you can signup into slack and then it will be re-directed into SLACK-HACK and you will be able to see your unread messages on the screen.
## Technology Stack
- HTML & CSS
- JavaScript
- Node.js
- Express
- EJS
- Slack API
- Heroku
|
Python | UTF-8 | 786 | 2.703125 | 3 | [] | no_license | import sqlite3
import os
import pandas as pd
db_location = r'C:\Users\c110846\Documents\salesforce_db'
#change to db location directory
os.chdir(db_location)
#connect to db
conn = sqlite3.connect('salesforce.db')
#create a datafrae from a query
df = pd.read_sql_query('''
SELECT * from sqlite_master where type= "table"
''', conn)
#create cursor then execture a sql command
cursor = conn.cursor()
cursor.execute('drop table event' )
#commit and close
conn.commit()
conn.close()
#Make a db in memory (<3 teh memzorz)
conn = sqlite3.connect(':memory:')
#write the table
#https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
df.to_sql('df_sqlite_master', conn, index=False, if_exists='replace') #can also append or fail if exists
|
Go | UTF-8 | 1,036 | 2.796875 | 3 | [
"MIT"
] | permissive | package service
import (
"context"
"github.com/karta0898098/iam/pkg/app/identity/entity"
)
type loggingMiddleware struct {
next IdentityService `json:"-"`
}
// LoggingMiddleware takes a logger as a dependency
// and returns a ServiceMiddleware.
func LoggingMiddleware() Middleware {
return func(next IdentityService) IdentityService {
return loggingMiddleware{next}
}
}
func (lm loggingMiddleware) Signin(ctx context.Context, username string, password string, opt *SigninOption) (identity *entity.Identity, err error) {
defer func() {
// lm.logger.Log(
// "method", "Signin",
// "username", username,
// "err", err,
// )
}()
return lm.next.Signin(ctx, username, password, opt)
}
func (lm loggingMiddleware) Signup(ctx context.Context, username string, password string, opts *SignupOption) (identity *entity.Identity, err error) {
defer func() {
// lm.logger.Log(
// "method", "Signup",
// "username", username,
// "err", err,
// )
}()
return lm.next.Signup(ctx, username, password, opts)
}
|
C++ | UTF-8 | 1,106 | 2.578125 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* This file is part of the source code of the software program
* Vampire. It is protected by applicable
* copyright laws.
*
* This source code is distributed under the licence found here
* https://vprover.github.io/license.html
* and in the source directory
*/
/**
* @file NameArray.hpp
* Defines ordered immutable arrays of integers.
* Previously they were used in Options.
*
* TODO : not currently used, but could be used in OptionValues
*
* @since 21/04/2005 Manchester
*/
#ifndef __NameArray__
#define __NameArray__
using namespace std;
namespace Lib {
/**
* Defines ordered immutable arrays of integers.
* Previously they were used in Options.
*
* @since 21/04/2005 Manchester
*/
class NameArray {
public:
NameArray(const char* array[],int length);
int find(const char* value) const;
int tryToFind(const char* value) const;
/** Return i-th element of the array */
const char* operator[] (int i) const { return _array[i]; }
/** The length of the array */
const int length;
private:
/** Array itself */
const char** _array;
}; // class NameArray
}
#endif
|
PHP | UTF-8 | 272 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
//From request import request
use Illuminate\Http\Request;
//El "extends" es el método para heredar en php
class RegistroController extends Controller
{
//
function index(Request $req) {
return "Conejito";
}
}
|
C# | UTF-8 | 809 | 3.125 | 3 | [
"MIT"
] | permissive | using System;
namespace BinarySerialization
{
/// <summary>
/// Provides the <see cref="BinarySerializer" /> with information used to serialize the decorated member.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class FieldOrderAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="FieldOrderAttribute" /> class.
/// </summary>
public FieldOrderAttribute(int order)
{
Order = order;
}
/// <summary>
/// The order to be observed when serializing or deserializing
/// this member compared to other members in the parent object.
/// </summary>
public int Order { get; set; }
}
} |
Markdown | UTF-8 | 16,691 | 2.65625 | 3 | [] | no_license | # Distributed street level image image processing
[](http://www.repostatus.org/#wip)
[](http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/)

# Sampling database
## Schema
A MySQL database utilising
[Geospatial extensions](https://dev.mysql.com/doc/refman/5.7/en/spatial-extensions.html)
holds all of the sample points in the following basic schema:
```
mysql> desc sample_points;
+-----------------+----------------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+----------------------+------+-----+-------------------+-----------------------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| city | varchar(255) | NO | | NULL | |
| road_name | varchar(255) | NO | | NULL | |
| osm_way_id | bigint(20) | NO | | NULL | |
| sequence | int(11) | NO | | NULL | |
| bearing | double | NO | | NULL | |
| geom | point | NO | MUL | NULL | |
| sample_order | int(11) | NO | | NULL | |
| sample_priority | int(11) | NO | | NULL | |
| ts | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| cam_dir | enum('left','right') | NO | | NULL | |
| predicted | tinyint(1) | YES | | 1 | |
| value | double | YES | | 0 | |
+-----------------+----------------------+------+-----+-------------------+-----------------------------+
13 rows in set (0.00 sec)
```
The table consists of 1 row **per sample**: 2 rows for each left and right
reading at each coordinate.
Where:
|Field |Meaning |
|:----------------|:-----------------------------------------------------------------------------------------------------------|
|id |A unique ID assigned to each sample point |
|city |One of the 112 major towns and cities the sample belongs to |
|road\_name |Name of the road the sample is on |
|osm\_way\_id |Open Street Map road network way id the sample belongs to |
|sequence |Order of this sample w.r.t the point along the way id/road |
|bearing |Heading in degrees of this point w.r.t previous and next point |
|geom |Coordinates of this sample, stored as a [WKT](https://en.wikipedia.org/wiki/Well-known_text) POINT(lng lat) |
|sample\_order |Order in which this sample should be taken |
|sample\_priority |Sampling priority for this point (lowest = highest priority) |
|ts |Timestamp for when this point was sampled or interpolated |
|cam\_dir |Sample direction - currently looking **left** or **right** w.r.t **bearing** |
|predicted |True if this point has been interpolated/predicted, False if an actual reading has been made |
|value |The **green** percentage value for this sample point |
## Initial data load
The code in [infrastructure/mysql](infrastructure/mysql) will import the initial
(un-sampled) dataset into mysql. It expects as input the **csv** files for each
city generated by the
[trees-open-street-map](https://github.com/datasciencecampus/trees-open-street-map)
module. During import, sample points will be assigned a **sampling priority** as
described below.
## Sampling priority
There are 418,941 unique
[osm way](http://wiki.openstreetmap.org/wiki/Elements#Way) ids/roads for the 112
major towns and cities in England and Wales. If sampling at 10 metre intervals,
this will result in 8,315,247 coordinates, or 16,630,494 sample points if
obtaining a **left** and **right** image at each point.
**A key requirement of this project is a complete dataset**
Missing points have been interpolated/predicted using **IDW** (details below).
Since it has been assumed that points closer to one another will exhibit a
higher correlation, it makes sense to sample points which are maximally further
appart. A naive sampling scheme would simply sample random points across a city
in a uniform fashon. It has been assumed that by **guiding** the sampling
process as to **maximise** information gain, we can **obtain a higher accuracy
dataset faster** than a random sampling method: In a random sampling scheme, it
is possible to sample 2 adjacent points which will do little to reduce the
overall error if sampling points are spatialy correlated.
In the case of sampling points along a road, this corresponds to a 1-
dimensional *maximally distant* sampling problem. For example, given a road
indexed by (pending) sample points:
```
[01 02 03 04 05 06 07 08 09 10 11 12 13 14 15]
```
If restricted to 1 sample per day, we could sample each point at random for 15
days, or proceed from lest to right. Instead, it is desirable to sample points
with maximum information gain as their sampled values will be propogated to
neighbours via the inverse distance weighting scheme. As such, the 15 indices
should be visited according to this schedule:
```
[08 04 12 02 06 10 14 01 03 05 07 09 11 13 15]
```
Where the middle (08) "pivot" point is visited first, point 04 second and so on.
The idea is to assign a sampling priority to each point which corresponds to a
"fold depth" if the list were to be continuously folded in half like a piece of
paper:

To solve this problem, each paper fold can be seen as a *depth* in a
*binary tree*. As such, the [algorithm](generic/sequence.py) used to assign
sampling priority to points traverses the list as if it were a tree in
[breadth first search](https://en.wikipedia.org/wiki/Breadth-first_search)
order.
```
01
02 03
04 05 06 07
08 09 10 11 12 13 14 15
```
For more details, also see the [unit test](generic/test_sequence.py).
Points on each road are assigned a priority using
[this](infrastructure/mysql/add_priority.py) script before database insertion.
# Image processing API
# Image processing pipeline
The image processing pipeline is divided by a number of network based FIFO
queues and worker processes. The objective is to separate the image sampling and
processing logic whilst keeping track of sampling state. The end-to-end pipeline
allows for complete control and flexibility over the sampling process.
## Layer 1
This layer consumes unsampled data points from the image processing API and
either: Places image download **jobs** directly onto the
**image\_download\_jobs** queue (option 1) or sends jobs to individual queues
for each city (option 2).
### Option 1: Quota based data load
N pending sample points are selected from the image processing API ordered
by their **sampling priority**.
### Option 2: City queue data loader
The **data loader** module is run on an ad-hoc basis. It consumes from the image
processing API and inserts a batch of work onto the first layer of **queues**.
#### City queues and "Jobs"
At this level, there is 1 (persitent) queue per city. This allows for maximum
flexibility and easy monitoring of image processing status. Each queue contains
a number of **jobs**, where each job is defined as follows:
```json
{
"id": 123,
"city": "Cardiff",
"road_name": "Clydesmuir Road",
"osm_way_id": "24005721",
"sequence": "000057",
"latitude": 51.491386,
"longitude": -3.141202,
"bearing": 46.48,
"cam_dir": "left"
}
```
The job structure is used throughout the processing pipeline.
## Layer 2
### Job scheduler
This (optional) module sits between the initial backlog\* queues and the current
work queue(s). It is both a consumer and producer of jobs. It's purpose is:
1. Control the job processing bandwidth. E.g., shovel a max quota of jobs onto
the current work queue per day.
2. Control the processing progress for each city. E.g., the city queues may be
consumed on a [round robin](https://en.wikipedia.com/wiki/Round-robin) basis,
in which case smaller cities will complete first. Or, jobs may be selected
using a weighted priority scheme, in which case the number of jobs selected from
each city is proportionate to the size of the city.
3. Processing flexibility. Jobs can be shoveled to different queues on an ad
-hoc basis or if processing restrictions change (e.g., different quota, the
addition of extra processing nodes or some form of load balancing proxy.
As such, the job shovel can be thought of as a
[job scheduler](https://en.wikipedia.com/wiki/Job_scheduler).
Note that this layer can by skipped if the
[data\_load/initial.sh](data_load/initial.sh) has not been used in Layer 1.
## Layer 3
### Image downloader
The process blocks on the **image\_download\_jobs** queue until a new job
arrives. Note that this behaviour can follow a scheme - see
[image\_download/download.sh](download.sh) for details.
Upon receiving a new image download job, the process will make a request for a
street-level image at a specific location and direction according to the
parameters in the download job. In addition, a second request is made to the
street-view API for associated image meta data which includes the month/year in
which the image was obtained.
Each downloaded image is stored locally (although could be pushed to an
external store) and then an **image processing** job is generated and pushed to
the **image\_processing\_jobs** queue where it will live until consumed by
workers in layer 4.
Having consumed the image download job **if** everything went as planned, the
job is deleted from the incoming queue. Otherwise, the job is marked as
"buried" as not to loose any samples and to assist in debugging/error
reproduction. Using a queue administration interface (see below), it is then
possible to flush or move buried jobs back onto the active queue after having
resolved the issue.
## Layer 4
### Image processor
This layer consists of 1 or more processes dedicated to image processing. At an
abstract level, an image processing process is both a consumer and a producer.
Image processing jobs are **consumed** from the **image\_processing\_jobs**
queue, processed and then the result is **pushed** to the
**image processing API**. As such, the image processing stages can be divided up
into 3 sub-steps:
#### Consumption
The process blocks on the **image\_processing\_jobs** queue according to a
*consumption scheme* which defines how much work the process will do before self
terminating. Specifically, the worker process will consume tasks until:
* **Forever**: Block on queue forever, processing jobs when they arrive.
* **Queue is empty**: Drain the queue until it is empty.
* **Maximum work load**: Do **N** many jobs as long as there exists work.
The format of a consumed job is exactly the same as a JSON image download job as
described above. Upon receiving a job, the image processor will obtain the
corresponding image from the image store:
`downloaded_images`/`city`/`road`/`osm_way_id`/{`left`,`right`}/`sequence`\_`lat`\_`lon`\_`id`.jpg
Note that the image could be located locally or as a network resource.
#### Processing
The next step is to quantify the amount of vegetation present in the image.
Currently, the image is first converted to the L\*a\*b\* colour space. Lab is
better suited to image processing tasks since it is much more intuitive than
RGB. In Lab, the lightness of a pixel (L value) is separated from the colour
(A and B values). A negative A value represents degrees of green, positive A,
degrees of red. Negative B represents blue, while positive B represents yellow.
A colour can never be red *and* green or yellow *and* blue at the same time.
Therefore the Lab colour space provides a more intuitive separability than RGB
(where all values must be adjusted to encode a colour.) Furthermore, since
lightness value (L) is represented independently from colour, a 'green' value
will be robust to varying lighting conditions.
The actual amount of vegetation present in the scene is defined to be the ratio
of *green* pixels in the overall image. Although it is possible to plug-in
other metrics at this stage.
#### Production
The results from image processing are then pushed to the image processing API.
Currently, the amount of green is pushed via a HTTP POST request to the
following end-point:
`http://server_ip:port/api/sample/<sample_id>`
With the following from:
```
value=<green_percent>
```
Having pushed the image processing results, the worker then deletes the job from
the queue and then repeats the cycle.
### Running the image processor
Whilst the image processing script is invoked from a higher level script, it is
possible to run it independently by invoking the
[image\_processor.sh](image_processing/image_processor.sh) script, which in turn
will invoke:
```
python3 ./image_processor.py WORKER_NAME SCHEME SRC_QUEUE SRC_STORE
```
Where `WORKER_NAME` = name of process, `SCHEME` = -1, 0, or N according to the
consumption scheme described above, `SRC_QUEUE` = name of the incoming job
queue and `SRC_STORE` = (local) directory where downloaded images have been
stored.
# Sample point interpolation
For **green** percentage, it has been assumed that *there exists a spatial
relationship between each point*: It is likely that points closer together are
likely to be similar. Furthermore, it has been assumed that this relationship
is stronger for points on the same road and even stronger still for points on
the same side of the road. This is typically the case for roads with *rows* of
trees, stretches of park/woodland and for linear features such as hedgerows.
When interpolating/predicting missing points there exist many schemes (for
example mean N-nearest neighbour). However, given the above assumption, missing
sample points along a road are predicted according to the
[Inverse Distance Weighting](https://en.wikipedia.org/wiki/Inverse_distance_weighting)
of sampled values of the nearest *left* and *right* points:
`predicted = (1-w)*left + w*left` where `w = [0, 1]`: distance along line between
`left` and `right` sample points. -- See code+unit tests in
[interpolator/](interpolator/) for details.
# Monitoring
Besides [Beanstalkd's protocol](https://github.com/kr/beanstalkd/blob/master/doc/protocol.txt),
there exist a number of
[queue monitoring and admin tools](https://github.com/kr/beanstalkd/wiki/Tools).
[Aurora](https://github.com/xuri/aurora) is a nice (web based) tool which allows
for monitoring **and** manipulation of queue states - E.g., the ability to move
jobs around queues. And for the CLI,
[beanwalker](https://github.com/kadekcipta/beanwalker) is a nice Go based tool.
Both tools have been used in this project.
# Dependencies
## OS
* [beanstalkd](https://github.com/kr/beanstalkd) for queues.
* Mysql (with GIS Spatial extentions)
## Python
```
pip3 install -r requirements.txt
```
# Licence
Open Government license v3 [OGL v3](http://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/). |
Markdown | UTF-8 | 4,388 | 2.515625 | 3 | [
"MIT"
] | permissive | ---
title: 'Установка и удаление'
taxonomy:
category:
- docs
---
## Системные требования
**Версия операционной системы:** OS X 10.7 (64 bit) или более поздняя
**Объем оперативной памяти:** от 2 Гб
**Браузеры:** Safari, Google Chrome, Opera, Yandex.Browser, Mozilla Firefox, любой другой браузер, совместимый с macOS
**Свободное пространство на диске:** 60 Мбайт
## Установка программы
Для того чтобы установить Adguad для macOS на вашем компьютере, запустите браузер, наберите в адресной строке _adguard.com_ и на открывшейся веб-странице нажмите кнопку **_Скачать AdGuard_**.

Дождитесь окончания загрузки файла _Adguard.release.dmg_ и щелкните мышью на его значке в списке загруженных объектов, который демонстрируется в панели dock. На Рабочем столе вашего компьютера отобразится значок AdGuard. Щелкните на нем мышью, чтобы открыть окно программы установки.

В окне программы установки перетащите мышью значок AdGuard вправо на изображение папки Applications.
Приложение установлено на вашем компьютере. Для его запуска дважды щелкните мышью на значке AdGuard в папке Приложения (Applications), которую можно открыть с помощью файлового менеджера Finder. При первом запуске AdGuard операционная система продемонстрирует на экране предупреждение о том, что данное приложение загружено из Интернета. Нажмите кнопку **_Открыть_**.

Для использования программы вам потребуется ввести пароль администратора вашей учетной записи macOS. Введите его в открывшемся диалоговом окне и нажмите кнопку **_ОК_**.

<a name="uninstall"></a>
## Удаление программы
#### Стандартное удаление
Первым делом, откройте приложение «Finder», кликнув по соответствующей иконке:

Перейдите в раздел *«Программы»*. Выберите в списке AdGuard, кликните по нему правой кнопкой мыши и выберите пункт *«Переместить в корзину»*.

#### Продвинутое удаление
Используйте эту инструкцию только после выполнения всех шагов из инструкции по «стандартному удалению». После её выполнения:
1. Удалите следующие файлы Адгарда:
* целиком папку /Library/Application Support/com.adguard.Adguard
* целиком папку ~/Library/Application Support/com.adguard.Adguard
* файл ~/Library/Preferences/com.adguard.Adguard.plist
2. Запустите приложение «Мониторинг системы».
3. Через поиск найдите процесс *’cfprefsd’*.

4. Остановите процесс, запущенный от имени пользователя.

AdGuard полностью удален с вашего компьютера.
|
Java | UTF-8 | 1,354 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | package com.userzrq.threadLimit;
import com.sun.org.apache.bcel.internal.generic.NEW;
import javax.xml.ws.Service;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class Demo01 {
static Semaphore semaphore = new Semaphore(5);
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
new Thread(() -> {
boolean flag = false;
try {
flag = semaphore.tryAcquire(100, TimeUnit.MICROSECONDS);
if (flag) {
System.out.println(Thread.currentThread().getName() + ",尝试下单中....");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + ",下单成功");
} else {
System.out.println(Thread.currentThread().getName() + ",秒杀失败,请稍后重试!");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 添加布尔类型的标记变量,只有真正抢到的才释放信号量
if (flag) {
semaphore.release();
}
}
}).start();
}
}
}
|
Python | UTF-8 | 842 | 3.6875 | 4 | [] | no_license | from scipy import stats
import pandas as pd
import matplotlib.pyplot as plt
# reads csv file and stores data in pandas data frame
weather = pd.read_csv("../data/weather.csv")
# gets columns to be used as x and y values for linear model
temperature = weather['temperature']
days = weather['days']
# fits a linear model to given data
slope, intercept, r_value, p_value, std_error = stats.linregress(x=days, y=temperature)
# equation of a line: y = bx + a
predict_y = slope * days + intercept
# scatter plot of given data
plt.scatter(x=days, y=temperature)
# set range of x-axis of plot
plt.xlim(0, 25)
# plot predicted line: 'k' is black and '-' is solid line
plt.plot(days, predict_y, 'k-')
# label plot title and axes
plt.title('Weather: Temperature vs Days')
plt.xlabel('days')
plt.ylabel('temperature')
# show plot
plt.show()
|
Java | UTF-8 | 3,376 | 1.921875 | 2 | [] | no_license | package com.yeahwap.netgame.domain.pojo;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Create on 2012-10-10 16:03
*
* @author Harry
*
*/
@Entity
@Table(name = "user")
public class User implements java.io.Serializable {
private static final long serialVersionUID = 7896211206968804796L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private int id;
@Column(name = "name", nullable = false, length = 50)
private String name;
@Column(name = "password", nullable = false, length = 50)
private String password;
@Column(name = "init_fromid", nullable = false, length = 10)
private int initFromid;
@Column(name = "dateline", nullable = false)
private Date dateline;
@Column(name = "phone", nullable = true, length = 50)
private String Phone;
@Column(name = "email", nullable = true, length = 100)
private String email;
@Column(name = "score", nullable = true, length = 200)
private int score;
@Column(name = "isview", nullable = false, length = 4)
private int isview;
@Column(name = "type", nullable = false, length = 4)
private int type;
@Column(name = "weibo_id", nullable = true, length = 50)
private String weiboId;
@Column(name = "token", nullable = true, length = 50)
private String token;
@Column(name = "secret", nullable = true, length = 50)
private String secret;
@Column(name = "status", nullable = true, length = 4)
private byte status;
public byte getStatus() {
return status;
}
public void setStatus(byte status) {
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getInitFromid() {
return initFromid;
}
public void setInitFromid(int initFromid) {
this.initFromid = initFromid;
}
public Date getDateline() {
return dateline;
}
public void setDateline(Date dateline) {
this.dateline = dateline;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getIsview() {
return isview;
}
public void setIsview(int isview) {
this.isview = isview;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getWeiboId() {
return weiboId;
}
public void setWeiboId(String weiboId) {
this.weiboId = weiboId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
|
C++ | UTF-8 | 588 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int max_index(const float* s)
{
int tmp = s[0] > s[1] ? 0 : 1;
return s[tmp] > s[2] ? tmp : 2;
}
const char TAG[3] = {'W', 'T', 'L'};
int main()
{
float score[3][3];
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
scanf("%f", score[i]+j);
}
float p = 0.65;
for (int i = 0; i < 3; ++i)
{
int t = max_index(score[i]);
printf("%c ", TAG[t]);
p *= score[i][t];
}
p = (p-1)*2;
printf("%.2f\n", ceil(p*100)/100);
return 0;
}
|
PHP | UTF-8 | 3,270 | 3.953125 | 4 | [] | no_license | <?php
/*
Today we learn
*What is PHP
Once upon a time developer called personal Home page, but actually PHP is a server-side scripting language.
that is used to develop Static websites or Dynamic websites or Web applications
*How to run
without server you can't run PHP, so you should use a private server by using XAMPP. in your Computer.
*How to declare a Variable
Variable are used as "containers" in which we store information.A PHP variable starts with a dollar sign ($),
which is followed by the name of the variable. Rules for PHP variables:
- A variable name must start with a letter or an underscore
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive ($name and $NAME would be two different variables)
*/
$num1=10;
// Variables asign in php
for($i=1; $i<=$num1; $i++){
echo $i;
}
// for loop in php
if($num1==10){
echo 'positive ';
}else{
echo 'negative ';
}
// if else statement in php
$Name='Yeasin ';
function globalName(){
global $Name;
echo $Name;
}
globalName();
// function using global method for accessed globaly assigend variable in php
function localname(){
$name='Shanto ';
echo $name;
}
localname();
// function using local variable in php
// Operators
// Assignment Operator =The left operand gets set to the value of the expression on the right ,+=, -= ,*= ,/= ,%=
// Arithmetic Operators +Addition, -Subtraction, *Multiplication, /Division, %Modulus, **Exponentiation
// Comparison operators == Equal, === Identical,!= Not equal,!== Not identical,> Greater than,< Less than,
//>=Greater than or equal to,<= Less than or equal to,<=> Spaceship
// Logical Operators !,|| ,&& ,xor, or,and
// Increment/Decrement operators ++$x Pre-increment,$x++ Post-increment,--$x Pre-decrement,$x-- Post-decrement
// String operators . Concatenation,.= Concatenation assignment
// Array operators + Union,== Equality,=== Identity,!= Inequality,<> Inequality,!== Non-identity
// Conditional assignment operators ?: Ternary, ?? Null coalescing
$num2 = 6;
//Addition
echo $num1 + $num2; //14
//Subtraction
echo $num1 - $num2; //2
//Multiplication
echo $num1 * $num2; //48
//Division
echo $num1 / $num2;
// Assignment Operators
$x = 50;
$x += 100;
echo $x;
// simple Age Calculator with one condition test
function ageCal($yourBirthDay){
$currentYear=2020;
// echo $currentYear-$yourBirthDay .'years';
$hbd = $currentYear-$yourBirthDay;
if($hbd>=18){
echo ' You are eligible for registration ' . ' and your age is: ' .$hbd;
}
else{
echo ' Sorry! You are not eligible. and your age is: ' .$hbd;
}
}
ageCal(2000);
// result is you are eligible for registetion and your age is: 20
?> |
SQL | UTF-8 | 1,394 | 3.15625 | 3 | [] | no_license | CREATE TABLE "cast_movie_junction" (
"rec_key" SERIAL NOT NULL,
"movie_id" integer NOT NULL,
"character" varchar(30) NOT NULL,
"order" integer NOT NULL,
"actor_id" integer NOT NULL,
CONSTRAINT "pk_cast_movie_junction" PRIMARY KEY ("rec_key")
);
CREATE TABLE "actors" (
"actor_id" integer NOT NULL,
"name" varchar(255) NOT NULL,
"gender" varchar(255) NOT NULL,
CONSTRAINT "pk_actors" PRIMARY KEY ("actor_id")
);
CREATE TABLE "crew_movie_junction" (
"rec_key" SERIAL NOT NULL,
"movie_id" integer NOT NULL,
"department" varchar(255) NOT NULL,
"job" varchar(255) NOT NULL,
"crew_id" integer NOT NULL
);
CREATE TABLE "crew" (
"crew_id" integer NOT NULL,
"name" varchar(255) NOT NULL,
"gender" varchar(255) NOT NULL,
CONSTRAINT "pk_crew" PRIMARY KEY ("crew_id")
);
ALTER TABLE "cast_movie_junction"
ADD CONSTRAINT "fk_cast_movie_junction_movie_id" FOREIGN KEY("movie_id") REFERENCES "movies_data" ("id");
ALTER TABLE "cast_movie_junction"
ADD CONSTRAINT "fk_cast_movie_junction_actor_id" FOREIGN KEY("actor_id") REFERENCES "actors" ("actor_id");
ALTER TABLE "crew_movie_junction"
ADD CONSTRAINT "fk_crew_movie_junction_movie_id" FOREIGN KEY("movie_id") REFERENCES "movies_data" ("id");
ALTER TABLE "crew_movie_junction"
ADD CONSTRAINT "fk_crew_movie_junction_crew_id" FOREIGN KEY("crew_id") REFERENCES "crew" ("crew_id"); |
Java | UTF-8 | 2,689 | 2.09375 | 2 | [] | no_license | package com.zqkh.healthy.context.appservice.impl.domain.repository.mappers.dmo;
import java.util.Date;
public class ProgramResultDmo {
private String id;
private String familymemberId;
private String programId;
private Date startTime;
private Date endTime;
private Integer insistDay;
private Integer wanderNum;
private Integer giveUpNum;
private Integer finishNum;
private Date createTime;
private Integer total;
private Integer transcend;
private String program;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getFamilymemberId() {
return familymemberId;
}
public void setFamilymemberId(String familymemberId) {
this.familymemberId = familymemberId == null ? null : familymemberId.trim();
}
public String getProgramId() {
return programId;
}
public void setProgramId(String programId) {
this.programId = programId == null ? null : programId.trim();
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getInsistDay() {
return insistDay;
}
public void setInsistDay(Integer insistDay) {
this.insistDay = insistDay;
}
public Integer getWanderNum() {
return wanderNum;
}
public void setWanderNum(Integer wanderNum) {
this.wanderNum = wanderNum;
}
public Integer getGiveUpNum() {
return giveUpNum;
}
public void setGiveUpNum(Integer giveUpNum) {
this.giveUpNum = giveUpNum;
}
public Integer getFinishNum() {
return finishNum;
}
public void setFinishNum(Integer finishNum) {
this.finishNum = finishNum;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getTranscend() {
return transcend;
}
public void setTranscend(Integer transcend) {
this.transcend = transcend;
}
public String getProgram() {
return program;
}
public void setProgram(String program) {
this.program = program == null ? null : program.trim();
}
} |
Markdown | UTF-8 | 3,567 | 2.921875 | 3 | [] | no_license | # vue项目
## 项目使用的技术栈 Vue+Vuex+Router+Vant
## 项目位置(https://github.com/PieceCat/smile)
## 配置环境
### git操作
1. 打开git `mkdir vue`(项目名称)
2. `git config --global user.name xxx`
3. `git config --global user.email xxx@xx.com`
4. `git init`
## vue-cli配置
5. 打开vscode ctrl + ~ 打开控制台
6. 先检查npm版本,推荐5.x以上版本 `npm -v`
7. 全局安装vue-cli `npm install vue-cli -g`
8. 初始化项目 `vue init webpack`
9. 输入 `npm run dev` ,在浏览器打开localhost:8080
**有时浏览器版本或者浏览器本身问题,打开后会出现sources 中import Vue from "vue"处报错,后续的一些基于vue的组件无法显示效果,建议更换浏览器或者升级浏览器**
## 安装vant
### vant介绍(https://youzan.github.io/vant/#/zh-CN/intro):
1. 国人制造,复合中国网站样式和交互习惯;
2. 单元测试超过90%,有些个人的小样式组件是不作单元测试的;
3. 支持babel-plugin-import引入,按需加载插件,无需单独引入样式;
4. 支持TypeScript,JavaScript的超集;
5. 支持SSR,服务端渲染也是可以使用这个组件库的;
### vant安装
1. `npm i vant -S` 或者 `npm i vant --save`
2. 引入vant有两种方式
1.全局引入(会增加项目打包时的大小)
import Vant from 'vant'
import 'vant/lib/vant-css/index.css'
Vue.use(Vant)
2.使用 babel-plugin-import 引入
npm install babel-plugin-import -D 或者 npm install babel-plugin-import --save-dev
在 .babelrc中配置plugins
"plugins":["transform-vue-jsx", "transform-runtime",["import",{"libraryName":"vant","style":true}]]
在src/main.js中按需引入vant组件
1 import { Button } from 'vant'
2 Vue.use(Button)
3 <van-button type="primary">主要按钮</van-button>
## 布局适配
1. 在index.html中加入一下代码
let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth//获取设备屏幕宽度
let htmlDom = document.getElementsByTagName('html')[0] //获取html元素
if(htmlWidth>750){htmlWidth=750} //如果设备屏幕大于750 就等于750
htmlDom.style.fontSize = htmlWidth/20 + "px" //设置html的fontSize 也可以htmlWidth/设计稿的宽度*100 ,测量的时候获取到设计稿的实际px值除以100
2. 在meta标签中加入 `user-scalable=no` 禁止用户缩放
## 页面布局和路由设置
1. 在component文件下新建page文件夹,新建ShoppingMall.vue
2. 找到router文件夹下的index.js
import Vue from 'vue'
import Router from 'vue-router'
import ShoppingMall from '@/components/pages/ShoppingMall' //引入组件
Vue.use(Router)
export default new Router({
routes: [
{path: '/',name: 'ShoppingMall',component: ShoppingMall} //配置路由
]
})
//@代表项目的src目录
3. 建立ShoppingMall.vue (使用vue VSCode Snippets插件)
用vbs可以快速创建模板 vda快速创建data
<template>
<div>
{{msg}}
</div>
</template>
<script>
export default {
data () {
return {
msg: 'Shopping Mall'
}
}
}
</script>
### 首页布局注意点
1. 使用require引入图片 `require('../../assets/images/location.png')`
2. vant组件引用可以连写
import { Button, Row, Col ,Search , Swipe , SwipeItem } from 'vant'
Vue.use(Button).use(Row).use(Col).use(Search).use(Swipe).use(SwipeItem)
|
C# | UTF-8 | 2,128 | 2.546875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SGE.Cagravol.Application.ServiceModel
{
public class ResultModel : IResultModel
{
public bool Success { get; set; }
public string Message { get; set; }
public string ErrorMessage { get; set; }
public Exception Exception { get; set; }
public string ErrorCode { get; set; }
public ResultModel()
{
this.Success = false;
this.ErrorMessage = string.Empty;
this.ErrorCode = string.Empty;
this.Message = string.Empty;
this.Exception = null;
}
public ResultModel(bool success = false)
: this()
{
this.Success = success;
}
public IResultModel OnException(Exception ex, string errorCode = "")
{
this.Exception = ex;
this.ErrorMessage = ex.Message;
this.Success = false;
this.ErrorCode = errorCode;
return this;
}
public IResultModel OnError(string errorMessage = "", string errorCode = "")
{
this.Success = false;
this.ErrorMessage = errorMessage;
this.ErrorCode = errorCode;
return this;
}
public IResultModel OnError(IResultModel rm)
{
this.Success = false;
this.ErrorMessage = rm.ErrorMessage;
this.ErrorCode = rm.ErrorCode;
return this;
}
public IResultModel OnSuccess(string message = "")
{
this.Success = true;
this.Message = message;
this.ErrorCode = string.Empty;
return this;
}
public IResultModelJSON ToJSONModel()
{
return new ResultModelJSON()
{
errorCode = this.ErrorCode,
message = this.Message,
errorMessage = this.ErrorMessage,
success = this.Success
};
}
}
}
|
C++ | UTF-8 | 3,553 | 2.703125 | 3 | [] | no_license | #include "Money_public.h"
Money_public::Money_public() : Money(1,1,1,1,1,1,1,1,1,1,1,1) { }
Money_public::Money_public(double gg1000, double gg500, double gg200,
double gg100, double gg50, double gg20,
double gg10, double gg5, double gg2,
double gg1, double cc50, double cc10) : Money(gg1000, gg500, gg200, gg100, gg50, gg20, gg10, gg5, gg2, gg1, cc50, cc10) { }
Money_public::Money_public(const Money_public& r)
: Money(r.GetG1000(), r.GetG500(), r.GetG200(), r.GetG100(), r.GetG50(), r.GetG20(), r.GetG10(), r.GetG5(), r.GetG2(), r.GetG1(), r.GetC50(), r.GetC10()) { }
Money_public& Money_public::operator = (const Money_public& r)
{
Money(r.GetG1000(), r.GetG500(), r.GetG200(), r.GetG100(), r.GetG50(), r.GetG20(), r.GetG10(), r.GetG5(), r.GetG2(), r.GetG1(), r.GetC50(), r.GetC10());
return *this;
}
istream& operator >> (istream& in, Money_public& a)
{
double gg1000, gg500, gg200, gg100, gg50, gg20, gg10, gg5, gg2, gg1, cc50, cc10;
do {
cout << " 1000 - ? "; in >> gg1000;
cout << " 500 - ? "; in >> gg500;
cout << " 200 - ? "; in >> gg200;
cout << " 100 - ? "; in >> gg100;
cout << " 50 - ? "; in >> gg50;
cout << " 20 - ? "; in >> gg20;
cout << " 10 - ? "; in >> gg10;
cout << " 5 - ? "; in >> gg5;
cout << " 2 - ? "; in >> gg2;
cout << " 1 - ? "; in >> gg1;
cout << " 0.50 - ? "; in >> cc50;
cout << " 0.10 - ? "; in >> cc10;
if (!a.Init(gg1000, gg500, gg200, gg100, gg50, gg20, gg10, gg5, gg2, gg1, cc50, cc10))
{
cout << endl << " Error! Enter right number. " << endl;
}
cout << endl;
} while (!a.Init(gg1000, gg500, gg200, gg100, gg50, gg20, gg10, gg5, gg2, gg1, cc50, cc10));
a.SetG1000(gg1000); a.SetG500(gg500); a.SetG200(gg200); a.SetG100(gg100); a.SetG50(gg50);
a.SetG20(gg20); a.SetG10(gg10); a.SetG5(gg5); a.SetG2(gg2); a.SetG1(gg1); a.SetC50(cc50); a.SetC10(cc10);
cout << endl;
return in;
}
Money_public::operator string () const
{
stringstream sstr;
sstr << " 1000 - " << GetG1000() * 1000. << endl;
sstr << " 500 - " << GetG500() * 500. << endl;
sstr << " 200 - " << GetG200() * 200. << endl;
sstr << " 100 - " << GetG100() * 100. << endl;
sstr << " 50 - " << GetG50() * 50. << endl;
sstr << " 20 - " << GetG20() * 20. << endl;
sstr << " 10 - " << GetG10() * 10. << endl;
sstr << " 5 - " << GetG5() * 5. << endl;
sstr << " 2 - " << GetG2() * 2. << endl;
sstr << " 1 - " << GetG1() * 1. << endl;
sstr << " 0.50 - " << GetC50() * 0.5 << endl;
sstr << " 0.10 - " << GetC10() * 0.1 << endl;
return sstr.str();
}
ostream& operator << (ostream& out, const Money_public& r)
{
out << string(r);
return out;
}
double Money_public::get_sum()
{
return (GetG1000() * 1000. + GetG500() * 500. + GetG200() * 200. + GetG100() * 100. + GetG50() * 50. +
GetG20() * 20. + GetG10() * 10. + GetG5() * 5. + GetG2() * 2. + GetG1() * 1. + GetC50() * 0.50 + GetC10() * 0.1);
}
void Money_public::Comparison(Money_public& sum1, Money_public& sum2)
{
if (sum1.get_sum() > sum2.get_sum()) { cout << " SUMM_1 > SUMM_2 " << endl; }
else
if (sum1.get_sum() < sum2.get_sum()) { cout << " SUMM_1 < SUMM_2 " << endl; }
else
if (sum1.get_sum() == sum2.get_sum()) { cout << " SUMM_1 = SUMM_2 " << endl; }
}
void Money_public::Divide(Money_public& sum1, Money_public& sum2)
{
if (sum1.get_sum() >= sum2.get_sum())
{
cout << " DIVIDE = " << setprecision(3) << sum1.get_sum() / sum2.get_sum() << endl;
}
else
if (sum1.get_sum() <= sum2.get_sum())
{
cout << " DIVIDE = " << setprecision(3) << sum2.get_sum() / sum1.get_sum() << endl;
}
} |
PHP | UTF-8 | 2,585 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Admin;
use App\Role;
use Illuminate\Http\Request;
class RoleController extends BaseAdminController
{
/**
*
*/
public function __construct()
{
parent::__construct();
}
/**
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request)
{
$limit = 20;
if ($request->has('limit')) {
$limit= $request->get('limit');
}
$roles = Role::paginate($limit);
return view('admin.role.index', ['roles' => $roles] );
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.role.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'desc' => 'required',
'status' => 'required'
]);
Role::create($request->all());
$request->session()->flash('message','insert completed');
return back();
}
/**
* @param $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function show($id)
{
$data['role'] = Role::findOrFail($id);
return view('admin.role.show',$data);
}
/**
* @param $id
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit($id)
{
$data['role'] = Role::findOrFail($id);
return view('admin.role.edit',$data);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Role $role
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Role $role)
{
request()->validate([
'name' => 'required',
'desc' => 'required',
'status' => 'required'
]);
Role::update($request->all());
return redirect('admin/role')->with('success','updated successfully');
}
/**
* @param $id
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($id)
{
Role::findOrFail($id)->delete();
return redirect('admin/role')->with('message','delete success');
}
}
|
Java | UTF-8 | 4,032 | 2.25 | 2 | [
"Apache-2.0",
"EPL-1.0",
"MIT",
"BSD-3-Clause"
] | permissive | /*
Copyright (C) 2013-2021 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.client;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.netty.util.AsciiString;
/**
* Contains the names for the headers that Styx will add to proxied requests/responses.
*/
public class StyxHeaderConfig {
public static final String STYX_INFO_DEFAULT = "X-Styx-Info";
public static final String ORIGIN_ID_DEFAULT = "X-Styx-Origin-Id";
public static final String REQUEST_ID_DEFAULT = "X-Styx-Request-Id";
public static final String STYX_INFO_FORMAT_DEFAULT = "{INSTANCE};{REQUEST_ID}";
private final CharSequence styxInfoHeaderName;
private final CharSequence originIdHeaderName;
private final CharSequence requestIdHeaderName;
private final String styxInfoHeaderFormat;
public StyxHeaderConfig(@JsonProperty("styxInfo") StyxHeader styxInfoHeader,
@JsonProperty("originId") StyxHeader originIdHeader,
@JsonProperty("requestId") StyxHeader requestIdHeader) {
this.styxInfoHeaderName = name(styxInfoHeader, STYX_INFO_DEFAULT);
this.originIdHeaderName = name(originIdHeader, ORIGIN_ID_DEFAULT);
this.requestIdHeaderName = name(requestIdHeader, REQUEST_ID_DEFAULT);
this.styxInfoHeaderFormat = valueFormat(styxInfoHeader, STYX_INFO_FORMAT_DEFAULT);
}
public StyxHeaderConfig() {
// uses defaults
this(null, null, null);
}
public CharSequence styxInfoHeaderName() {
return styxInfoHeaderName;
}
public CharSequence originIdHeaderName() {
return originIdHeaderName;
}
public CharSequence requestIdHeaderName() {
return requestIdHeaderName;
}
public String styxInfoHeaderFormat() {
return styxInfoHeaderFormat;
}
private static AsciiString name(StyxHeader header, String defaultName) {
if (header == null || header.name == null) {
return new AsciiString(defaultName);
}
return new AsciiString(header.name);
}
private static String valueFormat(StyxHeader header, String formatDefault) {
if (header == null || header.valueFormat == null) {
return formatDefault;
}
return header.valueFormat;
}
@Override
public String toString() {
return new StringBuilder(128)
.append(this.getClass().getSimpleName())
.append("{styxInfoHeaderName=")
.append(styxInfoHeaderName)
.append(", originIdHeaderName=")
.append(originIdHeaderName)
.append(", requestIdHeaderName=")
.append(requestIdHeaderName)
.append(", styxInfoHeaderFormat=")
.append(styxInfoHeaderFormat)
.append('}')
.toString();
}
/**
* Pojo used to parse header from config file.
*/
public static final class StyxHeader {
private final String name;
private final String valueFormat;
@JsonCreator
public StyxHeader(@JsonProperty("name") String name,
@JsonProperty("valueFormat") String valueFormat) {
this.name = name;
this.valueFormat = valueFormat;
}
@Override
public String toString() {
return "[name=" + name + ",vf=" + valueFormat + "]";
}
}
}
|
C++ | IBM866 | 2,560 | 2.5625 | 3 | [] | no_license | #ifndef __MISC_INCLUDE__
#define __MISC_INCLUDE__
#include <types.h>
#include <math.h>
////////////////////////////////////////////////////////////////////////////////
///Swap
////////////////////////////////////////////////////////////////////////////////
template <class Type>
void swap (Type& v1,Type& v2)
{
Type temp = v1;
v1 = v2;
v2 = temp;
}
////////////////////////////////////////////////////////////////////////////////
///CRC32
////////////////////////////////////////////////////////////////////////////////
extern ulong crc_32_tab [];
ulong CRC32 (const void* data,int size,ulong crc=0xFFFFFFFF);
inline ulong CRC32 (uchar data,ulong crc)
{ return crc_32_tab[(crc^data)&0xff]^(crc>>8); }
////////////////////////////////////////////////////////////////////////////////
/// ப ( ᪨ 䠢)
////////////////////////////////////////////////////////////////////////////////
extern char toUpper [256];
extern char toLower [256];
char* upcase (const char*,char*);
char* locase (const char*,char*);
inline char ToUpperEx(char x) { return toUpper [(uchar)x]; }
inline char ToLowerEx(char x) { return toLower [(uchar)x]; }
////////////////////////////////////////////////////////////////////////////////
///Memory
////////////////////////////////////////////////////////////////////////////////
void memsetw (void*,uint16,int num); //num!!!
void memsetd (void*,uint,int);
////////////////////////////////////////////////////////////////////////////////
///Random
////////////////////////////////////////////////////////////////////////////////
uint random (uint max);
inline float randomfl () { return float (random (20000)) / 20000.0f; }
////////////////////////////////////////////////////////////////////////////////
///Math
////////////////////////////////////////////////////////////////////////////////
template <class Type> inline Type sqr (Type x) { return x * x; }
inline float GetAngle (float dx,float dy)
{
if (dx <= 0) return acos (dy);
else return -acos (dy);
}
////////////////////////////////////////////////////////////////////////////////
///Utilites
////////////////////////////////////////////////////////////////////////////////
class Window;
int WND_Done (Window*,UINT,WORD,DWORD,DWORD);
void W32_PostQuitMessage (int);
BOOL W32_SetCursorPos (int,int);
#endif |
Markdown | UTF-8 | 4,440 | 2.734375 | 3 | [] | no_license | ---
layout: post
title: 一些面试题
tags: code interview
---
已经有一段时间没有面试了,感觉最近有些颓废,整理一些自己的面试问题啥的。
Q: css 如何实现水平垂直居中
送分题,先从这道题开始
Q: 如何实现 dark mode
很多种方式,可以 css variables, 或者 dymaic load 都行,随便聊聊。进一步还可以探讨下 css methodologies ,讨论下 atomic css, css modules 啥的,还是看情况吧。
Q: 手写去重
暴力解也行,基本送分题
Q: 如何检测浏览器的性能。空闲的时候做一些事情
大概从 `setTimeout` 开始谈起,引申到 `requestAnimationFrame` 继而谈到 `Promise` 顺便就能带一下事件模型,从中也可以继续谈 `Vue.nextTick` 或者 React 中的切分任务后的实现,看看候选人能不能聊到 `MutateObserver` , `requestIdleCallback` 等新式 API 和设计
纯性能检测得提 `performance` 的一些 API,查内存。不过不是特别重要。
如果还能聊,继续谈谈 node.js 事件模型,再往下到 epoll 和异步模型的概念了。到这里可以转到 `process`, `thread` , `coroutine`, `fiber` 之类的概念解释。
Q: 有哪些优化策略。
随便讲,从 http cache, dns prefetch, cdn 到资源压缩,图片格式什么的。还能穿插 pwa,压缩算法之类的应该蛮有意思。
这里 TCP/HTTP 是绕不开的,还得继续流程。中间谈到 HTTPS 可以介绍 TLS 证书校验的概念,细节可以到 RSA, AES 的算法实现。这里还可以问问怎么攻击 HTTPS 很有意思。
Q: event loop
前端面试八股文,没啥意思,但是如果感觉面试者是背过的,可以让他背一下拯救尴尬的场面,随便聊聊吧。
前面性能检测部分如果谈到可以跳过
Q: 内存泄漏及如何避免
简述吧,看看代码写得安全不,如何产生的,如何避免,怎么显示清理。
如果能到介绍 GC 基础算法就不错,如果有优化算法的介绍就更好了。
Q: 正则手机号
简单看看正则,一般不会太复杂
Q: js bridge 如何实现
如果有写 hybird 的简历,可以问问看。感觉没啥意思。
Q: 框架有关
React 问 hooks 实现,手写可以来个 `useInterval` 涉及到了蛮多东西的,很有意思。数据流聊一聊,看看怎么理解单向数据流的,还能继续就聊聊 `saga`
Vue 不是很懂, `defineProperty` 和 `proxy` 问烂了,就问问如何实现模板的事件绑定吧。数据流继续 flux 思想
ng 直接 ng
更多可以聊聊新潮得 next.js, gatsby 这些,看情况。
Q: git 操作
看看是不是除了三板斧之外还了解别的,比如 bisect, cherry-pick, merge, rebase 这种,另外 tag 和 branch 策略也可以聊聊
Q: 工程相关问问如何保证可用性
前端的报错怎么处理,性能监控怎么做,CI & CD怎么做,单元测试有没有
这段我还没想清楚怎么聊能更好地理解候选人的架构设计能力。仅限参考
Q: 聊聊最近看的最 wow (惊叹) 的东西,技术最好,非技术也行
比如最近刷屏的 web container 文章,或者新的浏览器渲染策略。
非技术可以说什么哲学思想,金融,历史?随便吧
有惊喜的话可以接着聊,算是加分项
---------------
整个过程我感觉自己对于设计可能更看重一些,可以看出我还是有些践行自己 **不把 bug 当 feature 问** 的价值观,这点儿还行。
算法没怎么问,我也基本只是 easy 到 medium 再高了我自己都不会写可不敢问。然后二进制计算的我是不会问的,这个东西知道就是知道,不知道想破脑袋也想不出来。
计算机基础,其实我很想去问,但是做前端天生被浏览器屏蔽了太多的东西,没办法往下了解。所以大多数时候我会把这个环节换成能不能试着探索候选人的学习能力和好奇心。
-------------
其实我很想在面试时从两个超大数字相除的问题开始,例如 `4983934826 / 33`。这一招是从之前的 leader 身上学来的,但是我还不敢这么开始,他也从未尝试过。
这道题看着很傻,实际上解法也是纯暴力解,两个数字都是随机想出来的。目的只是看候选人的耐心。其实就经历来看,我个人感觉至少三成候选人答不了这道除法题。。。
TODO: 有空更新下后端的面试题
|
Markdown | UTF-8 | 1,554 | 4.09375 | 4 | [
"MIT"
] | permissive | # 题目
## 反转字符串中的单词
### 来源:
[力扣-反转字符串中的单词](https://leetcode.cn/problems/reverse-words-in-a-string/description/)
### 题目内容
给你一个字符串 `s` ,请你反转字符串中 **单词** 的顺序。
**单词** 是由非空格字符组成的字符串。`s` 中使用至少一个空格将字符串中的 **单词** 分隔开。
返回 **单词** 顺序颠倒且 **单词** 之间用单个空格连接的结果字符串。
**注意:** 输入字符串
`s`中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
**示例 1:**
**输入:** s = "the sky is blue"
**输出:** "blue is sky the"
**示例 2:**
**输入:** s = " hello world "
**输出:** "world hello"
**解释:** 反转后的字符串中不能存在前导空格和尾随空格。
**示例 3:**
**输入:** s = "a good example"
**输出:** "example good a"
**解释:** 如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。
**提示:**
* `1 <= s.length <= 104`
* `s` 包含英文大小写字母、数字和空格 `' '`
* `s` 中 **至少存在一个** 单词
**进阶:** 如果字符串在你使用的编程语言中是一种可变数据类型,请尝试使用 `O(1)` 额外空间复杂度的 **原地** 解法。
|
C++ | UTF-8 | 695 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <set>
#include <string>
#include <boost/array.hpp>
struct println {
template<typename T>
void operator()(const T& t) const {
std::cout << t << ", ";
}
};
template<class Cont>
void print_all(const Cont& c)
{
std::for_each(c.begin(), c.end(), println());
std::cout << std::endl;
}
int main(void)
{
std::vector<double> v;
v.push_back(1.2);
v.push_back(3.4);
std::list<int> lst;
lst.push_back(-5);
lst.push_back(-6);
std::set<char> s;
s.insert('X');
s.insert('Y');
boost::array<std::string, 2> a = {"aaa", "bbb"};
print_all(v);
print_all(lst);
print_all(s);
print_all(a);
return 0;
}
|
Shell | UTF-8 | 541 | 3.421875 | 3 | [] | no_license | #!/usr/bin/env bash
# Jordan Justen : this file is public domain
source "$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"/menv
if [[ -f "$MESA_BUILD_DIR/build.ninja" ]]; then
NINJA=1
else
NINJA=0
fi
if [[ "$NINJA" -ne 0 ]]; then
nice -n 20 ninja -C "$MESA_BUILD_DIR" "$@" && \
ninja -C "$MESA_BUILD_DIR" install
NRESULT=$?
else
cd "$MESA_BUILD_DIR" && \
PATH=/usr/lib/ccache:$PATH make -j8 "$@" &&
make -j8 install
NRESULT=$?
fi
echo "Built $MESA_DIR => $NRESULT"
exit $NRESULT
|
Python | UTF-8 | 546 | 3.296875 | 3 | [] | no_license | import sys
read = sys.stdin.readline
# n = int(read())
n,r,c = map(int,read().rstrip().split())
# 2^n 의 행렬 count 먹이기
def count(n,r,c):
if n == 0:
return 0
idx = 2**(n-1)
k = idx ** 2
# A,B,C,D 0을 할지, 1을 할지 열로 검증
res = k if c >= idx else 0
# 2를 더할지, 더하지 않을지 행으로 **바로** 검증
res += 2*k if r >= idx else 0
# idx 로 나눠줘도, 앞에 행, 열은 영향받지 않는다.
return res + count(n-1,r%idx,c%idx)
print(count(n,r,c))
|
Java | UTF-8 | 2,000 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | package com.tolsma.pieter.turf.gui.panel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import com.tolsma.pieter.turf.database.BillManager;
import com.tolsma.pieter.turf.database.ItemManager;
import com.tolsma.pieter.turf.database.PersonManager;
import com.tolsma.pieter.turf.items.Item;
import com.tolsma.pieter.turf.items.Person;
import com.tolsma.pieter.turf.items.Transaction;
import com.tolsma.pieter.turf.listener.CustomMouseListener;
import com.tolsma.pieter.turf.util.Constants;
public class MainItemPanel extends JPanel {
public MainItemPanel(RightPanel rightPanel) {
this.setLayout(new GridLayout(2, 1));
this.setBackground(Color.BLACK);
JButton bier = new JButton("BIER");
bier.setOpaque(true);
bier.setBorderPainted(false);
bier.setForeground(Color.YELLOW);
bier.setBackground(Constants.GREEN);
bier.setFont(RightPanel.FONT);
bier.addMouseListener(new CustomMouseListener(Constants.GREEN, Constants.GREEN_HIGHLIGHT, bier));
Item item = ItemManager.getInstance().getBiertje();
bier.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ArrayList<Person> persons = PersonManager.getInstance().getSelectedPersons();
if (persons.size() == 0) {
JOptionPane.showMessageDialog(rightPanel, "Klik eerst op een persoon!");
}
for (Person p : persons) {
boolean succes = false;
for (Transaction itemLabel : BillManager.getInstance().getElements()) {
if (itemLabel.getItem().equals(item)) {
if (itemLabel.sameParticipants()) {
itemLabel.addCount();
succes = true;
}
}
}
if (!succes) {
BillManager.getInstance().getElements().add(new Transaction(item));
}
}
rightPanel.update();
}
});
add(bier);
MiscItemPanel miscItemPanel = new MiscItemPanel(rightPanel);
add(miscItemPanel);
}
}
|
Python | UTF-8 | 641 | 2.96875 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pymysql
connector = pymysql.connect("localhost", "root", "password", "food_nutrition", charset='utf8')
# 连接时,加入charset='utf8',可以在输出时正确显示中文
cursor = connector.cursor()
cursor.execute("select * from food")
data = cursor.fetchall()
for row in data:
#for column in row:
# print(column, end=" | ")
print(row)
# 执行事务
# 事务机制可以确保数据一致性
try:
# 执行SQL语句
cursor.execute('select * from food')
# 向数据库提交
connector.commit()
except:
# 发生错误时回滚
connector.rollback() |
C# | UTF-8 | 802 | 3.421875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
namespace Planner
{
class City
{
/*
Name of the city.
The mayor of the city.
Year the city was established.
A collection of all of the buildings in the city.
A method to add a building to the city. Yay!
*/
private string _cityName { get; set; }
private int _yearEstablished { get; set; }
public string Mayor { get; set; }
public List<Building> AllBuildings = new List<Building>();
public City (string cityName, int yearEstablished) {
_cityName = cityName;
_yearEstablished = yearEstablished;
}
public void AddBuilding(Building building) {
AllBuildings.Add(building);
}
}
} |
PHP | UTF-8 | 1,671 | 2.625 | 3 | [] | no_license | <?php
/**
* @copyright: Copyright © 2017 Firebear Studio GmbH. All rights reserved.
* @author : Firebear Studio <fbeardev@gmail.com>
*/
namespace Firebear\ImportExport\Api\Data;
/**
* Interface ImportInterface
*
* @package Firebear\ImportExport\Api\Data
*/
interface ImportInterface extends AbstractInterface
{
const IMPORT_SOURCE = 'import_source';
const MAP = 'map';
const XSLT = 'xslt';
const TRANSLATE_FROM = "translate_from";
const TRANSLATE_TO = "translate_to";
/**
* Get Import Source
*
* @return mixed
*/
public function getImportSource();
/**
* @return string
*/
public function getMapping();
/**
* @return string
*/
public function getPriceRules();
/**
* @return string
*/
public function getXslt();
/**
* @param string $source
*
* @return ImportInterface
*/
public function setImportSource($source);
/**
* @param $mapping
*
* @return ImportInterface
*/
public function setMapping($mapping);
/**
* @param $priceRules
*
* @return ImportInterface
*/
public function setPriceRules($priceRules);
/**
* @param $xslt
*
* @return ImportInterface
*/
public function setXslt($xslt);
/**
* @return mixed
*/
public function getTranslateFrom();
/**
* @return mixed
*/
public function getTranslateTo();
/**
* @param $val
*
* @return mixed
*/
public function setTranslateFrom($val);
/**
* @param $val
*
* @return mixed
*/
public function setTranslateTo($val);
}
|
Python | UTF-8 | 698 | 2.828125 | 3 | [] | no_license | import shapefile
import matplotlib.pyplot as plt
import csv
def plot(sf):
plt.figure()
for shape in sf.shapeRecords():
x = [i[0] for i in shape.shape.points[:]]
y = [i[1] for i in shape.shape.points[:]]
plt.plot(x,y)
plt.show()
def fieldsnrecords(sf):
print 0
records = sf.records()
print 1
fields = sf.fields
print 2
shapes = sf.shapes()
print 3
for x in range(len(records)):
print records[x][0], records[x][1], records[x][2]
#if records[x][1] == 'PA':
# for y in range(len(records[x])):
# print fields[y+1], records[x][y]
# print shapes[x]
if __name__ == '__main__':
sf = shapefile.Reader("State_2010Census_DP1/State_2010Census_DP1")
plot(sf)
fieldsnrecords(sf)
|
Java | UTF-8 | 1,295 | 1.921875 | 2 | [] | no_license | package gov.nih.nlm.meme.web;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class MappingActionForm
extends ActionForm {
private String host;
private int mapsetId;
private String midService;
private String port;
private String pageDirection;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(String port) {
this.port = port;
}
public void setMidService(String midService) {
this.midService = midService;
}
public void setMapsetId(int mapsetId) {
this.mapsetId = mapsetId;
}
public int getMapsetId() {
return mapsetId;
}
public String getMidService() {
return midService;
}
public String getPort() {
return port;
}
public void setPageDirection(String pageDirection) {
this.pageDirection = pageDirection;
}
public String getPageDirection() {
return pageDirection;
}
public ActionErrors validate(ActionMapping actionMapping,
HttpServletRequest httpServletRequest) {
/** @todo: finish this method, this is just the skeleton.*/
return null;
}
public void reset(ActionMapping actionMapping,
HttpServletRequest servletRequest) {
}
}
|
C++ | UTF-8 | 1,799 | 2.9375 | 3 | [] | no_license | #ifndef NGTK_LABEL_H_
#define NGTK_LABEL_H_
#include "gtk_misc.h"
namespace nodeGtk {
class NodeGtkLabel: public NodeGtkMisc {
public:
static v8::Persistent<v8::FunctionTemplate> constructor_template;
/**
* Constructor. Creates a new Label, which will wrap a new GtkLabel
*/
NodeGtkLabel(gchar *text);
NodeGtkLabel(GtkLabel *label);
/**
* Checks to see if a v8::Object is a Label in disguise
*
* Parameters:
* obj - The object to check for Labelness
*
* Returns:
* True if the object is a label, false otherwise
*/
static inline bool HasInstance(v8::Handle<v8::Object> val) {
v8::HandleScope scope;
if (val->IsObject()) {
v8::Local<v8::Object> obj = val->ToObject();
if (constructor_template->HasInstance(obj)) {
return true;
}
}
return false;
}
/**
* For getting the underlying GtkWidget.
*
* Usage:
* (code)
* GtkLabel *label = Label::Data(args[n]->ToObject());
* (end)
*
* Returns:
* The pointer to the GtkLabel contained in this Label
*/
static inline GtkLabel* Data (v8::Handle<v8::Object> obj) {
v8::HandleScope scope;
return GTK_LABEL(ObjectWrap::Unwrap<NodeGtkLabel>(obj)->getWidget());
}
static void SetupMethods (v8::Handle<v8::Object> target);
static void SetupCallbacks(std::vector<SignalCallback> *callbacks);
static void Initialize (v8::Handle<v8::Object> target);
/**
* Retrieves a reference to this instance from the widget
*
* Parameters:
* object - The GtkLabel that holds the reference
*/
static NodeGtkLabel* From(GtkLabel *object) {
NodeGtkLabel *button;
NODE_GTK_GET_REF(object, button, NodeGtkLabel);
return button;
}
};
} // namespace ngtk
#endif
|
C++ | UTF-8 | 774 | 2.890625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool binarysearch(vector<int>v, int x)
{
int l=0, h=v.size()-1, m;
if(v[l]==x || v[h]==x)
return true;
while(l<=h)
{
m=(l+h)/2;
if(x > v[m])
l=m+1;
else if(x < v[m])
h=m-1;
else return true;
}
return false;
}
int main()
{
vector<int>s;
int i=1,n,y,f=0;
cin>>y;
n=i*(i+1);
n=n/2;
s.push_back(n);
i++;
while(1)
{
n=i*(i+1)/2;
s.push_back(n);
if(n>1000000000)
break;
i++;
}
for(int j=0;s[j]<=y/2;++j)
{
if(binarysearch(s, y-s[j]))
{f=1;
break;}
}
if(f==1)
cout<<"YES";
else cout<<"NO";
return 0;
}
|
C++ | UTF-8 | 496 | 3.078125 | 3 | [] | no_license | #ifndef EVENT_H
#define EVENT_H
#include <string>
#include "Date.h"
class Event : public Date
{
private:
int eventID;
std::string description;
public:
// Constructor
Event(int d, int m, int y, int ID, std::string desc) : Date(d,m,y)
{
eventID = ID;
description.assign(desc);
}
int getID() const;
std::string getDesc() const;
void updateDesc (std::string newDesc) ;
};
#endif
|
Go | UTF-8 | 1,635 | 3.25 | 3 | [
"Apache-2.0"
] | permissive | package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
"testing"
"time"
"github.com/gohugoio/hugo/resources/page"
)
var expected *PageEntry
func setUp() {
myDate, _ := time.Parse(time.RFC3339, "2015-12-09T22:15:11+01:00")
expected = &PageEntry{
Type: "page",
Section: "",
Content: "Lorem ipsum Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n",
WordCount: 10,
ReadingTime: 1,
Keywords: []string{"keyword"},
Date: myDate,
LastModified: myDate,
}
}
// test single author
func TestNewPageForIndex(t *testing.T) {
setUp()
expected.Title = "Title-page-1"
expected.Author = "Author1Page1"
actual := newIndexEntry(findPage(expected.Title))
comparePages(t, actual, expected)
}
// test multiple authors
func TestNewPageForIndex2(t *testing.T) {
setUp()
expected.Title = "Title-page-2"
expected.Author = "Author1Page2, Author2Page2"
actual := newIndexEntry(findPage(expected.Title))
comparePages(t, actual, expected)
}
func comparePages(t *testing.T, actual *PageEntry, expected *PageEntry) {
if !reflect.DeepEqual(expected, actual) {
t.Error("Values don't match!")
printPage("Expected:", expected)
printPage("but was:", actual)
}
}
// find first page with specified title
func findPage(title string) page.Page {
pages := readSitePages(testHugoPath)
for _, page := range pages {
if page.Title() == title {
return page
}
}
return nil
}
// print struct as pretty formatted json
func printPage(label string, page *PageEntry) {
fmt.Println(label)
data, _ := json.MarshalIndent(page, "", " ")
os.Stdout.Write(data)
fmt.Println()
}
|
Python | UTF-8 | 2,763 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Composite gate, a container for a sequence of unitary gates.
"""
import warnings
from qiskit.exceptions import QiskitError
from .gate import Gate
class CompositeGate(Gate): # pylint: disable=abstract-method
"""Composite gate, a sequence of unitary gates."""
def __init__(self, name, params, inverse_name=None):
"""Create a new composite gate.
name = instruction name string
params = list of real parameters
"""
warnings.warn('CompositeGate is deprecated and will be removed in v0.9. '
'Any Instruction can now be composed of other sub-instructions. '
'To build them, you construct a circuit then use '
'circuit.to_instruction().', DeprecationWarning)
super().__init__(name, params)
self.data = [] # gate sequence defining the composite unitary
self.inverse_flag = False
self.inverse_name = inverse_name or (name + 'dg')
def instruction_list(self):
"""Return a list of instructions for this CompositeGate.
If the CompositeGate itself contains composites, call
this method recursively.
"""
instruction_list = []
for instruction in self.data:
if isinstance(instruction, CompositeGate):
instruction_list.extend(instruction.instruction_list())
else:
instruction_list.append(instruction)
return instruction_list
def append(self, gate):
"""Attach a gate."""
self.data.append(gate)
return gate
def _attach(self, gate):
"""DEPRECATED after 0.8."""
self.append(gate)
def _check_dups(self, qubits):
"""Raise exception.
if list of qubits contains duplicates.
"""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise QiskitError("duplicate qubit arguments")
def qasm(self):
"""Return OPENQASM string."""
return "\n".join([g.qasm() for g in self.data])
def inverse(self):
"""Invert this gate."""
self.data = [gate.inverse() for gate in reversed(self.data)]
self.inverse_flag = not self.inverse_flag
return self
def q_if(self, *qregs):
"""Add controls to this gate."""
self.data = [gate.q_if(qregs) for gate in self.data]
return self
def c_if(self, classical, val):
"""Add classical control register."""
self.data = [gate.c_if(classical, val) for gate in self.data]
return self
|
C# | UTF-8 | 845 | 2.71875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApiCrawlerTuTV.Model {
public class Actor : IComparable<Actor> {
public int id { get; set; }
public int tvDbId { get; set; }
public String name { get; set; }
public int age { get; set; }
public double actorUserRating { get; set; }
public DateTime created { get; set; }
public DateTime updated { get; set; }
public int CompareTo(Actor other) {
return this.id.CompareTo(other.id);
}
public override bool Equals(object obj) {
return this.id.Equals(((Actor)obj).id);
}
public override int GetHashCode() {
return this.id.GetHashCode();
}
}
}
|
Java | UTF-8 | 768 | 2.703125 | 3 | [] | no_license | package com.koo_proto.v0;
import java.util.ArrayList;
import java.util.UUID;
public class RestaurantOrder {
private UUID mRestaurantID;
private ArrayList<UUID> mOrderedDishIDs;
public RestaurantOrder(UUID restaurantID) {
mRestaurantID = restaurantID;
mOrderedDishIDs = new ArrayList<UUID>();
}
public UUID getRestaurantID() {
return mRestaurantID;
}
public void addDish(UUID dishID) {
mOrderedDishIDs.add(dishID);
}
public boolean removeDish(UUID dishID) {
if (mOrderedDishIDs.contains(dishID)) {
mOrderedDishIDs.remove(dishID);
return true;
}
return false;
}
public boolean contains(UUID dishID) {
return mOrderedDishIDs.contains(dishID);
}
public ArrayList<UUID> getOrderedDishIDs() {
return mOrderedDishIDs;
}
}
|
C++ | UTF-8 | 3,940 | 2.578125 | 3 | [
"MIT"
] | permissive |
/*
* IMPORTANT: The SD Card is powered from the peripheral voltage regulator so it can be shut down when the system is sleeping (when only the RTC is running)
* The SD Card will not work properly when the peripheral power supply is OFF.
*
* The Settings file will be looked for on initialisation and read if found
* The settings file gets passed to the command handler and is read just as if it is a series of commands sent over the serial port
*/
void setupSDHC(){
//Set up the command buffer
//if(DEBUGGING) DEBUG.println("Resetting Buffer");
//if(DEBUGGING) delay(100);
resetBuffer(bufferSD);
//Set to read from a file instead of serial
//if(DEBUGGING) DEBUG.println("Set port mode");
setPortMode(bufferSD, FILEREADER_COMMAND);
//Set the serial port so we can still print replies
//if(DEBUGGING) DEBUG.println("Set Primary Port");
bufferSD.port = &USBS;
//if(DEBUGGING) DEBUG.println("Reserving buffer");
bufferSD.bufferString.reserve(SBUFFER);
//if(DEBUGGING) DEBUG.println("Reserving Pending Buffer");
bufferSD.pendingCommandString.reserve(SBUFFER);
//if(DEBUGGING) DEBUG.println("Checking Power");
if(!device.peripheralPowerOn){
printErln("SDCard not powered up");
return;
}
//if(DEBUGGING) DEBUG.println("Setting Pins");
pinMode(SDCD, INPUT_PULLUP);
//if(DEBUGGING) DEBUG.println("Setting SDWP");
//pinMode(SDWP, INPUT_PULLUP);
pinMode(SDWP, OUTPUT);
//if(DEBUGGING) DEBUG.println("Setting SS");
pinMode(SS, OUTPUT);
//if(DEBUGGING) DEBUG.println("Setting SDWP state");
digitalWrite(SDWP, 0); //SDWP connects to SDCD when a card is inserted.
//if(DEBUGGING) DEBUG.println("Attaching int");
//attachInterrupt(digitalPinToInterrupt(SDCD), cardDetect_isr, CHANGE);
if(DEBUGGING) DEBUG.println("Checking for card");
//delay(100);
startSD();
}
void startSD(){
device.cardPresent = cardInserted();
//if(DEBUGGING && device.cardPresent) DEBUG.println("Card detected");
//if(DEBUGGING && !device.cardPresent) DEBUG.println("Card not detected");
//if(DEBUGGING) DEBUG.println("Attempting to initialise card");
if(device.cardPresent) tryInitSDCard();
else printErln("SDCard not present");
}
void tryInitSDCard(){
if(!device.peripheralPowerOn){
printErln("DEBUG: SDCard not powered up");
return;
}
if (!SD.begin(SS, SD_SCK_MHZ(50))) {
device.cardInitError = true;
printErln("DEBUG: SDCard Init Error");
}
else{
//SD.initErrorHalt();
device.cardInitError = false;
DEBUG.println("DEBUG: SDCard is ready");
}
}
bool checkForSettings(){
if (SD.exists("settings.txt")) {
DEBUG.println("DEBUG: settings file found.");
device.cardSettingsFile = true;
} else {
DEBUG.println("DEBUG: settings file not found.");
device.cardSettingsFile = false;
}
return device.cardSettingsFile;
}
void startReadDeviceSettings(){
//Open the settings file
bufferSD.fileReader = SD.open("settings.txt" , FILE_READ);
}
bool readDeviceSettings(){
return checkPort(bufferSD); //reads a line and returns true if more are available or false if end of file reached
}
void endReadDeviceSettings(){
//Closes the file
bufferSD.fileReader.close();
}
bool cardInserted(){
return !digitalRead(SDCD);
}
void cardDetect_isr(){
if(cardInserted()) device.deviceState = DCU_RESTARTING_SDHC;
else endSD();
}
void endSD(){
if(device.dataFileOpen){
closeLogFile();
}
device.cardPresent = false;
device.cardInitError = false;
device.dataFileOpen = false;
device.cardSettingsFile = false;
if(DEBUGGING)DEBUG.println("Card Removed");
//SD.end();
}
bool sdUnavailable(){
if(device.cardInitError == true || device.peripheralPowerOn == false){
printEr("SD Unavailable");
return true;
}
return false;
}
void printDirectory(Stream &port){
//print contents of SD card root directory to USB Serial
if(sdUnavailable()) return;
port.println("SD Card Root:");
//SD.ls(LS_R);
}
|
Python | UTF-8 | 20,981 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | import math
import numpy
import random
import typing
from collections import deque
from typing import List
import stock_exchange # circular dependency!
from experts.obscure_expert import ObscureExpert
from framework.period import Period
from framework.portfolio import Portfolio
from framework.stock_market_data import StockMarketData
from framework.interface_expert import IExpert
from framework.interface_trader import ITrader
from framework.order import Order, OrderType
from framework.vote import Vote
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam, Nadam, SGD
from framework.order import Company
from framework.utils import save_keras_sequential, load_keras_sequential
from framework.logger import logger
from dh.StateExpertsOnly import StateExpertsOnly
from dh.StateExpertsCashShares import StateExpertsCashShares
from dh.Action3 import Action3
from dh.Action5 import Action5
from dh.Experience import Experience
State = StateExpertsOnly
Action = Action3
class DeepQLearningTrader(ITrader):
"""
Implementation of ITrader based on Deep Q-Learning (DQL).
"""
RELATIVE_DATA_DIRECTORY = 'traders/dql_trader_data'
def __init__(self, expert_a: IExpert, expert_b: IExpert, load_trained_model: bool = True,
train_while_trading: bool = False, color: str = 'black', name: str = 'dql_trader',
other_data_directory: typing.Optional[str] = None,
plot_name: typing.Optional[str] = None):
"""
Constructor
Args:
expert_a: Expert for stock A
expert_b: Expert for stock B
load_trained_model: Flag to trigger loading an already trained neural network
train_while_trading: Flag to trigger on-the-fly training while trading
other_data_directory: relative directory path from project root to .json and .h5 files of model
plot_name: name to use in a plot for this trader, overriding parameter "name" (which also determines
path where the model gets saved)
"""
# Save experts, training mode and name
super().__init__(color, name)
assert expert_a is not None and expert_b is not None
self.experts = [expert_a, expert_b]
self.train_while_trading = train_while_trading
self.other_data_directory = other_data_directory
self.plot_name = plot_name
# Parameters for neural network
self.state_size = State.get_number_of_input_neurons()
self.action_size = Action.get_number_of_output_neurons()
self.hidden_size = 30
# Parameters for deep Q-learning
self.learning_rate = 0.001 # default for Adam: 0.001
self.epsilon = 0.9995 # determines how quickly epsilon decreases to epsilon_min
self.random_action_min_probability = 0.01 # minimum probability of choosing a random action
self.train_each_n_days = 128 # how many trading days pass between each training
self.batch_size = 128 # how many experience samples from memory to train on each training occasion
self.min_size_of_memory_before_training = 1000 # should be way bigger than batch_size, but smaller than memory
self.memory: typing.Deque[Experience] = deque(maxlen=2000)
# discount factor: how quickly we expect an action to pay off
# (0 -> only evaluate immediate effect on portfolio value on next day;
# near 1 -> also include development of portfolio value on future days, where each day has a weight of
# discount_factor ^ #days_ahead; higher values allow to factor in payoffs at later time while also
# making it harder to attribute the effects to the actions from a concrete day)
self.discount_factor = 0
assert 0 <= self.discount_factor < 1.0
# min_horizon: number of more recent experiences required until discount_factor ^ #days_ahead drops to 1%
if 0 < self.discount_factor < 1:
self.min_horizon = min(100, math.ceil(math.log(0.01, self.discount_factor)))
else:
self.min_horizon = 1
self.q_value_cap = 1.0 # limit Q-value to this magnitude; 0.0 to deactivate
self.is_evolved_model = False # set to True when loading model from file
self.days_passed = 0
self.training_occasions = 0
# Create main model, either as trained model (from file) or as untrained model (from scratch)
self.model = None
if load_trained_model:
data_dir = self.RELATIVE_DATA_DIRECTORY if self.other_data_directory is None else self.other_data_directory
self.model = load_keras_sequential(data_dir, 'dql_trader')
# logger.info(f"DQL Trader: Loaded trained model")
self.is_evolved_model = True
if self.model is None: # loading failed or we didn't want to use a trained model
self.model = Sequential()
# original code:
# self.model.add(Dense(self.hidden_size * 2, input_dim=self.state_size, activation='relu'))
# self.model.add(Dense(self.hidden_size, activation='relu'))
# self.model.add(Dense(self.action_size, activation='linear'))
# modified code:
# relu -> elu: avoid "dead nodes" problem of relu
# lecun_normal: initialization from gaussian accounting for number of nodes as well
# initialize bias with zeros
self.model.add(Dense(self.hidden_size * 2, input_dim=self.state_size, activation='elu', kernel_initializer='lecun_normal', bias_initializer='zeros'))
self.model.add(Dense(self.hidden_size, activation='elu', kernel_initializer='lecun_normal', bias_initializer='zeros'))
self.model.add(Dense(self.action_size, activation='linear', kernel_initializer='lecun_normal', bias_initializer='zeros'))
# logger.info(f"DQL Trader: Created new untrained model")
assert self.model is not None
# use one of the following solvers:
self.model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))
# self.model.compile(loss='mse', optimizer=SGD(lr=0.01, momentum=0.9, nesterov=True))
# self.model.compile(loss='mse', optimizer=Nadam(lr=0.001))
def log_info_every_nth_day(self, msg: str, n: int):
if self.days_passed % n == 0:
logger.info(msg)
def save_trained_model(self):
"""
Save the trained neural network under a fixed name specific for this traders.
"""
data_dir = self.RELATIVE_DATA_DIRECTORY if self.other_data_directory is None else self.other_data_directory
save_keras_sequential(self.model, data_dir, 'dql_trader')
# logger.info(f"DQL Trader: Saved trained model")
def trade(self, portfolio: Portfolio, stock_market_data: StockMarketData) -> List[Order]:
"""
Generate actions to be taken on the "stock market"
Args:
portfolio : current Portfolio of this traders
stock_market_data : StockMarketData for evaluation
Returns:
A OrderList instance, may be empty never None
"""
assert portfolio is not None
assert stock_market_data is not None
assert stock_market_data.get_companies() == [Company.A, Company.B]
# Compute the current state
expert_votes = [
self.experts[i].vote(stock_market_data[company])
for i, company in enumerate(stock_market_data.get_companies())
]
shares_owned = [
portfolio.get_stock(company)
for company in stock_market_data.get_companies()
]
if State is StateExpertsOnly:
state = StateExpertsOnly(expert_votes, portfolio.get_value(stock_market_data))
elif State is StateExpertsCashShares:
state = StateExpertsCashShares(expert_votes, portfolio.cash, shares_owned, portfolio.get_value(stock_market_data))
else:
raise RuntimeError
if self.train_while_trading:
# store state as experience in memory
if len(self.memory) > 0:
self.memory[-1].state2 = state
experience = Experience(
state1=state
)
self.memory.append(experience)
# train
if len(self.memory) >= self.min_size_of_memory_before_training:
if self.days_passed % self.train_each_n_days == 0:
self.train()
# determine probability for random actions
if not self.is_evolved_model:
# first training episode
random_action_probability = (
(self.epsilon ** self.days_passed) * (1.0 - self.random_action_min_probability) +
self.random_action_min_probability
)
else:
# subsequent training episode
random_action_probability = self.random_action_min_probability
if self.training_occasions == 0 or random.random() < random_action_probability:
actions = [Action.get_random(), Action.get_random()]
else:
# choose actions by querying network
x = state.to_input()
y = self.model.predict(numpy.array([x]))
assert y.shape == (1, self.action_size)
actions = Action.from_model_prediction(y[0])
experience.actions = actions
else:
# not training -> always choose actions by querying network
actions = Action.from_model_prediction(self.model.predict(numpy.array([state.to_input()]))[0])
# translate actions into orders
orders: typing.List[Order] = []
companies_with_actions_and_magnitudes = list(zip(list(Company), actions, Action.get_action_magnitudes(actions)))
for comp, action, mag in companies_with_actions_and_magnitudes:
if action.is_buy():
cash_limit = portfolio.cash * mag
date, stock_price = stock_market_data[comp].get_last()
shares_amount = cash_limit / stock_price
if shares_amount > 0:
orders.append(Order(OrderType.BUY, comp, shares_amount))
elif action.is_sell():
shares_amount = portfolio.get_stock(comp) * mag
if shares_amount > 0:
orders.append(Order(OrderType.SELL, comp, shares_amount))
self.days_passed += 1
return orders
def train(self):
"""
Train model based on experiences stored in memory.
To speed up training a batch of experiences is trained at once (instance attribute batch_size).
Conversely, training can happen at intervals up to batch_size days (instance attribute .
"""
# determine cumulative rewards for actions in memory
# loop backwards through the memory, ignoring the latest entry
for i in range(2, len(self.memory) + 1):
e: Experience = self.memory[-i]
next_e: Experience = self.memory[-i + 1] # its reward has been set in the previous loop iteration
if i == 2:
e.reward = e.get_portfolio_rel_immediate_change() - 1
else:
e.reward = e.get_portfolio_rel_immediate_change() - 1 + self.discount_factor * next_e.reward
# modify reward as part of the computation of the Q-value:
# 1. multiply by 100 to make it easier for the network to learn the values
# (brings absolute values mostly into a range of 0.01 .. 10.0)
# 2. normalize for time horizon
# (assuming a high discount factor there is a large difference in cumulative reward between
# very recent and rather old experiences, simply because accumulating (discounted) reward
# over more recent experiences stops when the most recent experience has been hit)
discounted_time_factor = 1.0
for i in range(2, len(self.memory) + 1):
e: Experience = self.memory[-i]
e.reward *= 100.0 / discounted_time_factor
discounted_time_factor += self.discount_factor ** (i - 1)
# A part of the memory is too recent, i.e. the rewards for these states have only a short time horizon.
# We want to exclude these recent states from learning because they do not meet the requirements
# implied by the discount factor.
memory_range_for_training = range(len(self.memory) - self.min_horizon)
# assemble input (x) and output (y) arrays for training
batch_indices = random.sample(memory_range_for_training, self.batch_size)
x = numpy.array([
State.to_input(self.memory[i].state1) for i in batch_indices
])
assert x.shape == (self.batch_size, self.state_size)
# use the output of the network as the basis for training
y = self.model.predict(x)
assert y.shape == (self.batch_size, self.action_size)
action_to_index = {a: i for (i, a) in enumerate(Action)}
# modify those parts of the output that correspond to the actions taken in the
# experiences selected from memory
for bi in range(self.batch_size):
e: Experience = self.memory[batch_indices[bi]]
q_value_to_train = e.reward
# cap Q-value to lower model performance fluctuations during training
if self.q_value_cap > 0.0:
if q_value_to_train > self.q_value_cap:
q_value_to_train = self.q_value_cap
if q_value_to_train < -self.q_value_cap:
q_value_to_train = -self.q_value_cap
# 1) if encode each possible action tuple as a separate output neuron
# e.g. Action5 with output layer as 5^(#companies) neurons
node_index = (action_to_index[e.actions[0]] * Action.get_number_of_output_neurons_per_action() +
action_to_index[e.actions[1]])
y[bi][node_index] = q_value_to_train
# 2) if encode each possible action per company as separate output neurons
# e.g. Action5 with output layer as 5*(#companies) neurons
# (simplified representation to reduce #output neurons)
# node_index = action_to_index[e.actions[0]]
# y[bi][node_index] = q_value_to_train
# node_index = action_to_index[e.actions[1]] + Action.get_number_of_output_neurons_per_action()
# y[bi][node_index] = q_value_to_train
# debug info: show some untrained vs. trained Q-values
# if bi == 0:
# self.log_info_every_nth_day(f'{y[bi][node_index]:.6f} vs. {q_value_to_train:.6f}', 50)
self.model.train_on_batch(x, y)
self.training_occasions += 1
def print_policy(self):
"""
Print the policy by enumerating all possible inputs and their corresponding output
(actions determined by the highest Q-value).
"""
if State is not StateExpertsOnly:
return
for eo1 in list(Vote):
for eo2 in list(Vote):
state = StateExpertsOnly([eo1, eo2], 0)
x = state.to_input()
y = self.model.predict(numpy.array([x]))[0]
actions = Action.from_model_prediction(y)
x_str = f'[{eo1.value: <4}, {eo2.value: <4}]'
if Action is Action3:
action_str = f'[{actions[0].value: <4}, {actions[1].value: <4}]'
elif Action is Action5:
action_str = f'[{actions[0].value: <11}, {actions[1].value: <11}]'
else:
raise NotImplementedError
y_str = ' '.join((f'{value:+.4f}' for value in y))
logger.info(f'{x_str} -> {action_str} ({y_str})')
# Executing this module retrains the deep q-learning trader from scratch
# trains TRAINING_RUNS different models and saves the one with the median v score (return_pct_per_day)
TRAINING_RUNS = 5
# training is finished after data from the training set has been replayed EPISODES times
EPISODES = 5
if __name__ == "__main__":
# Create the training data and testing data
data = dict(train=StockMarketData([Company.A, Company.B], [Period.TRAINING]),
test=StockMarketData([Company.A, Company.B], [Period.TESTING]))
print(f"training data: {data['train'].get_row_count()} samples")
# Hint: You can crop the training data with training_data.deepcopy_first_n_items(n)
# data['train'] = data['train'].deepcopy_first_n_items(int(data['train'].get_row_count() / 5))
print(f"training data (cropped): {data['train'].get_row_count()} samples")
print(f"testing data: {data['test'].get_row_count()} samples")
# Save final portfolio values and return % per day
# per training run and episode
final_portfolio_values = dict(train=[], test=[])
return_pct_per_day = dict(train=[], test=[])
traders = dict(train=[], test=[])
def get_last_portfolio_value(phase: str, run: int) -> float:
index = min(run * EPISODES + EPISODES - 1, len(final_portfolio_values[phase]) - 1)
return final_portfolio_values[phase][index]
def get_last_v_score(phase: str, run: int) -> float:
index = min(run * EPISODES + EPISODES - 1, len(return_pct_per_day[phase]) - 1)
return return_pct_per_day[phase][index]
for run in range(TRAINING_RUNS):
# Create the stock exchange and one traders to train the net
starting_cash = dict(train=10000.0, test=2000.0)
stock_exchanges = dict(train=stock_exchange.StockExchange(starting_cash["train"]),
test=stock_exchange.StockExchange(starting_cash["test"]))
traders['train'].append(DeepQLearningTrader(ObscureExpert(Company.A), ObscureExpert(Company.B), False, True))
for episode in range(EPISODES):
# logger.info(f"DQL Trader: Starting training episode {episode}")
for phase in ['train', 'test']:
if phase == 'test':
testing_trader = DeepQLearningTrader(ObscureExpert(Company.A), ObscureExpert(Company.B), True, False)
if episode == 0:
traders[phase].append(testing_trader)
else:
traders[phase][-1] = testing_trader # replace testing trader from previous episode
trader = traders[phase][-1]
stock_exchanges[phase].run(data[phase], [trader])
if phase == 'train':
trader.save_trained_model() # required to be able to create testing trader in next iteration
p = stock_exchanges[phase].get_final_portfolio_value(trader)
v = 100.0 * (math.pow(p / starting_cash[phase], 1 / data[phase].get_row_count()) - 1.0)
final_portfolio_values[phase].append(p)
return_pct_per_day[phase].append(v)
logger.info(f"DQL Trader: Finished training episode {episode}, "
f"final portfolio value training {get_last_portfolio_value('train', run):.1e} vs. "
f"final portfolio value test {get_last_portfolio_value('test', run):.1e}")
logger.info(f"\treturn % per day training {get_last_v_score('train', run):.6f} vs. "
f"return % per day test {get_last_v_score('test', run):.6f}")
# traders['train'][-1].print_policy()
logger.info('-' * 80)
# sort traders by test v score
traders_sorted_by_score = sorted(enumerate(traders['test']), key=lambda tup: get_last_v_score('test', tup[0]))
# choose the one in the middle
run, trader = traders_sorted_by_score[(TRAINING_RUNS - 1) // 2]
# overwrite model from other training runs
trader.save_trained_model()
print(f"choosing model with median v score from run {run + 1}")
print('output for csv data:')
print('trader;dataset;returnpctperday;finalportfoliovalue')
print('-' * 80)
print(f";train;{get_last_v_score('train', run):.6f};{get_last_portfolio_value('train', run):.1e}")
print(f";test;{get_last_v_score('test', run):.6f};{get_last_portfolio_value('test', run):.1e}")
print('-' * 80)
# plotting v scores across training episodes
from matplotlib import pyplot as plt
plt.figure()
data_start_index = run * EPISODES
data_stop_index = data_start_index + EPISODES
plt.plot(return_pct_per_day['train'][data_start_index:data_stop_index], label='training', color="black")
plt.plot(return_pct_per_day['test'][data_start_index:data_stop_index], label='testing', color="green")
plt.title('v score training vs. testing')
plt.ylabel('v score (avg. return % per day)')
plt.xlabel('episode')
plt.legend(['training', 'testing'])
plt.show()
|
Java | UTF-8 | 2,010 | 2.09375 | 2 | [] | no_license | package com.zjkj.wxy.core.web.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zjkj.wxy.core.domain.User;
/**
* 资源跳转控制器
* @author smil
*
*/
@Controller
@RequestMapping("/page")
public class PageController {
/**
* 后台入口index.jsp
* @return
*/
@RequestMapping("/index.do")
public String index(){
return "index";
}
/**
* 选择学校后跟新session的学校标识sid
* @param request
* @param sid
*/
@RequestMapping("/setSid.do")
public void setSidInSession(HttpServletRequest request,Integer sid,HttpServletResponse response){
try {
HttpSession session = request.getSession();
if(sid!=null){
session.setAttribute("SCHOOLID",sid);
}
response.getWriter().print(1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 主页top资源跳转
* @return
*/
@RequestMapping("/top.do")
public String top(HttpServletRequest request){
HttpSession session = request.getSession();
User user =(User) session.getAttribute("loginUser");
if(user.getSid()!=null){
request.setAttribute("schoolid", user.getSid());
session.setAttribute("SCHOOLID", user.getSid());
}
return "top";
}
/**
* 主页main资源跳转
* @return
*/
@RequestMapping("/main.do")
public String main(){
return "main";
}
/**
* 主页main部分left资源跳转
* @return
*/
@RequestMapping("/left.do")
public String left(){
return "wechatConfig/wctConfig";
}
/**
* 主页main部分right资源跳转
* @return
*/
@RequestMapping("/right.do")
public String right(){
return "right";
}
}
|
Python | UTF-8 | 288 | 4.0625 | 4 | [
"MIT"
] | permissive | '''write a function that prints values in reverse way but with three positions skipped'''
def reverse_3_skip(alist):
temp_list = []
for i in range(len(alist)-1, 0, 3):
temp_list.append(alist[i])
return temp_list
reverse = reverse_3_skip([4,2,5,3,6,1,2,6,8,6,9])
print(reverse) |
JavaScript | UTF-8 | 2,543 | 2.53125 | 3 | [] | no_license | javascript: (function() {
var fPrefix = "[YT] ";
var videoId = getYTId();
var videoId_tag = " ([vid-" + videoId + "])";
var videoTitle_raw = document.querySelector("h1.title").innerText.trim();
var videoTitle_clean = cleanString(videoTitle_raw);
var videoCreator_raw = document.querySelector("div#text-container.ytd-channel-name").innerText.trim();
var videoCreator_clean = cleanString(videoCreator_raw).trim();
var fName = fPrefix + videoCreator_clean + " -- " + videoTitle_clean + videoId_tag + ".mp4";
var grabberBase = "https://www.savethevideo.com/download?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D";
var grabberLink = grabberBase + videoId;
copyText(fName);
/*alert(grabberLink);*/
window.location.href = grabberLink;
function copyText(inputString) {
var jscbta = document.createElement("textarea");
jscbta.value = inputString;
document.body.appendChild(jscbta);
jscbta.select();
document.execCommand("copy");
document.body.removeChild(jscbta);
}
function cleanString(var_input) {
console.log(var_input);
var var_cleaning;
var var_output;
var_cleaning = var_input;
var_cleaning = var_cleaning.replace(" : ", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace(": ", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace(" :", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace(":", "");
var_cleaning = var_cleaning.replace(" < ", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace("< ", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace(" <", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace("<", "");
var_cleaning = var_cleaning.replace(" > ", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace("> ", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace(" >", "zxzINVALIDzxz");
var_cleaning = var_cleaning.replace("zxzINVALIDzxz", " - ");
var_cleaning = var_cleaning.replace(">", "");
var_cleaning = var_cleaning.replace("/", "");
var_cleaning = var_cleaning.replace("\\", "");
var_cleaning = var_cleaning.replace("|", "");
var_cleaning = var_cleaning.replace("?", "");
var_cleaning = var_cleaning.replace("*", "");
var_cleaning = var_cleaning.replace("\"", "");
var_cleaning = var_cleaning.replace(" ", " ");
var_output = var_cleaning;
return var_output;
}
function getYTId(x=0)
{
if(x==0)
{
x = document.URL;
}
var a = x.match(/^(?:[\w\d]+\:\/\/)?(?:(?:(?:[\w\d]+\.)*(?:youtube)(?:\.[\w\d]+)+\/watch\?v=)|(?:youtu\.be\/))([^\?&]+)(?:[\?&].*)?/);
if(a===null){return null;}
x = a[1];
return x;
}
})();
|
Ruby | UTF-8 | 1,845 | 2.609375 | 3 | [
"MIT"
] | permissive | # Simple example of a server for sending notifications through postgresql that can be listened for.
module CelluloidIOPGListener
module Examples
class Server
include Celluloid
include Celluloid::IO
include Celluloid::Internals::Logger
prepend CelluloidIOPGListener::Initialization::ArgumentExtraction
def initialize(*args)
debug "Server will send notifications to #{dbname}:#{channel}"
end
# Defaults:
# 1/10th of a second sleep intervals
# 1 second run intervals
def start(run_interval: 1, sleep_interval: 0.1)
@sleep_interval = sleep_interval
@run_interval = run_interval
async.run
end
def run
now = Time.now.to_f
sleep now.ceil - now + @sleep_interval
# There is no way to pass anything into the block, which is why this server isn't all that useful.
# The client is intended to listen to notifications coming from other sources,
# like a PG TRIGGER than sends a notification on INSERT, for example.
every(@run_interval) { ping }
end
# Helps with testing by making the notify synchronous.
def ping
notify(channel, Time.now.to_i)
debug "Notified #{channel}"
end
private
def pg_connection
@pg_connection ||= PG.connect(conninfo_hash)
end
# Supported channel names are any delimited (double-quoted) identifier:
# We supply the double quotes, you supply the contents.
# If you want unicode character code support submit a pull request to make the quote style `U&"` a config setting.
# See: http://www.postgresql.org/docs/9.4/static/sql-syntax-lexical.html
def notify(channel, value)
pg_connection.exec(%[NOTIFY "#{channel}", '#{value}';])
end
end
end
end
|
Java | UTF-8 | 4,173 | 1.960938 | 2 | [] | no_license | package com.welian.service;
import com.welian.beans.cloudevent.admin.AdminReq;
import com.welian.beans.cloudevent.admin.AdminResp;
import com.welian.beans.cloudevent.user.UserResp;
import com.welian.commodity.beans.Liquidation;
import com.welian.commodity.beans.LiquidationBean;
import com.welian.mapper.EventOrderMapper;
import com.welian.pojo.Event;
import com.welian.service.impl.EventServiceImpl;
import com.welian.pojo.EventOrder;
import com.welian.pojo.EventOrderExample;
import org.sean.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* Created by zhaopu on 2018/1/9.
*/
@Service
public class AdminService {
@Autowired
private CommodityRemoteService commodityRemoteService;
@Autowired
private EventServiceImpl eventService;
@Autowired
private EventOrderModule eventOrderModule;
@Autowired
private EventOrderMapper eventOderMapper;
/**
* 财务系统-活动结算列表
*/
public Object getEventSettlementes(AdminReq req) {
final AdminResp adminRespR = new AdminResp();
adminRespR.list = new ArrayList<>();
final LiquidationBean liquidationBean = commodityRemoteService.getSettlementList(req.page,req.size);
if (!Optional.ofNullable(liquidationBean).map(e -> e.pageData).isPresent()) {
return adminRespR;
}
final List<EventOrder> eventOrders = Optional.ofNullable(liquidationBean.pageData.getList())
.map( l -> l.stream().map(e -> e.batchNum).collect(Collectors.toList()))
.filter(StringUtil::isNotEmpty)
.map(e -> {
final EventOrderExample example = new EventOrderExample();
example.createCriteria().andBatchnumIn(e);
return example;
})
.map(eventOderMapper::selectByExample)
.filter(StringUtil::isNotEmpty)
.map(l -> l.stream().distinct().collect(Collectors.toList())
).orElseGet(ArrayList::new);
final Map<String,List<Event>> eventTemp = new ConcurrentHashMap<>(); // 为了防止重复查询添加了本地缓存
final CompletableFuture<Map<String,Event>> eventMapFucture = CompletableFuture.supplyAsync(() ->
eventOrderModule.getEventsMapByBatchNums(eventOrders,eventTemp));
final CompletableFuture<Map<Integer,UserResp>> userMapFucture = CompletableFuture.supplyAsync(() ->
eventService.getAdminMapByIds(
eventOrders.stream().map(EventOrder::getEventId).collect(Collectors.toList()),eventTemp));
final Map<String,Event> eventMap = eventMapFucture.join();
final Map<Integer,UserResp> userMap = userMapFucture.join();
for (Liquidation liquidation : liquidationBean.pageData.getList()) {
AdminResp adminResp = new AdminResp();
Event event = eventMap.get(liquidation.batchNum);
if (event == null) {
continue;
}
adminResp.eventId = event.getId();
adminResp.eventTitle = event.getTitle();
adminResp.eventType = event.getTemplateId();
adminResp.intro = "活动结算";
adminResp.price = liquidation.price;
adminResp.createTime = liquidation.createTime;
adminResp.status = liquidation.status;
adminResp.reason = liquidation.note;
adminResp.batchNum = liquidation.batchNum;
adminResp.serviceAmount = liquidation.details.get(0).serviceAmount;
adminResp.user = userMap.get(adminResp.eventId);
adminRespR.list.add(adminResp);
}
adminRespR.count = (long)adminRespR.list.size();
adminRespR.waitAmount = liquidationBean.waitSum;
adminRespR.waitTotal = liquidationBean.waitNum;
return adminRespR;
}
}
|
Markdown | UTF-8 | 46 | 2.828125 | 3 | [
"CC0-1.0"
] | permissive | # Stackable Beds
Makes beds stackable upto 64. |
C++ | UTF-8 | 2,907 | 3.296875 | 3 | [] | no_license | #include<iostream>
#include <string.h>
using namespace std;
void DFS(int step, char* string, int length, int book[], char result[])
{
if(step == length)
{
for(int i=0; i<length; i++)
{
cout << result[i];
}
cout << endl;
return;
}
for(int i=0; i<length; i++)
{
if(book[i] == 0)
{
book[i] = 1;
result[step] = string[i];
DFS(step+1, string, length, book, result);
book[i] = 0;
}
}
}
void StringPermutation(char* string, int length)
{
if(string == nullptr || length <= 0) return;
int book[length]={0};
char result[length]={0};
DFS(0, string, length, book, result);
}
// 深度优先算法
// void Dfs(int step, char* string, int length, int* book, int* a)
// {
// if(step == length)
// {
// for(int i=0; i<length; i++)
// {
// cout << string[a[i]];
// }
// cout << endl;
// return;
// }
// for(int i=0; i<length; i++)
// {
// if(book[i] == 0)
// {
// book[i] = 1;
// a[step] = i;
// Dfs(step+1, string, length, book, a);
// book[i] = 0;
// }
// }
// return;
// }
// void StringPermutation(char* string, int length)
// {
// if(string == nullptr || length == 0 )return;
// int book[length]={0};
// int a[length] = {0};
// Dfs(0, string, length, book, a);
// }
//
// void Permutation(char* string, char* pBegin)
// {
// if(*pBegin == '\0')
// {
// cout << string << endl;
// return;
// }
// else
// {
// for(char* pCh = pBegin; *pCh!='\0'; ++pCh)
// {
// char tmp = *pCh;
// *pCh = *pBegin;
// *pBegin = tmp;
// Permutation(string, pBegin+1); //这里千万不能用++, 否则下面语句的pBegin值就变了
// // 再进行下一次循环的时候,得保持原来的顺序,所以得再换回来
// tmp = *pCh;
// *pCh = *pBegin;
// *pBegin = tmp;
// }
// return;
// }
// }
// void StringPermutation(char* string, int length)
// {
// if(string == nullptr || length == 0) return;
// Permutation(string, string);
// }
// ============================测试代码================================
void Test(char* string, int length)
{
if(string == nullptr)return;
else
{
StringPermutation(string, length);
}
cout << endl;
}
int main(void)
{
char string1[] = "";
int tmp = strlen(string1);
Test(string1, tmp);
//char string2[] = {'a'};
char string2[] = "a";
tmp = strlen(string2);
Test(string2, tmp);
// char string3[] = {'a','b'};
char string3[] = "ab";
tmp = strlen(string3);
Test(string3, tmp);
// char string4[] = {'a','b','c'};
char string4[] = "abc";
tmp = strlen(string4);
Test(string4, tmp);
return 0;
}
|
Java | UTF-8 | 1,011 | 2.78125 | 3 | [] | no_license | package classes;
import interfaces.Visitable;
import interfaces.Classifiable;
public class Church extends Node implements Classifiable, Visitable{
private String openingHours;
private String rank;
public String getOpeningHours() {
return openingHours;
}
private String closingHours;
@Override
public void setClosingHours(String closingHours) {
this.closingHours = closingHours;
}
@Override
public String getClosingHours() {
return closingHours;
}
public void setOpeningHours(String openingHours) {
this.openingHours = openingHours;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public Church(String name) {
super(name);
}
@Override
public String toString() {
return "Church{" +"name = "+getName()+ "}";//, openingHours=" + openingHours + ", rank=" + rank + '}'+'\n';
}
}
|
C# | UTF-8 | 2,469 | 2.546875 | 3 | [] | no_license | //
// Copyright (C) 2017 Fluendo S.A.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
//
using System;
using VAS.Core.Interfaces;
using SystemStopwatch = System.Diagnostics.Stopwatch;
namespace VAS.Core.Common
{
/// <summary>
/// Wrapper for System.Diagnostics.Stopwatch
/// </summary>
public class Stopwatch : IStopwatch
{
/// <summary>
/// The frequency of the timer as the number of ticks per second
/// </summary>
public static readonly long Frequency = SystemStopwatch.Frequency;
SystemStopwatch stopwatch;
public Stopwatch ()
{
stopwatch = new SystemStopwatch ();
}
/// <summary>
/// Gets the elapsed milliseconds.
/// </summary>
/// <value>The elapsed milliseconds.</value>
public long ElapsedMilliseconds {
get {
return stopwatch.ElapsedMilliseconds;
}
}
/// <summary>
/// Gets the elapsed ticks.
/// </summary>
/// <value>The elapsed ticks.</value>
public long ElapsedTicks {
get {
return stopwatch.ElapsedTicks;
}
}
/// <summary>
/// Gets the elapsed seconds.
/// </summary>
/// <value>The elapsed seconds.</value>
public double ElapsedSeconds {
get {
return (double)stopwatch.ElapsedTicks / Frequency;
}
}
/// <summary>
/// Check if the Stopwatch is running.
/// </summary>
/// <returns><c>true</c>, Stopwatch running <c>false</c> otherwise.</returns>
public bool IsRunning {
get {
return stopwatch.IsRunning;
}
}
/// <summary>
/// Reset the Stopwatch.
/// </summary>
public void Reset ()
{
stopwatch.Reset ();
}
/// <summary>
/// Start the Stopwatch.
/// </summary>
public void Start ()
{
stopwatch.Start ();
}
/// <summary>
/// Stop the Stopwatch.
/// </summary>
public void Stop ()
{
stopwatch.Stop ();
}
}
}
|
TypeScript | UTF-8 | 2,745 | 2.5625 | 3 | [
"MIT"
] | permissive | import * as monaco from "monaco-editor";
import path from "path";
import { parseConfigFileTextToJson } from "typescript";
const extToLang: {
[key: string]: "json" | "javascript" | "typescript" | "html";
} = {
".js": "javascript",
".ts": "typescript",
".tsx": "typescript",
".json": "json",
".svelte": "html",
".vue": "html"
};
export function getMonaco() {
return monaco;
}
export function findModel(filepath: string): monaco.editor.IModel | void {
return monaco.editor.getModels().find(model => {
return model.uri.path === filepath;
});
}
export function renameFile(
filepath: string,
to: string
): monaco.editor.IModel | void {
const m = findModel(filepath);
if (m) {
const value = m.getValue();
deleteFile(filepath);
createFile(to, value);
}
}
export function updateFile(filepath: string, content: string) {
const m = monaco.editor.getModels().find(m => m.uri.path === filepath);
if (m && m.getValue() !== content) {
m.setValue(content);
}
return m;
}
export function deleteFile(filepath: string) {
const confirmed = window.confirm(`Delete ${filepath}`);
if (!confirmed) {
return;
}
const m = monaco.editor.getModels().find(m => m.uri.path === filepath);
if (m) {
m.dispose();
console.log("disposed", filepath);
} else {
console.warn(`[monaco:deleteFile] ${filepath} does not exists`);
}
}
export function createFile(
filepath: string,
content?: string
): monaco.editor.ITextModel {
const extname = path.extname(filepath);
const lang = extToLang[extname as any];
console.log(extname, lang);
const newModel = monaco.editor.createModel(
content || "",
lang,
monaco.Uri.from({
scheme: "file",
path: filepath
})
);
newModel.updateOptions({
tabSize: 2,
insertSpaces: true
});
if (filepath === "/tsconfig.json" && content) {
const conf = parseConfigFileTextToJson(filepath, content);
// debugger;
monaco.languages.typescript.typescriptDefaults.setCompilerOptions(
conf.config.compilerOptions
);
monaco.languages.typescript.typescriptDefaults.addExtraLib(
"declare module '*';",
"decls.d.ts"
);
}
return newModel;
}
export type SerializedFS = { [k: string]: string };
export function toJSON(): SerializedFS {
const ret: { [k: string]: string } = {};
for (const m of monaco.editor.getModels()) {
const v = m.getValue();
const fpath = m.uri.path;
ret[fpath] = v;
}
return ret;
}
export function restoreFromJSON(serialized: SerializedFS): void {
Object.entries(serialized).map(([k, v]) => {
createFile(k, v);
});
}
export function disposeAll(): void {
for (const m of monaco.editor.getModels()) {
m.dispose();
}
}
|
C# | UTF-8 | 966 | 3.453125 | 3 | [] | no_license | using Plugin.Connectivity;
using System;
using System.Collections.Generic;
using System.Text;
namespace Memory_Game_App.Classes
{
public static class StringExtensions
{
public static int ToInteger(this string numberString)
{
int result = 0;
if (int.TryParse(numberString, out result))
return result;
return 0;
}
}
public static class Utils
{
public static bool IsConnectedToInternet()
{
return CrossConnectivity.Current.IsConnected;
}
}
}
//The Helper.cs file is composed of two classes: StringExtension and Utils.
// The StringExtension class contains a ToIntenger() extension method to convert a valid numerical string value into an integer type.
// The Utils class on the other hand contains an IsConnectedToInternet() method to verify internet connectivity. We will be using these methods later in our application. |
C++ | UTF-8 | 250 | 2.53125 | 3 | [] | no_license | #pragma once
#include <string>
#include <iostream>
struct InfoProduct
{
std::string m_product_name = {};
std::string m_product_color = {};
int m_price = 0;
};
std::ostream& operator << (std::ostream& out, const InfoProduct& data);
|
PHP | UTF-8 | 1,697 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of Zippy.
*
* (c) Alchemy <info@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Zippy\ProcessBuilder;
use Symfony\Component\Process\Process;
class ProcessBuilder implements ProcessBuilderInterface
{
/**
* The command to run and its arguments listed as separate entries
*
* @var array
*/
private $command;
/**
* The working directory or null to use the working dir of the current PHP process
*
* @var string|null
*/
private $cwd;
/**
* ProcessBuilder constructor.
* @param array $command
*/
public function __construct($command)
{
$this->command = $command;
$this->cwd = null;
}
/**
* Creates a Process instance and returns it
*
* @return Process
*/
public function getProcess()
{
$process = new Process($this->command, $this->cwd);
$process->setTimeout(null);
return $process;
}
/**
* @inheritdoc
*/
public function add($argument)
{
$this->command = array_merge($this->command, array($argument));
return $this;
}
/**
* @inheritdoc
*/
public function setWorkingDirectory($directory)
{
$this->cwd = $directory;
return $this;
}
/**
* The command to run or a binary path and its arguments listed as separate entries
*
* @param array $command
*
* @return static
*/
public static function create(array $command)
{
return new static($command);
}
}
|
Python | UTF-8 | 691 | 3.046875 | 3 | [
"MIT"
] | permissive | import concurrent.futures
import logging
import time
import numpy as np
class MyThreads(object):
def thread_function(self, args):
name1, name2 = args
print(name1, name2)
name = name1 + "-" + name2
logging.info("Thread %s: starting", name)
time.sleep(2)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format,
level=logging.INFO, datefmt="%H:%M:%S")
my_threads = MyThreads()
args = [('a', 'a'), ('b', 'b'), ('c', 'c')]
with concurrent.futures.ThreadPoolExecutor(
max_workers=3) as executor:
executor.map(my_threads.thread_function, args)
|
JavaScript | UTF-8 | 1,639 | 3.125 | 3 | [] | no_license | var fs = require('fs-extra');
var string = 'render_zone',
dir = process.argv[2],
zoneArray = [];
var readDir = function(dir){
fs.readdir(dir,function(error, dirContent){
if(!error){
var files = dirContent;
//On checke la liste du contenu du répertoire
for (var i = files.length - 1; i >= 0; i--) {
var filePath = dir+files[i];
//Si c'est un dossier, on relance un readDir de zéro sur ce dossier
if(files[i].indexOf('.') == -1){
readDir(filePath+"/");
} else {
getSlug(filePath);
}
};
} else {
console.log("erreur de directory");
}
});
}
var getSlug = function(file){
//Et on continue quoi qu'il arrive sur le reste
var fileContent = fs.readFileSync(file, 'utf8');
console.log((fileContent.match(new RegExp(string, "g") ) || []).length);
if (fileContent.indexOf(string) != -1){
// console.log("trouvé dans : ", filePath);
for(var a = fileContent.indexOf(string); a < fileContent.length; a++){
//console.log(fileContent[a]);
if(fileContent[a] == ')'){
zone = fileContent.substring(fileContent.indexOf(string), a+1);
zone = zone.replace("render_zone('", '');
zone = zone.replace("')", '');
//console.log("zone ",zone)
zoneArray.push(zone);
break;
}
}
//creatFileSlug(zoneArray);
};
}
var creatFileSlug = function(zone){
console.log(zone);
fs.writeFile("hello.txt", zone, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
}
readDir(dir);
|
Markdown | UTF-8 | 6,523 | 3.5625 | 4 | [
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | ---
id: debug-a-zio-application
title: "Tutorial: How to Debug a ZIO Application?"
sidebar_label: "Debugging a ZIO Application"
---
## Introduction
Writing applications using functional programming helps us to write a base code that is less error-prone and more predictable. However, we often make mistakes when developing applications. Even though we have written lots of tests, we might have missed some areas of our code that could have caused errors. Finally, in the middle of one night, the alarm starts calling and paging us to take the right action for the error in production. This is where debugging comes in. It is a process of finding the root cause of the error and then fixing it. Sometimes this process takes a large amount of time and effort.
In this article, we are going to learn how to debug a ZIO application. We will start with the simplest example of a ZIO application and then move to the more complex ones.
## Debugging an Ordinary Scala Application
Before talking about debugging functional effects, we need to understand how to debug an ordinary Scala application. In scala, one simple way to debug a code is to use `print` statements to print the intermediate values of the computation to the console.
Assume we have the following fibonacci function:
```scala mdoc:compile-only
def fib(n: Int): Int = {
@annotation.tailrec
def go(n: Int, a: Int, b: Int): Int =
if (n == 0) a
else go(n - 1, b, a + b)
go(n, 0, 1)
}
```
The implementation of this function is correct, but for pedagogical purposes, let's debug it by printing the intermediate values of the computation:
```scala mdoc:compile-only
def fib(n: Int): Int = {
@annotation.tailrec
def go(n: Int, a: Int, b: Int): Int =
if (n == 0) {
println(s"final result: $a")
a
} else {
println(s"go(${n - 1}, $b, ${a + b})")
go(n - 1, b, a + b)
}
println(s"go($n, 0, 1)")
go(n, 0, 1)
}
```
Now if we call `fib(3)`, we will see the following output:
```
go(3, 0, 1)
go(2, 1, 1)
go(1, 1, 2)
go(0, 2, 3)
final result: 2
```
The `print` statements are the easiest way for lazy programmers to debug their code. However, they are not the most efficient way to debug code.
## Debugging a ZIO Application Using `debug` Effect
When we use functional effects like `ZIO`, we are creating the description of the computation that we want to run. For example, assume we have the following code:
```scala mdoc:compile-only
import zio._
val effect: ZIO[Any, Nothing, Unit] = ZIO.succeed(3).map(_ * 2)
```
The `effect` itself is a description of the computation that we want to run. So we can't use print statements to debug effects directly. For example, if we write `println(effect)`, we will get something like this:
```scala
OnSuccess(<empty>.MainApp.effect(MainApp.scala:4),Sync(<empty>.MainApp.effect(MainApp.scala:4),MainApp$$$Lambda$23/0x00000008000bc440@44a3ec6b),zio.ZIO$$Lambda$25/0x00000008000ba040@71623278)
```
This is not the expected output. We want to see the result of the computation, not the description of the computation. Why did this happen? Because we haven't run the computation yet.
So keep in mind that, unlike the ordinary scala print statements, we can't use print statements directly to debug functional effects, unless we unsafely run the computation:
```scala mdoc:compile-only
import zio._
val effect: ZIO[Any, Nothing, Int] =
ZIO.succeed(3).map(_ * 2)
val executedEffect: Int =
Unsafe.unsafe { implicit unsafe =>
Runtime.default.unsafe.run(effect).getOrThrowFiberFailure()
}
println(s"executedEffect: $executedEffect")
```
This will print the result of the computation. But, this is not the idiomatic way to debug functional effects.
Simple _print statements_ are not composable with ZIO applications. So we can't use them to debug ZIO applications easily. So instead of print statements, we should use ZIO effects to debug ZIO applications. We can use `Console.printLine` effect to debug ZIO applications, but the ZIO itself has a specialized effect called `ZIO.debug`/`ZIO#debug` which allows us to print intermediate values easily.
For example, assume we have written the Fibonacci function using the `ZIO` data type:
```scala mdoc:compile-only
import zio._
def fib(n: Int): ZIO[Any, Nothing, Int] = {
if (n <= 1) ZIO.succeed(n)
else fib(n - 1).zipWith(fib(n - 2))(_ + _)
}
```
We can debug this program by utilizing the `ZIO#debug` effect:
```scala mdoc:compile-only
import zio._
def fib(n: Int): ZIO[Any, Nothing, Int] = {
if (n <= 1) ZIO.succeed(n).debug(s"fib($n) = $n")
else {
fib(n - 1)
.zipWith(fib(n - 2))(_ + _)
.debug(s"fib($n) = fib(${n - 1}) + fib(${n - 2})")
}
}
```
If we run the above program, we will see the following output:
```
fib(1) = 1: 1
fib(0) = 0: 0
fib(2) = fib(1) + fib(0): 1
fib(1) = 1: 1
fib(3) = fib(2) + fib(1): 2
fib(1) = 1: 1
fib(0) = 0: 0
fib(2) = fib(1) + fib(0): 1
fib(4) = fib(3) + fib(2): 3
fib(1) = 1: 1
fib(0) = 0: 0
fib(2) = fib(1) + fib(0): 1
fib(1) = 1: 1
fib(3) = fib(2) + fib(1): 2
fib(5) = fib(4) + fib(3): 5
```
The `ZIO#debug` effect taps into the called function and prints its output. It doesn't change the result of a computation. We also can use `ZIO.debug` to print any arbitrary message.
We have the same effect as the following:
```scala mdoc:compile-only
import zio.stream._
ZStream
.fromIterable(1 to 3)
.debug("before map")
.map(_ * 2)
.debug("after map")
.runDrain
```
The output is:
```
before map: 1
after map: 2
before map: 2
after map: 4
before map: 3
after map: 6
```
## Debugging Using a Debugger
Debugging using print statements is usable in some cases, and sometimes it is not performant. Another way to debug a code is to use a debugger. A debugger is a program that allows us to step through the code and see the intermediate values of the computation. Some IDEs like IntelliJ IDEA or Visual Studio Code have built-in debuggers. We can use these to debug our code, whether we are debugging a functional effect or an ordinary scala program.
To learn how to use a debugger in each of the IDEs, we can look at the following links:
- [IntelliJ IDEA](https://www.jetbrains.com/help/idea/run-debug-and-test-scala.html)
- [Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging)
## Conclusion
In this article we discussed how to debug functional effects using `debug` effect and also debuggers. We saw that debugging with functional effects can be even easier than debugging ordinary scala programs.
|
Markdown | UTF-8 | 1,110 | 2.546875 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: ''RaiseEvent' ya se ha declarado'
ms.date: 07/20/2015
f1_keywords:
- vbc31129
- bc31129
helpviewer_keywords:
- BC31129
ms.assetid: 6e5c89fc-ca1d-4e8f-bf04-8af3e8b03a4b
ms.openlocfilehash: ec6078cf8b3dc75b9f8a426059c1699f3e5989fd
ms.sourcegitcommit: 3d5d33f384eeba41b2dff79d096f47ccc8d8f03d
ms.translationtype: MT
ms.contentlocale: es-ES
ms.lasthandoff: 05/04/2018
ms.locfileid: "33621064"
---
# <a name="39raiseevent39-is-already-declared"></a>'RaiseEvent' ya se ha declarado
Aparece más de una declaración `RaiseEvent` en una declaración de evento personalizado. Una declaración `RaiseEvent` declara un procedimiento que se usa para generar el evento.
**Identificador de error:** BC31129
## <a name="to-correct-this-error"></a>Para corregir este error
- Quite la instrucción redundante `RaiseEvent` .
## <a name="see-also"></a>Vea también
[RaiseEvent (instrucción)](../../visual-basic/language-reference/statements/raiseevent-statement.md)
[Event (instrucción)](../../visual-basic/language-reference/statements/event-statement.md)
|
C++ | UTF-8 | 463 | 3.28125 | 3 | [] | no_license | /**
*
* https://leetcode.com/problems/to-lower-case/
* Runtime: 0 ms, faster than 100.00% of C++ online submissions for To Lower Case.
* Memory Usage: 8.2 MB, less than 58.97% of C++ online submissions for To Lower Case.
*
*/
class Solution {
public:
string toLowerCase(string str) {
for (char& letter : str){
if (letter >= 'A' && letter <= 'Z') {
letter += 32;
}
}
return str;
}
};
|
Markdown | UTF-8 | 690 | 3.234375 | 3 | [] | no_license | # PythonGeometryObject2D
In this practice, i make my own distribution to print some 2D Geometry Object
Which have feature to prints
--
1. Square
2. Rectangle
3. Right Triangle
4. Equilateral Triangle
Installation
--
Run the following to install:
pip install geometryobject
Usage
--
import geometyobject as obj2d;<br><br>
#To print square object<br>
obj2d.printSquare(5)<br>
#5 is side length<br>
<br>
#To print rectangle object<br>
obj2d.printRectangle(3,7)<br>
#3 is height<br>
#7 is length<br>
<br>
#To print right triangle object<br>
obj2d.printRightTriangle(5)<br>
#5 is height<br>
<br>
#To print equilateral triangle object<br>
obj2d.printEquilateralTriangle(5)<br>
#5 is height
|
C# | UTF-8 | 6,643 | 2.78125 | 3 | [
"MIT"
] | permissive | // Author:
// jjennings <jaredljennings@gmail.com>
//
// Copyright (c) 2012 jjennings
// Robert Nordan
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using Tomboy.Tags;
using System.Linq;
namespace Tomboy
{
/// <summary>
/// Tomboy Engine.
/// </summary>
public class Engine
{
#region fields
/* holds whatever storage interface will be used */
private IStorage storage;
private static TagManager tagMgr = TagManager.Instance;
/* holds the current notes
* This will change as notes are added or removed */
public Dictionary<string, Note> Notes { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Tomboy.Engine"/> class.
/// </summary>
/// <description>Must provide whatever storage class that should be used by the Engine</description>
/// <param name='storage'>
/// Storage.
/// </param>
public Engine (IStorage storage)
{
if (storage == null)
throw new ArgumentNullException ("storage");
this.storage = storage;
this.Notes = new Dictionary<string, Note> ();
var temp_notes = this.storage.GetNotes ();
foreach (string item in temp_notes.Keys) {
this.Notes.Add (item, temp_notes [item]);
tagMgr.AddTagMap (temp_notes [item]);
}
}
#endregion
#region delegate
public delegate void NoteAddedEventHandler (Note note);
public delegate void NoteRemovedEventHandler (Note note);
public delegate void NoteUpdatedEventHandler (Note note);
#endregion
#region event handlers
public event NoteAddedEventHandler NoteAdded;
public event NoteAddedEventHandler NoteRemoved;
public event NoteAddedEventHandler NoteUpdated;
#endregion
#region public methods
/// <summary>
/// Gets the tags, which is built from the collection of Notes
/// </summary>
/// <returns>
/// The tags.
/// </returns>
public List<Tag> GetTags ()
{
return tagMgr.AllTags;
}
/// <summary>
/// Gets the notes.
/// </summary>
/// <description>
/// Dictionary looks like <note://tomboy/44a1a2d6-7ffb-46e0-9b5c-a00260a5bb50, Note>
/// </description>
/// <returns>
/// Dictionary<string, Note>
/// </returns>
[Obsolete("Use the property 'Notes' on the Engine instead")]
public Dictionary<string, Note> GetNotes ()
{
return this.Notes;
}
/// <summary>
/// Gets the specified Note based on Title search
/// </summary>
/// <returns>
/// The note.
/// </returns>
/// <param name='title'>
/// Title.
/// </param>
public Note GetNote (string title)
{
foreach (KeyValuePair<string, Note> n in this.Notes){
if (String.Compare (n.Value.Title, title, StringComparison.InvariantCultureIgnoreCase) == 0)
return n.Value;
}
return null;
}
/// <summary>
/// Gets the notes that match the search term.
/// </summary>
/// <param name='searchTerm'>
/// Search term.
/// </param>
/// <param name='searchContent'>
/// Decides whether to search only the titles or to search the content as well.
/// </param>
public Dictionary<string, Note> GetNotes (string searchTerm, bool searchContent)
{
if (!searchContent) {
return SearchEngine.SearchTitles (searchTerm.ToLowerInvariant (), this.Notes);
} else {
return SearchEngine.SearchContent (searchTerm.ToLowerInvariant (), this.Notes);
}
}
public Dictionary<string, Note> GetNotesForNotebook(string notebook)
{
if (notebook.Equals ("All Notebooks", StringComparison.Ordinal)) {
return this.Notes;
} else {
var results = this.Notes.Values.Where(
n => n.Notebook != null && n.Notebook.Equals (notebook, StringComparison.Ordinal)
).ToDictionary(n => n.Guid, n => n);
return results;
}
}
/// <summary>
/// Generates a New Note instance
/// </summary>
/// <returns>
/// The note.
/// </returns>
public Note NewNote ()
{
// We maybe need a way to detect if we've tried loading the notes yet.
// basically it's possible to call NewNote () and not have loaded the notes database yet.
// this would then generate a 0 note list.
Note note = NoteCreator.NewNote (Notes.Count);
Notes.Add (note.Uri, note);
if (NoteAdded != null)
NoteAdded (note);
return note;
}
/// <summary>
/// Saves the note.
/// </summary>
/// <param name='note'>
/// Note.
/// </param>
/// <param name='update_dates'>
/// By default true and can be omited. If set to false, do not update the ChangeDate
/// and MetadataChangeDate fields. Usefull for pure data storage, and when syncing.
/// </param>
public void SaveNote (Note note, bool update_dates = true)
{
if (update_dates) {
DateTime saveUtcNow = DateTime.UtcNow;
note.ChangeDate = saveUtcNow;
}
/* Update the dictionary of notes */
if (Notes.ContainsKey (note.Uri))
Notes.Remove (note.Uri);
Notes.Add (note.Uri, note);
tagMgr.AddTagMap (note);
/* Save Note to Storage */
this.storage.SaveNote (note);
if (NoteUpdated != null)
NoteUpdated (note);
}
/// <summary>
/// Deletes the note.
/// </summary>
/// <param name='note'>
/// Note.
/// </param>
public void DeleteNote (Note note)
{
if (Notes.ContainsKey (note.Uri))
Notes.Remove (note.Uri);
tagMgr.RemoveNote (note);
this.storage.DeleteNote (note);
if (NoteRemoved != null)
NoteRemoved (note);
}
/// <summary>
/// Adds existing notes, to be used by for example sync agents
/// </summary>
/// <param name='note'>
/// Note.
/// </param>
public void AddAndSaveNotes (Dictionary<string, Note> newNotes)
{
foreach (string guid in newNotes.Keys) {
SaveNote (newNotes[guid]);
}
}
public void SetConfigVariable (string key, string value)
{
storage.SetConfigVariable (key, value);
}
public string GetConfigVariable (string key)
{
return storage.GetConfigVariable (key);
}
#endregion
#region Events
#endregion
}
} |
PHP | UTF-8 | 318 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
echo "Socket Server running on localhost:8001" . PHP_EOL;
$socket = stream_socket_server('tcp://localhost:8001');
$conn = stream_socket_accept($socket);
$wait = rand(1, 5);
sleep($wait);
fwrite($conn, "Socket Server Response after $wait seconds\n");
fclose($conn);
echo "Socket Server stopped" . PHP_EOL;
|
Java | UTF-8 | 1,296 | 4.0625 | 4 | [] | no_license | package com.revature.classbasics;
public class ControlStatements {
public static void main(String[] args) {
// int[row][col] ??
int[][] twoD = new int[4][5]; // Arrays are NOT dynamically sized
// FOR EACH ("enhanced for loops") - at runtime, get converted behind the scenes to a regular
// for loop used to iterate over arrays or collections
String[] strings = {"string 1", "string 2", "string 3 "};
for(String s : strings){
s.replaceAll(" ", "--");
System.out.println(s);
System.out.println(s.replaceAll(" ", "--"));
}
// DO WHILE
int x;
do {
x=1;
x++;
}
while(x<10);
// SWITCH: use only for discrete options
// can only use prims that can be cast to an int (short, byte, char).
// can use enums and Strings
// so can use: byte, short, char, int
// Byte, Short, Character, Integer
// Enums(enumerations, special characters)
// Strings
int fromUser = 2;
/*
* Will print: 2
* 10
* default
*/
switch(fromUser){
case 1:
System.out.println("1");
break;
// System.out.println("unreachable"); // Unreachable code does not compile
case 2:
System.out.println("2");
case 10:
System.out.println("10");
default: System.out.println("default");
}
}
}
|
Swift | UTF-8 | 852 | 2.9375 | 3 | [] | no_license | //
// ServerManager.swift
// VKHackathon2019
//
// Created by Михаил Луцкий on 29/09/2019.
// Copyright © 2019 Mikhail Lutskii. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
class ServerManager {
static func getList(emoji: String, r: @escaping(_ trips: [TripObject]) -> Void) {
let url = "http://demo14.charlie.vkhackathon.com:8080/gen/\(emoji)"
let safeURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
Alamofire.request(safeURL).responseJSON { (response) in
switch response.result {
case .success:
let trips = Mapper<TripObject>().mapArray(JSONObject: response.result.value)
r(trips ?? [TripObject]())
case .failure(let error):
print("Error \(error)")
}
}
}
}
|
C# | UTF-8 | 2,961 | 2.671875 | 3 | [] | no_license | //using Lib.Finder;
//using Lib.Models;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using System.Windows.Forms;
//namespace ManualControl
//{
// class ProgramPlayer
// {
// History mapHistory;
// public Action MapUpdated;
// public Action<bool> LoadedUpdated;
// public Action<bool> AutoplayUpdated;
// public bool Loaded { get; private set; }
// public bool Autoplay { get; private set; }
// public int TimerInterval { get { return timer.Interval; } set { timer.Interval = value; } }
// Timer timer;
// public ProgramPlayer(History mapHistory)
// {
// this.mapHistory = mapHistory;
// timer = new Timer();
// timer.Interval = 10;
// timer.Tick += (s,a)=>Step();
// }
// public void InitializeProgram(string program)
// {
// if (Loaded) throw new Exception("Can't init program when loading");
// Program = program;
// ProgramPointer = 0;
// Loaded = true;
// if (LoadedUpdated!=null) LoadedUpdated(true);
// }
// bool stopWhenFinished;
// public void Play(bool stopWhenFinished=false)
// {
// if (!Loaded) throw new Exception("No program to run");
// timer.Start();
// Autoplay = true;
// this.stopWhenFinished = stopWhenFinished;
// if (AutoplayUpdated != null) AutoplayUpdated(true);
// }
// public void Pause()
// {
// if (!Loaded) throw new Exception("No program to run");
// timer.Stop();
// Autoplay = false;
// if (AutoplayUpdated != null) AutoplayUpdated(false);
// }
// public void Stop()
// {
// Pause();
// Program = null;
// Loaded = false;
// if (LoadedUpdated!=null) LoadedUpdated(false);
// }
// public void Step()
// {
// if (!Loaded) throw new Exception("No program to run");
// var over = mapHistory.Peek().IsOver;
// if (ProgramPointer >= Program.Length )
// {
// Pause();
// if (stopWhenFinished)
// Stop();
// return;
// }
// var c = Program[ProgramPointer];
// var dir = c.ToDirection();
// if (!mapHistory.Peek().IsOver)
// mapHistory.Push(mapHistory.Peek().Move(dir));
// ProgramPointer++;
// if (MapUpdated != null) MapUpdated();
// }
// public void Back()
// {
// if (ProgramPointer>0)
// {
// ProgramPointer--;
// mapHistory.Pop();
// if (MapUpdated != null) MapUpdated();
// }
// }
// }
//}
|
C | UTF-8 | 1,368 | 2.84375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* node_add.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: knaumov <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/01 10:40:45 by knaumov #+# #+# */
/* Updated: 2018/10/01 10:40:46 by knaumov ### ########.fr */
/* */
/* ************************************************************************** */
#include "b_ls.h"
t_node *node_add(t_node *root, char *name, struct stat buf)
{
t_node *temp;
t_node *begin_list;
if (root == NULL)
{
root = malloc(sizeof(t_node));
root->name = ft_strdup(name);
root->buf = buf;
root->next = NULL;
return (root);
}
begin_list = root;
temp = (t_node *)malloc(sizeof(t_node));
temp->name = ft_strdup(name);
temp->buf = buf;
temp->next = NULL;
while (root->next)
root = root->next;
root->next = temp;
return (begin_list);
}
|
SQL | UTF-8 | 2,009 | 3.0625 | 3 | [
"MIT"
] | permissive | -- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 20, 2021 at 07:37 AM
-- Server version: 10.4.6-MariaDB
-- PHP Version: 7.2.22
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `data`
--
-- --------------------------------------------------------
--
-- Table structure for table `biodata_artis`
--
CREATE TABLE `biodata_artis` (
`uuid` int(255) NOT NULL,
`nama` varchar(255) DEFAULT NULL,
`tempat_lahir` varchar(255) DEFAULT NULL,
`tanggal_lahir` date DEFAULT NULL,
`foto` varchar(255) DEFAULT NULL,
`alamat_tinggal` varchar(255) DEFAULT NULL,
`id_kecamatan` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `biodata_artis`
--
INSERT INTO `biodata_artis` (`uuid`, `nama`, `tempat_lahir`, `tanggal_lahir`, `foto`, `alamat_tinggal`, `id_kecamatan`) VALUES
(1, 'ateng', 'pekanbaru', '2021-03-02', 'kkkk', 'jl.nangka', '14'),
(2, 'aa', 'aa', '2021-03-03', 'ada', 'aa', NULL),
(3, 'sfwe', 'aawda', '2021-03-04', 'wda', 'wdaw', NULL),
(4, 'aa', 'aa', '2021-03-19', 'wd', 'wdad', '110116'),
(5, 'aaa', 'aaa', '2021-03-11', 'aaa', 'aaa', '110114');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `biodata_artis`
--
ALTER TABLE `biodata_artis`
ADD PRIMARY KEY (`uuid`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `biodata_artis`
--
ALTER TABLE `biodata_artis`
MODIFY `uuid` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
JavaScript | UTF-8 | 12,154 | 2.828125 | 3 | [
"MIT"
] | permissive |
/**
* Service base class
* Return output usable in a REST service but also usable via js API
*
* @constructor
*
*/
function apiService() {
'use strict';
/*jshint validthis: true */
var service = this;
/**
* trace errors to console
* @var {Boolean}
*/
this.trace = false;
/**
* HTTP status for service
* will be used only by REST service
* @var {Number}
*/
this.httpstatus = 200;
/**
* Path used in getService
* defined withing the function app.getService
* @var {String}
*/
this.path = null;
/**
* Service outcome
* contain success boolean
* a list of alert messages
* errfor: errors associated to fields
*/
this.outcome = {
success: true,
alert: [],
errfor: {}
};
this.Q = require('q');
/**
* Defered service result
*/
this.deferred = this.Q.defer();
/**
* Services instances must implement
* this method to resolve or reject the service promise
*
* @param {Object} params
*
* @return {Promise}
*/
this.getResultPromise = function(params) {
console.log('Not implemented');
return this.deferred.promise;
};
/**
* Set application
* @param {Object} app
*/
this.setApp = function(app) {
service.app = app;
};
/**
* Add alert to service
* @param {string} type One of boostrap alert types (danger|success|info)
* @param {String|Error} err Error message or object
*/
this.addAlert = function(type, err) {
var alert = { type: type };
if (err instanceof Error) {
alert.message = err.name+' : '+err.message;
alert.stack = err.stack;
} else if (typeof err === 'string') {
alert.message = err;
} else {
console.error(err);
throw new Error('Wrong error type, must be a string or Error, got '+(typeof err));
}
service.outcome.alert.push(alert);
};
/**
* Get an error object from a mixed value
* @param {String|Error} err
* @returns {Error}
*/
this.getError = function(err) {
if (err instanceof Error) {
return err;
}
return new Error(err);
};
/**
* Reject the service promise with an forbidden status
* The server understood the request, but is refusing to fulfill it.
* Authorization will not help and the request SHOULD NOT be repeated.
* If the request method was not HEAD and the server wishes to make public
* why the request has not been fulfilled, it SHOULD describe the reason for
* the refusal in the entity. If the server does not wish to make this
* information available to the client, the status code 404 (Not Found)
* can be used instead.
* @param {String|Error} err
*/
this.forbidden = function(err) {
service.httpstatus = 403;
service.outcome.success = false;
service.addAlert('danger', err);
service.deferred.reject(service.getError(err));
};
/**
* Reject the service promise with an error status
* The HTTP server encountered an unexpected condition which prevented
* it from fulfilling the request.
* For example this error can be caused by a serveur misconfiguration,
* or a resource exhausted or denied to the server on the host machine.
*
* @param {String|Error} err
*/
this.error = function(err) {
if (err.name === 'ValidationError') {
return service.handleMongoError(err); // 400
}
service.httpstatus = 500;
service.outcome.success = false;
service.addAlert('danger', err);
service.deferred.reject(service.getError(err));
};
/**
* Ouput a 404 error
* with an outcome message
*
* @param {String|Error} err
*/
this.notFound = function(err) {
service.httpstatus = 404;
service.outcome.success = false;
service.addAlert('danger', err);
service.deferred.reject(service.getError(err));
};
/**
* Ouput a 410 error
* with an outcome message
*
* @param {String|Error} err
*/
this.gone = function(err) {
service.httpstatus = 410;
service.outcome.success = false;
service.addAlert('danger', err);
service.deferred.reject(service.getError(err));
};
/**
* Set a success message into outcome
* @param {String} message
*/
this.success = function(message) {
service.addAlert('success', message);
};
/**
* output document and $outcome with a sucess message
*
* @param {Document} document Mongoose document
* @param {String} message message for outcome
*/
this.resolveSuccess = function(document, message) {
service.outcome.success = true;
service.success(message);
var output;
if (document.toObject) {
output = document.toObject();
} else {
output = document;
}
output.$outcome = service.outcome;
service.deferred.resolve(output);
};
/**
* Get a document using the sibling get service
* @param {String} param all parameters or document ID to get, this will set the 'id' param in the parameters given to GET service
* @return {Promise} promise resolve to an object but without the $outcome property
*/
this.get = function(param) {
if (null === service.path) {
throw new Error('The path need to be defined in the app.getService function');
}
var path = service.path.split('/');
delete path[path.length-1];
if (typeof param !== 'object' || param.constructor.name === 'ObjectID') {
param = { id: param };
}
return service.app.getService(path.join('/')+'/get')
.getResultPromise(param)
.then(function(serviceObject) {
delete serviceObject.$outcome;
return serviceObject;
});
};
/**
* output document from the sibling get service and $outcome with a sucess message
* @param {String} param savedDocument ID or parameters
* @param {String} message message for outcome
*/
this.resolveSuccessGet = function(param, message) {
this.get(param).then(function(document) {
service.resolveSuccess(document, message);
})
.catch(service.error);
};
/**
* emit exception if parameter contain a mongoose error
*
* @param {Error|null} err - a mongoose error or no error
* @param {Boolean} trace set to false to disable console.trace of the error
*
* @return {Boolean}
*/
this.handleMongoError = function(err) {
if (err) {
if (true === service.trace) {
console.trace(err);
}
service.httpstatus = 400; // Bad Request
if (err.errors) {
for(var field in err.errors) {
var e = err.errors[field];
service.outcome.errfor[field] = e.type;
service.outcome.alert.push({ type:'danger' ,message: e.message});
}
}
service.outcome.alert.push({ type:'danger' ,message: err.message});
service.outcome.success = false;
service.deferred.reject(new Error(err.message));
return false;
}
return true;
};
/**
* @return {Boolean}
*/
this.hasErrors = function() {
if (Object.keys(service.outcome.errfor).length !== 0) {
return true;
}
for(var i=0; i<service.outcome.alert.length; i++) {
if (service.outcome.alert[i].type === 'danger') {
return true;
}
}
return false;
};
}
/**
* Service to get a list of items
* output a resultset
*
*/
function listItemsService(app) {
apiService.call(this);
this.setApp(app);
var service = this;
/**
* Default function used to resolve a result set
*
* @param {Error} err mongoose error
* @param {Array} docs an array of mongoose documents or an array of objects
*/
this.mongOutcome = function(err, docs) {
if (service.handleMongoError(err))
{
service.outcome.success = true;
service.deferred.resolve(docs);
}
};
/**
* Resolve a mongoose query, paginated or not
* This method can be used by the service to resolve a mongoose query
* The paginate parameter is optional, if not provided, all documents will be resolved to the service promise.
* the function to use for pagination is the 2nd argument of the getResultPromise() method
* @see listItemsService.getResultPromise()
*
* @param {Query} find
* @param {function} [paginate] (controller optional function to paginate result)
* @param {function} [mongOutcome] optional function to customise resultset before resolving
*/
this.resolveQuery = function(find, paginate, mongOutcome) {
if (!mongOutcome) {
mongOutcome = this.mongOutcome;
}
find.exec(function(err, docs) {
if (!err && typeof paginate === 'function') {
return paginate(docs.length, find).exec(mongOutcome);
}
return mongOutcome(err, docs);
});
};
/**
* Services instances must implement
* this method to resolve or reject the service promise
* list items services have an additional parameter "paginate", this function will be given as parameter
* by the controller
*
* @see listItemsController.paginate()
*
* @param {Object} params
* @param {function} paginate
*
* @return {Promise}
*/
this.getResultPromise = function(params, paginate) {
console.log('Not implemented');
return this.deferred.promise;
};
}
listItemsService.prototype = new apiService();
/**
* Service to get one item
* output one object
* @constructor
*
* @param {Object} app
*/
function getItemService(app) {
apiService.call(this);
this.setApp(app);
}
getItemService.prototype = new apiService();
/**
* Service to create or update one item
* output the saved object
* @constructor
*
* @param {Object} app
*/
function saveItemService(app) {
apiService.call(this);
this.setApp(app);
var service = this;
/**
* Test required fields in params
* complete outcome and http status if a fields is empty
*
* @param {Object} params - parameters to save
* @param {Array} list - list of fields to test
*
* @return {bool}
*/
service.needRequiredFields = function(params, list) {
for(var i=0; i<list.length; i++)
{
if (!params[list[i]]) {
service.outcome.errfor[list[i]] = 'required';
service.httpstatus = 400; // Bad Request
service.outcome.success = false;
}
}
if (service.hasErrors()) {
service.deferred.reject(new Error('Missing mandatory fields'));
return true;
}
return false;
};
}
saveItemService.prototype = new apiService();
/**
* Service to delete one item
* output the deleted object
* @constructor
*
* @param {Object} app
*/
function deleteItemService(app) {
apiService.call(this);
this.setApp(app);
}
deleteItemService.prototype = new apiService();
/**
* Load a service object
* @param {express|Object} app Express app or headless app
* @param {String} path
*
* @return {apiService}
*/
function loader(app, path) {
return app.getService(path);
}
exports = module.exports = {
list: listItemsService,
get: getItemService,
save: saveItemService,
delete: deleteItemService,
load: loader
};
|
Java | UTF-8 | 1,361 | 2.765625 | 3 | [] | no_license | package org.densyakun.bukkit.animalcrossing.menumanager;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.densyakun.bukkit.animalcrossing.playermanager.PlayerData;
import org.densyakun.bukkit.animalcrossing.playermanager.PlayerRank;
public class InventoryChangeRank extends MenuInventory {
PlayerData playerdata;
public InventoryChangeRank(MenuManager menumanager, UUID uuid, PlayerData playerdata) {
super(menumanager, 9, "内部ランクを変更", uuid);
this.playerdata = playerdata;
setitem(0, Material.WOOD, PlayerRank.Default.getChatColor() + PlayerRank.Default.name());
setitem(2, Material.IRON_BLOCK, PlayerRank.Admin.getChatColor() + PlayerRank.Admin.name());
setitem(4, Material.OBSIDIAN, PlayerRank.Owner.getChatColor() + PlayerRank.Owner.name());
}
@Override
public void Click(InventoryClickEvent e) {
switch (e.getRawSlot()) {
case 0:
playerdata.setRank(PlayerRank.Default);
break;
case 2:
playerdata.setRank(PlayerRank.Admin);
break;
case 4:
playerdata.setRank(PlayerRank.Owner);
break;
default:
break;
}
e.getWhoClicked().closeInventory();
e.getWhoClicked().sendMessage(ChatColor.AQUA + "内部ランクを変更: " + playerdata.getRank().getChatColor() + playerdata.getInternalRank());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.