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 |
|---|---|---|---|---|---|---|---|
Ruby | UTF-8 | 1,591 | 3.484375 | 3 | [] | no_license | require "benchmark"
def solution(a)
result = nil
length = a.size
for i in 0..(length-1)
while a[i] != (i+1)
item = a[i]
break if item >= length || a[item-1] == item
a[i] = a[item-1]
a[item-1] = item
end
result = i+1 if a[i] > length
end
result = length+1 if !result
result
end
puts "solution([]) should = 1: #{solution([])}"
puts "solution([1]) should = 2: #{solution([1])}"
puts "solution([2]) should = 1: #{solution([2])}"
puts "solution([1,2]) should = 3: #{solution([1,2])}"
puts "solution([1,3]) should = 2: #{solution([1,3])}"
puts "solution([4,1,3]) should = 2: #{solution([4,1,3])}"
puts "solution([5,2,1,3]) should = 4: #{solution([5,2,1,3])}"
puts "solution([2,3,1,5]) should = 4: #{solution([2,3,1,5])}"
puts "solution([3,2,1,4]) should = 5: #{solution([3,2,1,4])}"
puts "solution([10,2,6,3,8,1,5,7,4]) should = 9: #{solution([10,2,6,3,8,1,5,7,4])}"
puts ""
puts "============================================================"
puts RUBY_DESCRIPTION
puts "============================================================"
puts "Running tests for cyclic rotation of an array"
N=50_000
Benchmark.bm(30) do |x|
x.report("solution([1,3])") { N.times { solution([1,3]) } }
x.report("solution([4,1,3])") { N.times { solution([4,1,3]) } }
x.report("solution([5,2,1,3])") { N.times { solution([5,2,1,3]) } }
x.report("solution([2,3,1,5])") { N.times { solution([2,3,1,5]) } }
x.report("solution([10,2,6,3,8,1,5,7,4])") { N.times { solution([10,2,6,3,8,1,5,7,4]) } }
end if false
|
Markdown | UTF-8 | 5,258 | 3.359375 | 3 | [] | no_license | # Applicant comments
> <img src="http://hhru.github.io/api/badges/emp_paid.png" alt="employer with paid access" /> : Methods require [paid access for the employer](employer_payable_methods.md)
* [List of comments](#list)
* [Adding a comment](#add_comment)
* [Comment update](#edit_comment)
* [Delete comment](#delete_comment)
<a name="list"></a>
## List of comments
Receiving the list of comments is available only for an employer. The list will
contain comments of the current user as well as comments of other company
managers provided that the managers made these comments accessible to others at
the moment of posting.
### Request
No need to construct the request url on your own – it should be received from
the [owner CV field](resumes.md#owner-field)
`GET /applicant_comments/{applicant_id}`
where `applicant_id` is the applicant ID.
Additional request parameters:
* [`page` and `per_page` pagination parameters](general.md#pagination)
* `order_by` – comments sorting, available values are provided in the
[`applicant_comments_order` reference](dictionaries.md)
### Response
Successful server response is returned with `200 OK` code and contains:
```json
{
"found": 2,
"page": 0,
"pages": 1,
"per_page": 20,
"items": [
{
"author": {
"full_name": "Ivanov Ivan Ivanovich"
},
"created_at": "2015-08-27T10:19:55+0300",
"id": "123456",
"is_mine": true,
"text": "look at this candidate\nnow!",
"access_type": {
"id": "coworkers",
"name": "Visible to me and my colleagues",
}
},
{
"author": {
"full_name": "Ivanova Maria Ivanovna"
},
"created_at": "2015-08-27T10:30:14+0300",
"id": "123654",
"is_mine": false,
"text": "do not consider necessary",
"access_type": {
"id": "owner",
"name": "Visible only to me",
}
}
]
}
```
key| type| description
-----|-----|---------
author.full_name| string| comment author full name
created_at| string, date| comment creation date
id| string| comment unique ID
is_mine| logical| was the comment written by the current user?
text| string| comment content, text that can contain newline characters
access_type | object | access types for comments, possible values are stored in the [directory](dictionaries.md#etc)
### Errors
* `404 Not Found` – the specified applicant was not found.
* `403 Forbidden` – receiving comments is not available for the current user.
<a name="add_comment"></a>
## Adding a comment
### Request
You do not need to construct the request URL manually, you can get it from
[the `owner` field in the resume](resumes.md#owner-field)
`POST /applicant_comments/{applicant_id}`
where
* `applicant_id` – applicant ID
Request parameters:
* `text` - comment text,
* `access_type` - access type (possible values are stored in the [applicant_comment_access_type directory](dictionaries.md#etc))
### Response
Successful response is returned with `201 Created` code and contains added comment:
```json
{
"author": {
"full_name": "Ivanova Maria Ivanovna"
},
"created_at": "2015-08-27T10:30:14+0300",
"id": "123654",
"is_mine": true,
"text": "do not consider necessary",
"access_type": {
"id": "owner",
"name": "Visible only to me",
}
}
```
### Errors
* `403 Forbidden` – if the current user is not an employer.
* `404 Not Found` – the specified applicant does not exist.
* `400 Bad argument` – error in the request parameters.
<a name="edit_comment"></a>
## Comment update
You can change the access type and text of an existing comment.
Only the author can change the comment.
### Request
To get the URL, add a comment ID to the URL of the [list of comments](#list).
`PUT /applicant_comments/{applicant_id}/{comment_id}`
where
* `applicant_id` – applicant ID,
* `comment_id` – comment ID.
Request parameters:
* `text` - comment text,
* `access_type` - access type (possible values are stored in the [applicant_comment_access_type directory](dictionaries.md#etc))
The comment text and access type can be changed. If the parameter is not passed,
then the value will remain the same.
### Response
A successful response contains a code `204 No Content` and is body-less.
### Errors
* `403 Forbidden` – if the current user is not an employer.
* `404 Not Found` – if the specified applicant or comment does not exist.
* `400 Bad argument` – error in the request parameters; in addition, the names of parameter with errors may be specified.
<a name="delete_comment"></a>
## Delete comment
Only the author can delete the comment.
### Request
To get the URL, add a comment ID to the URL of the [list of comments](#list).
`DELETE /applicant_comments/{applicant_id}/{comment_id}`
where
* `applicant_id` – applicant ID,
* `comment_id` - comment ID
### Response
A successful response contains a code `204 No Content` and is body-less.
### Errors
* `403 Forbidden` – if the current user is not an employer
* `404 Not Found` – if the specified applicant or comment does not exist. |
Python | UTF-8 | 1,993 | 2.640625 | 3 | [] | no_license | #!/usr/bin/env python
import socket
import time
import datetime
from thread import *
import threading
import Queue
import select
import os
import signal
import errno
import random
TIMEOUT = 5
do_work = 1
def proc_evt_q(q,pid_list):
while not q.empty():
item = q.get()
pid_list[item[0]] = item[1]
q.task_done()
def proc_pid_list(pid_list):
start_ts = time.time()
bad_proc = 0
for item in pid_list.keys():
curr_ts = time.time()
last_seen = pid_list[item]
delta = curr_ts - last_seen
if delta > TIMEOUT:
print "Something wrong with pid %d" % (int(item))
bad_proc += 1
#del pid_list[item]
print "it took", time.time() - start_ts, "seconds."
print "Dict length", len(pid_list), "Stuck proc ", bad_proc
def timer_thread(q):
pid_list = {}
while do_work:
time.sleep(2)
#print "Check event queue."
proc_evt_q(q,pid_list)
#print "Processed element in queue"
proc_pid_list(pid_list)
#print pid_list
print "Killing all processes in list..."
for item in pid_list.keys():
cmd = "kill -9 {0}".format(item)
os.system(cmd)
def my_handler(sig, frame):
global do_work
print "Clearing up child processes"
do_work = 0
q = Queue.Queue()
""" Create a background thread to do work """
timer_t = threading.Thread(target=timer_thread, args=(q,))
timer_t.daemon = True
timer_t.start()
signal.signal(signal.SIGINT, my_handler)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('localhost', 10000))
while do_work:
try:
data, address = s.recvfrom(4096)
#print "Received %s bytes from %s" % (len(data), address)
if data:
elems = data.split()
#print elems
q.put((elems[0],time.time()))
except socket.error as (code,msg):
if code != errno.EINTR:
raise
print "Main thread done"
timer_t.join()
|
Java | UTF-8 | 1,170 | 1.953125 | 2 | [] | no_license | package com.qlf.plants.activity;
import com.qlf.plants.MainActivity;
import com.qlf.plants.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class AskPosActivity extends Activity{
Button buy,nobuy;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.zhongduantip);
buy = (Button) findViewById(R.id.button_buyed);
buy.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
});
nobuy = (Button) findViewById(R.id.button_notbuyed);
nobuy.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
});
}
}
|
Python | UTF-8 | 1,904 | 3.609375 | 4 | [] | no_license | import heapq
#pair:(vertex, weight)
adjList = {1:[(2,10),(4,5)],
2:[(3,1),(4,2)],
3:[(5,4)],
4:[(2,3),(3,9),(5,2)],
5:[(1,7),(3,6)]}
heap = []
def decreaseKey(solution, adjList, heap):
for vertexInSol in solution:
for pair in adjList[vertexInSol[2]]:
for vertexInHeap in heap:
if(vertexInHeap[2] == pair[0]):
if(pair[1] + vertexInSol[0] == vertexInHeap[0]):
if(vertexInHeap[1] > vertexInSol[1] + 1):
vertexInHeap[1] = vertexInSol[1] + 1
vertexInHeap[3] = vertexInSol[2]
if(pair[1] + vertexInSol[0] < vertexInHeap[0]):
vertexInHeap[0] = pair[1] + vertexInSol[0]
vertexInHeap[1] = vertexInSol[1] + 1
vertexInHeap[3] = vertexInSol[2]
def dijkstra(adjList, source, target):
#vertex in heap: (distance, pathlen, name, parent)
solution = []
heapq.heappush(heap, [0, 0, source, 0])
for vertex in adjList:
if(vertex != source):
heapq.heappush(heap, [float('INF'), float('INF'), vertex, 0])
heapq.heapify(heap)
currentVertex = [0,0,0,0]
while currentVertex[2] != target:
currentVertex = heapq.heappop(heap)
solution.append(currentVertex)
decreaseKey(solution, adjList, heap)
heapq.heapify(heap)
return solution
def findPath(solution, source):
size = len(solution)
path = []
if size == 0:
return path
vertexInSol = solution[size - 1]
while vertexInSol[2] != source:
path.append(vertexInSol)
for vertex in solution:
if vertex[2] == vertexInSol[3]:
vertexInSol = vertex
path.append(vertexInSol)
return path
result = dijkstra(adjList, 1, 5)
print result
print findPath(result, 1)
|
TypeScript | UTF-8 | 3,772 | 2.671875 | 3 | [
"MIT"
] | permissive | import { createElement as h } from "react";
import { DOMParser, XMLSerializer } from "xmldom";
import { camelCase } from "lodash";
const { styled } = require("@patternplate/components");
const parser = new DOMParser();
const serializer = new XMLSerializer();
const TAG_NAMES = ["circle", "g", "path", "polygon", "rect", "svg"];
/**
* These attributes are valid on all SVG elements and accepted by this
* renderer.
* All attributes will be converted to their camelCase version.
* This allows using valid SVG strings.
* Extend this list to allow additional default SVG attributes.
*
* @type {Array}
*/
const SHARED_ATTRIBUTES = ["fill", "stroke", "stroke-width"];
const ATTRIBUTES: {[element: string]: string[]} = {
circle: [...SHARED_ATTRIBUTES, "cx", "cy", "r", "style"],
g: [...SHARED_ATTRIBUTES, "x", "y"],
path: [...SHARED_ATTRIBUTES, "d", "style"],
polygon: [...SHARED_ATTRIBUTES, "points"],
rect: [...SHARED_ATTRIBUTES, "x", "y", "width", "height", "style"],
svg: ["width", "height", "viewBox", "x", "y", "style", "xmlns"]
};
function attributes(node: Element, key: number | string) {
return (ATTRIBUTES[node.tagName] || []).reduce(
(props: {[key: string]: any}, name: string) => {
const attribute = node.attributes.getNamedItem(name);
const reactProp = camelCase(name);
if (attribute && attribute.specified) {
props[reactProp] = attribute.value;
}
return props;
},
{ key }
);
}
export function btoa(source: string): string {
return `data:image/svg+xml;base64,${Buffer.from(source).toString("base64")}`;
}
export function parse(source: string) {
const doc = parser.parseFromString(source, "image/svg+xml");
const parsed = Array.prototype.slice.call(doc.childNodes).find((node: Element) => node.tagName === "svg");
parsed.setAttribute("xmlns", "http://www.w3.org/2000/svg");
return parsed;
}
export function purge(parsed: Element[]): Element[] {
return Array.prototype.slice.call(parsed)
.filter((node: Element) => TAG_NAMES.indexOf(node.tagName) > -1)
.map((node: Element) => {
const children: any = node.childNodes;
(node as any).childNodes = purge(children);
const attributes = ATTRIBUTES[node.tagName] || [];
for (let i = 0; i < node.attributes.length; i++) {
const attribute = node.attributes[i];
if (attributes.indexOf(attribute.name) === -1) {
node.removeAttribute(attribute.name);
}
}
return node;
});
}
export function render(element: any): React.ReactNode {
const [tagName, props, children = []] = element;
const { style, ...rest } = props;
const tag = styled(tagName)`
${style};
`;
return h(tag, rest, children.map((c: any) => render(c)));
}
export function sanitize(parsed: Element[]): any[] {
return [...parsed].map((node, i) => [
(node as Element).tagName,
attributes((node as Element), i),
sanitize(node.childNodes as any)
]);
}
export function stringify(tree: Document): string {
return serializer.serializeToString(tree);
}
interface Renderable {
0: string;
1: {[key: string]: any};
2: Renderable[];
}
interface Criteria {
width: number;
height: number;
}
export function detectBackground(tree: Renderable, criteria: Criteria): string {
const bgs: string[] = [];
walk(tree, node => {
if (node[0] !== "rect") {
return;
}
if (Number(node[1].height) !== criteria.height) {
return;
}
if (Number(node[1].width) !== criteria.width) {
return;
}
if (node[1].fill) {
bgs.push(node[1].fill);
}
});
return bgs[bgs.length - 1];
}
function walk(node: Renderable, predicate: (node: Renderable) => void) {
predicate(node);
node[2].forEach(n => walk(n, predicate));
}
|
JavaScript | UTF-8 | 308 | 2.734375 | 3 | [] | no_license | export const setTheme = name => {
try {
localStorage.setItem("theme", name);
} catch (error) {
console.log(error);
};
};
export const getTheme = () => {
try {
const ongoingTheme = localStorage.getItem("theme");
return ongoingTheme;
} catch (error) {
console.log(error);
};
}; |
Markdown | UTF-8 | 1,059 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | ---
layout: post
title: "Python2 str and unicode err"
description:
category: python
tags:
---
{% include JB/setup %}
使用Py2最大的不爽的一点就是,在文件写入带有非asii码字符时总是容易出错。一会儿又需要调用codecs模块啦,
一会儿又是 str.decode() 着的 unicode.encode()方法了。 什么时候调用 decode 什么时候调用 encode总是搞混。
而且一个最大的麻烦就是,怎么知道一个对象是str还是unicode对象呢?
设想一个场景,从命令行传递 参数给 python script.py arg0 arg1 这种格式,传递给脚本的内部的 sys.argv list
里面的对象到底是 str还是unicode? 每一个需不需要编解码? 是否要先判断类型再进行确定编解码操作?
这样完全违背了Python的精神啊。。。
妈蛋,为了让自动生成的博客标题中 也就是上面的 title field能够支持中文。也是折腾了半天,最后终于在被 str和unicode烦够了之后走向了
Python3K的怀抱。。以后写 print 都需要加括号了!!
|
C++ | UTF-8 | 3,126 | 2.890625 | 3 | [] | no_license | #pragma once
#ifndef APPLICATION_H_
#define APPLICATION_H_
#include <exception>
#include <memory>
#include <vector>
#include <string>
#include <SDL.h>
#include <SDL_ttf.h>
#include <GL/glew.h>
#include <AL/al.h>
#include <AL/alc.h>
#include "Physics.h"
#include "UiSystem.h"
namespace myengine
{
class Camera;
class ResourceManager;
class PhysicsWorld;
class Screen;
class Entity;
class Shader;
/**
*Setups the engine for use in simulations or games.
*/
class Application
{
private:
Application();
/**
*Stores a pointer to the current audio device.
*/
ALCdevice* audioDevice;
/**
*Stores a pointer to the current audio context.
*/
ALCcontext* audioContext;
/**
*Stores the physics settings for use in the bullet library.
*/
std::shared_ptr<PhysicsWorld> physicsWorld;
/**
*Stores a list of the current entities in the scene.
*/
std::vector<std::shared_ptr<Entity>> entities;
/**
*Stores a list of UIs
*/
std::vector<std::shared_ptr<UiSystem>> uis;
/**
*Stores a weak pointer to itself.
*/
std::weak_ptr<Application> self;
/**
*Stores the resource manager.
*/
std::shared_ptr<ResourceManager> resources;
/**
*Stores information about the screen.
*/
std::shared_ptr<Screen> screen;
/**
*Stores a pointer to the application window.
*/
SDL_Window* window;
/**
*Determines whether the main engine loop should run.
*/
bool loop = true;
/**
*Updates the screen size.
*/
void UpdateScreenSize();
public:
/**
*Stores the current framerate.
*/
double frameRate;
std::shared_ptr<Shader> standardShader;
std::shared_ptr<Shader> uiShader;
/**
*Initializes the engine, starting required libraries, and making a window.
*/
static std::shared_ptr<Application> Initialise(std::string windowName);
/**
*Starts the main engine loop.
*/
void MainLoop();
/**
*Returns a shared pointer to the screen object.
*/
std::shared_ptr<Screen> GetScreen();
/**
*Returns a shared pointer to the resource manager.
*/
std::shared_ptr<ResourceManager> GetResources();
/**
*Creates an entity and stores it in the entity list. Returns the created entity as a shared pointer.
*/
std::shared_ptr<Entity> AddEntity();
/**
*Returns the physics world.
*/
std::shared_ptr<PhysicsWorld> GetPhysicsWorld();
/**
*Stores the main camera.
*/
std::shared_ptr<Camera> camera;
/**
*Tells the engine what to use as the main camera.
*/
void AddCamera(std::shared_ptr<Camera> cam);
/**
*Creates, initializes and adds a UI to the application.
*/
template<typename T>
std::shared_ptr<T> BindUI()
{
std::shared_ptr<T> ui = std::make_shared<T>();
ui->InitializeUI();
ui->application = self;
ui->self = ui;
uis.push_back(ui);
return ui;
}
template<typename T>
std::shared_ptr<T> GetUI()
{
for (size_t ui = 0; ui < uis.size(); ui++)
{
std::shared_ptr<T> rtn = std::dynamic_pointer_cast(uis.at(ui));
if (rtn)
{
return rtn;
}
}
std::cout << "Could not find UI of type!" << std::endl;
throw std::exception();
}
};
}
#endif |
C++ | UTF-8 | 1,181 | 3.296875 | 3 | [] | no_license | /**********************************************
* Lab 10
* Your name goes here
**********************************************/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include "Tree.h"
/**********************************************
* main
**********************************************/
void main()
{ int pos;
string fname,s;
fstream infile;
tree t;
// Open file
cout << "Enter file name: ";
cin >> fname;
infile.open(fname.data(),ios::in);
// Loop through file
while(!infile.eof())
{ infile >> s;
if(infile.good()) t.insert(s);
};
// Close file
infile.close();
// Display tree dump
/*
cout << "Depth = " << t.depth() << endl << endl;
t.dump();
cout << endl;
*/
/* STEP 3
// Display tree in LMR order
t.show("LMR");
cout << endl;
*/
/* STEP 6
// Display tree in order
cout << "Enter display order (LMR,RML,MLR): ";
cin >> s;
t.show(s);
cout << endl;
*/
// STEP 8
// Find
cout << "Enter string to find: ";
cin >> s;
pos = t.find(s);
if(pos!=TREE_ERR)
cout << s << " found at position " << pos << endl;
else
cout << s << " not found" << endl;
}
|
C++ | UTF-8 | 263 | 2.53125 | 3 | [] | no_license | #include "counting_id_generator.hpp"
BEGIN_NAMESPACE_CORE
counting_id_generator::counting_id_generator(std::size_t prev_id)
: m_last_assigned_id(prev_id)
{
}
std::size_t counting_id_generator::operator()() { return ++m_last_assigned_id; }
END_NAMESPACE_CORE
|
JavaScript | UTF-8 | 2,484 | 2.796875 | 3 | [] | no_license | /**
*
*/
let sendbutton = document.getElementById('WeightButton');
sendbutton.addEventListener("click",(e)=>{
e.preventDefault();
let weight = document.getElementById('weight').value;
let height = document.getElementById('height').value;
let age = document.getElementById('age').value;
let gender = document.querySelector('input[id="gender"]:checked').value;
/*let docinput = document.querySelectorAll('input');
for(let i of docinput) {
if(i.value === "" || i.value == null){
alert(`${i.placeholder} 를 입력하여주세요`);
return;
}
}*/
let data = {weight:weight, height:height, age:age, gender:gender, user:sessionStorage.getItem("sessionNickName") == null ? "게스트":'sessionStorage.getItem("sessionNickName")'}
let xhp = new XMLHttpRequest();
xhp.open("POST", "/apiWeight/insertWeight", true);
xhp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhp.send(JSON.stringify(data));
xhp.onreadystatechange = () => {
if(xhp.readyState === 4 && xhp.status === 200){
let jsonData = JSON.parse(xhp.responseText);
console.log(jsonData);
let resultboard = document.getElementById('resultBoard');
let result = "";
result += `
<div class="bmi_INFO">
<div class="bmi_INFO_Height">
<span>키</span>
<span>${jsonData.height}</span>
</div>
<div class="bmi_INFO_Weight">
<span>몸무게</span>
<span>${jsonData.weight}</span>
</div>
<div class="bmi_INFO_BMI">
<span>BMI</span>
<span>${jsonData.bmi}</span>
</div>
</div>
<div class="bmi_Result">
<div class="bmi_Result_text">결과</div>
<div id="answer" class="bmi_Result_answer">${jsonData.bmi_status}</div>
<div class="bmi_Result_comment">건강이 위험해요</div>
</div>
`;
resultboard.innerHTML = result;
resultboard.style.opacity = 1;
let answercolor;
if(data.bmi_status === "비만"){
answercolor = "#ff0000";
} else if (data.bmi_status === "과체중") {
answercolor = "#b168ee";
} else if (data.bmi_status === "정상") {
answercolor = "#5cf928";
} else if (data.bmi_status === "고도 비만") {
answercolor = "#ff2020";
} else {
answercolor = "#000000";
}
document.getElementById('answer').style.color = answercolor;
document.getElementById('WeightButton').style.pointerEvents = "none";
}
}
});
|
C++ | UTF-8 | 1,618 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
using namespace std;
unsigned long long int getBits(int num);
int getDateToBits(int date, int month, int year);
int getDateToInt(int binary);
int main()
{
int year;
int month;
int date;
cout << "Enter a date DD: " << endl;
cin >> date;
if (date > 31) {
return 1;
}
cout << "Enter a month MM: " << endl;
cin >> month;
if (month > 12) {
return 1;
}
cout << "Enter a year YYYY: " << endl;
cin >> year;
if (year > 2047) {
return 1;
}
cout << endl;
int binary = getDateToBits(date, month, year);
cout << "Packed date is: " << binary << endl;
cout << endl;
int decimal = getDateToInt(binary);
_getch();
return 0;
}
unsigned long long int getBits(int num) {
unsigned long long int shift = 1;
unsigned long long int result = 0;
while (num) {
result = result + shift * (num % 2);
num = num / 2;
shift = shift * 10;
}
return result;
}
int getDateToBits(int date, int month, int year) {
int binary = date;
cout << getBits(binary) << endl;
binary = binary << 4;
cout << getBits(binary) << endl;
binary = binary + month;
cout << getBits(binary) << endl;
binary = binary << 11;
cout << getBits(binary) << endl;
binary = binary + year;
cout << getBits(binary) << endl;
cout << endl;
return binary;
}
int getDateToInt(int binary) {
int year = binary & 2047;
cout << year << endl;
binary = binary >> 11;
int month = binary & 15;
cout << month << endl;
int day = binary >> 4;
cout << day << endl;
return 0;
}
|
C# | UTF-8 | 1,440 | 2.703125 | 3 | [] | no_license | using Pin80Server.Models.JSONSerializer;
namespace Pin80Server.Models.Effects
{
public class SetEffect : Effect
{
public SetEffect(EffectSerializer effect) : base(effect) { }
public override bool Tick(EffectInstance triggeredAction, long ts)
{
var ledTarget = (LEDTarget)triggeredAction.target;
int value = triggeredAction.triggeredValue == "1" ? 1 : 0;
bool runAgain = true;
triggeredAction.state.TryGetValue(Constants.STEP, out int step);
switch (step)
{
case 0:
triggeredAction.nextUpdate = ts + delay; // This makes a very small delay, we could skip this if there is no delay
break;
case 1:
ledTarget.updatePortValue(value);
runAgain = false;
break;
}
triggeredAction.state[Constants.STEP] = step + 1;
return runAgain;
}
public override string ToString()
{
if (name != null)
{
return name;
}
string timeStr = timeString(duration);
string str = string.Format("Set Value", timeStr);
if (delay > 0)
{
str += string.Format(" w/ {0} delay", timeString(delay));
}
return str;
}
}
}
|
Python | UTF-8 | 923 | 2.5625 | 3 | [] | no_license | import os
import codecs
import operator
import numpy as np
import csv
# read data
# filename1 = os.path.join(os.path.dirname(__file__), 'all_data.csv')
filename1 = os.path.join(os.path.dirname(__file__), 'all_data.csv')
#f1 = codecs.open( filename1, "r", "utf-8")
#filename2 = os.path.join(os.path.dirname(__file__), 'table_1.csv')
filename2 = os.path.join(os.path.dirname(__file__), 'TABLE_ALL_1.csv')
f2 = codecs.open( filename2, "r", "utf-8")
n = 2646
arr = np.empty((n, 2))
for line in f2:
i = 0
line = line.split(',')
f1 = codecs.open( filename1, "r", "utf-8")
for arg in f1:
arg = arg.split(',')
if line[0] == arg[0]:
arr[i][0] = int(line[1])
if line[0] == arg[1]:
arr[i][1] = int(line[1])
i += 1
f1.close
np.savetxt('input.csv', arr,fmt="%d", delimiter=' ')
#j=0
#while (j<n):
# print(arr[j][0], ": ", arr[j][1])
# j += 1
|
SQL | UTF-8 | 387 | 3.5 | 4 | [
"MIT"
] | permissive | CREATE TABLE core.mno_prefixes
(
id serial NOT NULL,
mno_id integer NOT NULL,
prefix character varying(16) NOT NULL,
CONSTRAINT mno_prefixes_pkey PRIMARY KEY (id),
CONSTRAINT mno_prefixes_mno_id_fkey FOREIGN KEY (mno_id)
REFERENCES core.mno (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
);
COMMENT ON TABLE core.mno_prefixes IS 'MSISDN prefixes for MNOs';
|
C++ | UTF-8 | 6,036 | 3 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<ASU_tools.hpp>
/*****************************************************************
* This C++ function use "points_in_polygon.fun.c" from ASU_tools
* to combine several polygons into another set of polygons.(The
* union sets of given polygons)
*
* vector<vector<pair<double,double>>> &P ---- Input polygons.
*
* Each polygon is denoted by a vecotr of pairs of coordinates (x,y).
*
* Return value.
* vector<vector<pair<double,double>>> Ans ---- Output polygons.
*
* Shule Yu
* Mar 14 2017
*
* Key words: polygon, union set.
*****************************************************************/
double CalcDist(std::pair<double,double> p1,std::pair<double,double> p2){
return sqrt(pow(p1.first-p2.first,2)+pow(p1.second-p2.second,2));
}
bool CombineTwoPolygons(std::vector<std::pair<double,double>> All,std::vector<std::pair<double,double>> New){
auto res=PointsInPolygon(All,New);
auto res2=PointsInPolygon(New,All);
int m=All.size(),n=New.size();
int nn=std::count(res.begin(),res.end(),true);
int mm=std::count(res2.begin(),res2.end(),true);
// One of the polygon contains another.
if (nn==n) return true;
if (mm==m){
All=New;
return true;
}
// Two polygons are seperated.
if (mm==0 || nn==0) return false;
// Find the new begin/end points in All.
bool flag=false;
std::vector<int> NB_All,NE_All;
for (int i=0;i<m;i++){
if (res2[i] && !res2[(i+1)%m]){
NB_All.push_back((i+1)%m);
}
if (!res2[i] && res2[(i+1)%m]){
NE_All.push_back(i);
}
if (NB_All.size()==0 && NE_All.size()==1) flag=true;
}
if (flag) rotate(NE_All.begin(),NE_All.begin()+1,NE_All.end());
// Find the new begin/end points in New.
flag=false;
std::vector<int> NB_New,NE_New;
for (int i=0;i<n;i++){
if (res[i] && !res[(i+1)%n]){
NB_New.push_back((i+1)%n);
}
if (!res[i] && res[(i+1)%n]){
NE_New.push_back(i);
}
if (NB_New.size()==0 && NE_New.size()==1) flag=true;
}
if (flag) rotate(NE_New.begin(),NE_New.begin()+1,NE_New.end());
// Bug ! Bug ! .... Pia ! Pia !
// ignore small sections.
int n1=NB_All.size(),n2=NB_New.size();
if (n1!=n2){
for (int i=n1-1;i>=0;i--){
int x=NE_All[i]-NB_All[i];
if (x<0) x+=All.size();
if (x<3){
NB_All.erase(NB_All.begin()+i);
NE_All.erase(NE_All.begin()+i);
}
}
for (int i=n2-1;i>=0;i--){
int x=NE_New[i]-NB_New[i];
if (x<0) x+=New.size();
if (x<3){
NB_New.erase(NB_New.begin()+i);
NE_New.erase(NE_New.begin()+i);
}
}
}
// Bug bug.. buzz..buzz... pia !
n1=NB_All.size(),n2=NB_New.size();
if (n1!=n2){
std::vector<int> &p=(n1>n2?NB_All:NB_New);
std::vector<int> &p2=(n1>n2?NE_All:NE_New);
std::vector<std::pair<double,double>> &P=(n1>n2?All:New);
int Diff=abs(n1-n2),N=(n1>n2?m:n);
rotate(p2.begin(),p2.end()-1,p2.end());
std::vector<std::pair<int,int>> pp;
for (size_t i=0;i<p.size();i++){
pp.push_back({p[i]-p2[i],i});
if (pp.back().first<0) pp.back().first+=N;
}
sort(pp.begin(),pp.end());
std::vector<int> t;
for (int i=0;i<Diff;i++){
t.push_back(pp[i].second);
}
sort(t.begin(),t.end(),std::greater<int>());
for (auto item: t){
for(size_t i=p2[item]+1;i<(p[item]<p2[item]?(p[item]+P.size()):p[item]);i++){
int xx=(i>=P.size()?i-P.size():i);
P[xx].first=std::numeric_limits<double>::quiet_NaN();
}
p.erase(p.begin()+item);
p2.erase(p2.begin()+item);
}
rotate(p2.begin(),p2.begin()+1,p2.end());
}
// Find where these two shape meet.
int N=NB_All.size();
std::vector<int> X(N),Y(N);
for (int i=0;i<N;i++){
double MinDist=std::numeric_limits<double>::max();
double MinDist2=std::numeric_limits<double>::max();
for (int j=0;j<N;j++){
double dist=CalcDist(All[NE_All[i]],New[NB_New[j]]);
if (MinDist>dist){
MinDist=dist;
X[i]=j;
}
double dist2=CalcDist(New[NE_New[i]],All[NB_All[j]]);
if (MinDist2>dist2){
MinDist2=dist2;
Y[i]=j;
}
}
}
/**************
// Method 1. Create new polygon.
std::vector<std::pair<double,double>> All_New;
for (int PB=0;PB<N;PB++){
for (int i=0;i<m;i++){
int xx=(NB_All[PB]+i)%m;
if (!std::isnan(All[xx].first)) All_New.push_back(All[xx]);
if (xx==NE_All[PB]) break;
}
for (int i=0;i<n;i++){
int xx=(NB_New[X[PB]]+i)%n;
if (!std::isnan(New[xx].first)) All_New.push_back(New[xx]);
if (xx==NE_New[X[PB]]) break;
}
}
All=All_New;
******************/
// /**************
// Method 2.
// For Non-simply connected result.
// we ignore the center parts.
std::vector<std::vector<std::pair<double,double>>> Polygons;
std::vector<bool> pPB(N);
decltype(pPB.begin()) it;
while((it=find(pPB.begin(),pPB.end(),false))!=pPB.end()){
int PB=(it-pPB.begin());
std::vector<std::pair<double,double>> All_New;
while(!pPB[PB]){
pPB[PB]=true;
for (int i=0;i<m;i++){
int xx=(NB_All[PB]+i)%m;
if (!std::isnan(All[xx].first)) All_New.push_back(All[xx]);
if (xx==NE_All[PB]) break;
}
for (int i=0;i<n;i++){
int xx=(NB_New[X[PB]]+i)%n;
if (!std::isnan(New[xx].first)) All_New.push_back(New[xx]);
if (xx==NE_New[X[PB]]) break;
}
PB=Y[X[PB]];
}
Polygons.push_back(All_New);
}
size_t MaxL=Polygons[0].size(),j=0;
for (size_t i=1;i<Polygons.size();i++){
if (MaxL<Polygons[i].size()){
MaxL=Polygons[i].size();
j=i;
}
}
All=Polygons[j];
// ******************/
return true;
}
std::vector<std::vector<std::pair<double,double>>> CombinePolygons(const std::vector<std::vector<std::pair<double,double>>> &P){
std::vector<std::vector<std::pair<double,double>>> ans;
int NP=P.size();
std::vector<bool> V(NP);
for (int i=0;i<NP;i++){
if (V[i]) continue;
V[i]=true;
std::vector<std::pair<double,double>> CurP=P[i];
int Cnt=0,Cnt_Prev=-1;
while (Cnt!=Cnt_Prev){
Cnt_Prev=Cnt;
for (int j=0;j<NP;j++){
if (V[j]) continue;
V[j]=CombineTwoPolygons(CurP,P[j]);
if (V[j]) Cnt++;
}
}
ans.push_back(CurP);
}
return ans;
}
|
Markdown | UTF-8 | 503 | 2.59375 | 3 | [] | no_license | In Lesson 5 of the [Self Driving Car Nanodegree](https://www.udacity.com/course/self-driving-car-engineer-nanodegree--nd013) offered by Udacity, you create, piece by piece, a library called MiniFlow. The library is a core component recreation of some aspects of Tensorflow in order to learn key concepts via 1st principles.
While this is done in the browser, I followed along and create the library in my chosen IDE in order to create a good study material and play around with the library further.
|
C++ | UTF-8 | 855 | 2.5625 | 3 | [] | no_license | #ifndef _CLEVELTRANSITION_H_
#define _CLEVELTRANSITION_H_
#include "CStaticObject.h"
#include "CStateMgr.h"
class CLevelTransition : public CStaticObject
{
private :
CStateMgr::StateList m_eStateToChange;
SDL_Rect m_DrawingRect;
bool m_bTransitStart;
double m_dTransitTime;
double m_dMaxTransitTime;
float m_fColPos;
public:
CLevelTransition();
CLevelTransition(int iXpos, int iYpos);
CLevelTransition(const CLevelTransition & copy) {}
CLevelTransition& operator=(const CLevelTransition & copy) {}
virtual ~CLevelTransition() {}
virtual bool Init();
virtual void Update(double dDt);
virtual void Render(SDL_Renderer* pRenderer);
virtual void Shutdown();
public :
void SetStateToChange(CStateMgr::StateList eStateToChange) { m_eStateToChange = eStateToChange; }
bool GetIsTransitStart() const { return m_bTransitStart; }
};
#endif |
Python | UTF-8 | 4,317 | 2.734375 | 3 | [] | no_license | # python libraties
import os, cv2
import numpy as np
from PIL import Image
# pytorch libraries
import torch
from torch import nn
from torch.autograd import Variable
from torchvision import models,transforms
def set_parameter_requires_grad(model, feature_extracting):
if feature_extracting:
for param in model.parameters():
param.requires_grad = False
def initialize_model(model_name, num_classes, feature_extract, use_pretrained=True):
# Initialize these variables which will be set in this if statement. Each of these
# variables is model specific.
model_ft = None
input_size = 0
if model_name == "resnet":
""" Resnet18, resnet34, resnet50, resnet101
"""
model_ft = models.resnet50(pretrained=use_pretrained)
set_parameter_requires_grad(model_ft, feature_extract)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, num_classes)
input_size = 224
elif model_name == "vgg":
""" VGG11_bn
"""
model_ft = models.vgg11_bn(pretrained=use_pretrained)
set_parameter_requires_grad(model_ft, feature_extract)
num_ftrs = model_ft.classifier[6].in_features
model_ft.classifier[6] = nn.Linear(num_ftrs,num_classes)
input_size = 224
elif model_name == "densenet":
""" Densenet121
"""
model_ft = models.densenet121(pretrained=use_pretrained)
set_parameter_requires_grad(model_ft, feature_extract)
num_ftrs = model_ft.classifier.in_features
model_ft.classifier = nn.Linear(num_ftrs, num_classes)
input_size = 224
elif model_name == "inception":
""" Inception v3
Be careful, expects (299,299) sized images and has auxiliary output
"""
model_ft = models.inception_v3(pretrained=use_pretrained)
set_parameter_requires_grad(model_ft, feature_extract)
# Handle the auxilary net
num_ftrs = model_ft.AuxLogits.fc.in_features
model_ft.AuxLogits.fc = nn.Linear(num_ftrs, num_classes)
# Handle the primary net
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs,num_classes)
input_size = 299
else:
print("Invalid model name, exiting...")
exit()
return model_ft, input_size
def choose_model(model_name):
# resnet,vgg,densenet,inception
model_name = model_name
num_classes = 7
feature_extract = False
# Initialize the model for this run
model_ft,input_size = initialize_model(model_name, num_classes, feature_extract, use_pretrained=True)
# Define the device:
device = torch.device('cuda:0')
# Put the model on the device:
model = model_ft.to(device)
current_path = os.path.dirname(__file__)
model.load_state_dict(torch.load(os.path.join(current_path,'skin_lesion')))
model.eval()
return model,input_size,device
def compute_img_mean_std(image):
img_h, img_w = 224, 224
img = cv2.imdecode(np.fromstring(image.read(), np.uint8), cv2.IMREAD_UNCHANGED)
img = cv2.resize(img, (img_h, img_w))
img = img.astype(np.float32) / 255.
pixels = img.ravel() # resize to one row
mean=np.mean(pixels)
stdev=np.std(pixels)
print("normMean = {}".format(mean))
print("normStd = {}".format(stdev))
return mean,stdev
def predict(img,model,input_size,device):
norm_mean,norm_std = compute_img_mean_std(img)
transform = transforms.Compose(
[transforms.Resize((input_size,input_size)),transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),transforms.RandomRotation(20),
transforms.ColorJitter(brightness=0.1, contrast=0.1, hue=0.1),
transforms.ToTensor(), transforms.Normalize(norm_mean, norm_std)]
)
image=Image.open(img)
image = transform(image)
with torch.no_grad():
image = Variable(image).to(device)
image = image.unsqueeze(0)
outputs = model(image)
prediction = outputs.max(1, keepdim=True)[1]
return int(prediction[0][0]) |
Markdown | UTF-8 | 1,057 | 2.859375 | 3 | [] | no_license | ## Table of Contents
- [What is Snapwhyb](#what-is-snapwhyb)
- [Features](#features)
## What is Snapwhyb
Snapwhyb is acronym for Snap - Where have you been
Take a photo using the app. It suggests your current location and you
write your thoughts about the photo. Photos are stored locally on the phone.
## Features
- Use phone camera to take a picture and store in device
- Use Google APIs - location service, geocode service and places service
to suggest current location
- Write and edit a story for each picture
<img src="https://s3-ap-southeast-1.amazonaws.com/khoo0030-storage/github/android-snapwhyb-native/photo-app-1.jpg" width="45%"></img>
<img src="https://s3-ap-southeast-1.amazonaws.com/khoo0030-storage/github/android-snapwhyb-native/photo-app-2.jpg" width="45%"></img>
<img src="https://s3-ap-southeast-1.amazonaws.com/khoo0030-storage/github/android-snapwhyb-native/photo-app-3.jpg" width="45%"></img>
<img src="https://s3-ap-southeast-1.amazonaws.com/khoo0030-storage/github/android-snapwhyb-native/photo-app-4.jpg" width="45%"></img>
|
Java | UTF-8 | 703 | 2.015625 | 2 | [] | no_license | package be.rochus.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import be.rochus.domain.Schutter;
public interface SchutterRepository extends JpaRepository<Schutter, Long> {
@Query("FROM Schutter ORDER BY joinYear ASC")
List<Schutter> findSchutters();
@Query("FROM Schutter WHERE active=1 ORDER BY joinYear ASC")
List<Schutter> findActive();
@Query("FROM Schutter WHERE male=:male AND active=1 ORDER BY joinYear ASC")
List<Schutter> findMaleOrFemale(@Param("male") boolean male);
Schutter findByUrlTitle(String urlTitle);
}
|
Java | UTF-8 | 952 | 2.15625 | 2 | [] | no_license | package com.xz.netty.demo.cspecial.client;
import com.xz.netty.demo.cspecial.SpecialDelimiter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
/**
* Created by xz on 2020/1/25.
*/
public class SpecialClientChannelInit extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ByteBuf byteBuf = Unpooled.copiedBuffer(SpecialDelimiter.delimiter.getBytes());
socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new SpecialClientHandle("hello"));
}
}
|
Markdown | UTF-8 | 738 | 2.609375 | 3 | [] | no_license | 1. 调用queryPage接口可以查询数据库app_timeline中的任何数据。
2. 查询语句:(Ok)
'''
select date from app_timeline
'''
3. 插入语句:
```
INSERT INTO app_timeline
(date,subject,title,content,author,flag,url)
VALUES
("2017-12-03","美团1","爬虫","你好,异常!","刘先锋",1,'');
```
4. 更新语句:(always Ok)
```
UPDATE app_timeline SET content="我爱学习"
WHERE id=1;
```
5. 删除语句:(need refreash page Ok)
```
DELETE FROM app_timeline
WHERE author="刘先锋";
```
思路:
1. 首先获取所有的记录,渲染页面。
2. 获取所有的date,赋值给timelineMap数组(去重)。
3. CRUD调用接口queryPage操作。
4. 筛选查询,where调用接口queryPage操作。
|
JavaScript | UTF-8 | 12,133 | 2.625 | 3 | [] | no_license | const SHA256 = require('crypto-js/sha256');
const Blockchain = require('./simpleChain.js').Blockchain;
const Block = require('./simpleChain.js');
const BitcoinMessage = require('bitcoinjs-message');
const message_star = 'starRegistry';
/**
* Controller Definition to encapsulate routes to work with blocks
*/
class BlockController {
/**
* Constructor to create a new BlockController, you need to initialize here all your endpoints
* @param {*} app
*/
constructor(app) {
this.app = app;
this.blocks = [];
this.blockchain = new Blockchain();
this.initializeMockData();
this.getBlockByIndex();
this.postNewBlock();
////////////validation for 5 minutes "calculation" ///////////////
this.timeoutRequestsWindowTime = 5 * 60 * 1000;
this.mempool = new Map();
this.mempoolValid = new Map();
this.timeRequests = new Map();
this.postRequestValidation();
this.postMessageSignatureValidate();
this.getStarsHash();
this.getStartsWalletAddress();
}
/**
* Implement a GET endpoint to retrieve a block by height
*/
getBlockByIndex() {
this.app.get("/block/:index", async(req, res) => {
//Get block hight "index"
let index = req.params.index;
try {
console.log(`Get block with index ${index}`);
//Get block by index
let result = await this.blockchain.getBlocksByHeight(index);
//convert the block to json format
res.json(result);
res.end();
} catch (err) {
console.log(`Error: ${err}`);
//Bad request
res.send(`Error: ${err}`);
}
});
}
/**
* Implement a POST endpoint to add a new block, url: "/block"*/
postNewBlock() {
this.app.post("/block", (req, res) => {
// check for request properties
try {
if (req.body.address && req.body.star) {
//check for address in memory pool
if (!this.mempoolValid.get(req.body.address)) {
console.log("Invlaid address in memory pool");
return;
}
let blockBody = req.body;
if (!blockBody.star.story || !blockBody.star.dec || !blockBody.star.ra) {
console.log(`Invalid request `);
return;
}
blockBody.star.story = Buffer(blockBody.star.story).toString('hex');
let block = new Block.Block(blockBody);
//add the block ti the chain
this.blockchain.addBlock(block).then(_block => {
// remove address from mempool valid
this.removeValidationRequest(req.body.address);
res.json(block);
res.end();
})
} else {
console.log(`Invalid address`);
}
} catch (err) {
console.log(`Error: ${err}`);
res.send(`Error: ${err}`);
}
});
}
// Removing Request Validation and mempool
removeValidationRequest(walletAddress) {
this.timeRequests.delete(walletAddress);
this.mempool.delete(walletAddress);
this.mempoolValid.delete(walletAddress);
}
///////////////////////
/**
* Help method to inizialized Mock dataset, adds 10 test blocks to the blocks array
*/
initializeMockData() {
if (this.blocks.length === 0) {
for (let index = 0; index < 10; index++) {
let blockAux = new Block.Block(`Test Data #${index}`);
blockAux.height = index;
blockAux.hash = SHA256(JSON.stringify(blockAux)).toString();
this.blocks.push(blockAux);
}
}
}
///////////////postRequestValidation method////////////////////
// Web API POST endpoint to validate request with JSON response.
postRequestValidation() {
this.app.post("/requestValidation", (req, res) => {
let address = req.body.address;
if (address) {
// check for timeout scope or no
if (this.timeRequests.get(address)) {
// getting validation Window after calculation
let validationWindow = this.calculateValidationWindow(req);
//check mempool
let response = this.mempool.get(address);
response.validationWindow = validationWindow;
res.json(response);
res.end();
} else {
// process a new request
this.addRequestValidation(address);
// getting validation Window after calculation
let validationWindow = this.calculateValidationWindow(req);
let response = this.getRequestObject(req, validationWindow);
// store in mempool
this.mempool.set(address, response);
res.json(response);
res.end();
}
} else {
console.log("invalid address");
}
});
}
// Implement adding request Validation
addRequestValidation(walletAddress) {
let requestTimeout = setTimeout(function() {
this.removeValidationRequest(walletAddress);
}, this.timeoutRequestsWindowTime);
this.timeRequests.set(walletAddress, requestTimeout);
}
// Implement calculate validation window .
calculateValidationWindow(request) {
let previousResponse = this.mempool.get(request.body.address);
let timeElapse = 0;
if (previousResponse) {
timeElapse = request.requestTimeStamp - previousResponse.requestTimeStamp;
} else {
timeElapse = (new Date().getTime().toString().slice(0, -3)) - request.requestTimeStamp;
}
let timeLeft = (this.timeoutRequestsWindowTime / 1000) - timeElapse;
return timeLeft;
}
//////////////////////////getRequestObject method//////////////////
getRequestObject(req, validationWindow) {
let requestObject = { walletAddress: "", requestTimeStamp: "", message: "", validationWindow: "" };
requestObject.walletAddress = req.body.address;
requestObject.requestTimeStamp = req.requestTimeStamp;
///set massage
requestObject.message = requestObject.walletAddress + ':' + req.requestTimeStamp + ':' + message_star;
requestObject.validationWindow = validationWindow;
return requestObject;
}
/**
* Implement /message-signature/validate API to validate the given signature with address wallet by bitcoin library
*/
postMessageSignatureValidate() {
this.app.post('/message-signature/validate', (req, res) => {
let address = req.body.address;
let signature = req.body.signature;
let body = req.body;
if (address && signature) {
// verify window time
if (this.verifyWidnowTime(body)) {
console.log("Expired Window Time ");
}
// verify whether it exists in the memroy pool , otherwise throws error msg.
let memPoolData = this.mempool.get(address);
if (!memPoolData) {
console.log("Invalid address wallet in memory pool");
}
// verify the signature must check
let isSignatureValid = this.verifySignature(body);
let validationWindows = this.calculateValidationWindow(req);
let validRequest = this.createValidRequest(true, memPoolData, validationWindows, isSignatureValid);
// save it if it is signature valid.
console.log("isSignatureValid " + isSignatureValid);
if (isSignatureValid) {
this.mempoolValid.set(address, validRequest);
}
res.json(validRequest);
} else {
console.log("Invalid address or signature");
res.send("Invalid address or signature ");
res.end()
}
});
}
// verify the address for window time
verifyWidnowTime(req) {
if (req.address) {
return true;
} else {
return false;
}
}
// verify the signature based on the given address and signature
verifySignature(req) {
let memPool = this.mempool.get(req.address);
let response = BitcoinMessage.verify(memPool.message, req.address, req.signature);
return response;
}
/////////createValidRequest method ////////////////
createValidRequest(RegisterStart, poolData, validationWindows, isValid) {
let RequestObject = {};
RequestObject.registerStar = RegisterStart;
RequestObject.status = {};
RequestObject.status.address = poolData.walletAddress;
RequestObject.status.requestTimeStamp = poolData.requestTimeStamp;
RequestObject.status.message = poolData.message;
RequestObject.status.validationWindow = validationWindows;
RequestObject.status.messageSignature = isValid;
return RequestObject;
}
///Get the block using the provided hash
getStarsHash() {
this.app.get("/stars/hash::hashdata", async(req, res) => {
//Get block hash
let hashdata = req.params.hashdata;
try {
console.log(`Get block with hashdata ${hashdata}`);
//Get block by hash
let result = await this.blockchain.getBlockByHash(hashdata);
// console.log(`result: ${result}`);
//convert the block to json format
res.json(result);
res.end();
} catch (err) {
console.log(`Error: ${err}`);
}
});
}
/**
* Implement starts by address
*/
getStartsWalletAddress() {
this.app.get("/stars/address::addressdata", async(req, res) => {
//Get block address
let addressdata = req.params.addressdata;
try {
console.log(`Get block with addressdata ${addressdata}`);
//Get block by address
let result = await this.blockchain.getBlocksByAddress(addressdata);
// console.log(`result: ${result}`);
//convert the block to json format
res.json(result);
res.end();
} catch (err) {
console.log(`Error: ${err}`);
}
});
}
//////////////
}
/**
* Exporting the BlockController class
* @param {*} app
*/
module.exports = (app) => { return new BlockController(app); } |
C++ | UTF-8 | 496 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include "tree.h"
static void test_tree()
{
int a[] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int* preorder = a;
int b[] = { 4, 7, 2, 1, 5, 3, 8, 6 };
int* inorder = b;
int c[] = { 7, 4, 2, 5, 8, 6, 3, 1 };
int* postorder = c;
BinaryTreeNode* tree = ConstructInPost(inorder, postorder, 8);
PreorderTraversal(tree);
std::cout << std::endl;
InorderTraversal(tree);
std::cout << std::endl;
PostorderTraversal(tree);
std::cout << std::endl;
std::cout << GetNext(tree)->value;
}
|
Java | UTF-8 | 2,737 | 2.21875 | 2 | [] | no_license | /**
* @author pulem3t
*/
package org.pulem3t.crm.entry;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "COMPANIES")
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ID")
private Long id;
@Column(name = "NAME")
private String name;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "VENDOR_ID")
private Long vendorId;
@Column(name = "CREATION_DATE")
private Date creationDate;
@Column(name = "ADDRESS")
private String address;
@Column(name = "PHONE")
private String phone;
@Column(name = "FAX")
private String fax;
@Column(name = "COUNTRY")
private String country;
@Column(name = "CITY")
private String city;
@Column(name = "STATE")
private String state;
@Column(name = "ZIP_POST_CODE")
private String zipPostCode;
@Column(name = "CATEGORY")
private String category;
public Company() {
this.id = System.currentTimeMillis();
this.creationDate = new Date();
}
public Company(String name) {
this.id = System.currentTimeMillis();
this.name = name;
this.creationDate = new Date();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getVendorId() {
return vendorId;
}
public void setVendorId(Long vendorId) {
this.vendorId = vendorId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipPostCode() {
return zipPostCode;
}
public void setZipPostCode(String zipPostCode) {
this.zipPostCode = zipPostCode;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Long getId() {
return id;
}
public Date getCreationDate() {
return creationDate;
}
}
|
C | UTF-8 | 437 | 3.703125 | 4 | [] | no_license | /* dez2bin.c */
#include <stdio.h>
#include <stdlib.h>
#define ulong unsigned long
void dez2bin(ulong dez) {
if(dez) {
dez2bin(dez / 2);
printf("%lu", dez % 2);
}
}
int main(void) {
ulong dezimal;
printf("Dezimalzahl in Dualzahl konvertieren\n");
printf("Welche Zahl : ");
scanf("%lu",&dezimal);
printf("Dezimal = %lu Dual = ",dezimal);
dez2bin(dezimal);
printf("\n");
return EXIT_SUCCESS;
}
|
Java | UTF-8 | 1,497 | 2.6875 | 3 | [] | no_license | package ru.snchz29.dao;
import lombok.extern.java.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import static java.sql.Connection.TRANSACTION_READ_COMMITTED;
@Log
public class DataBaseConnection {
private Connection connection;
public void openConnection() throws SQLException {
log.info("Connection open");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Properties props = new Properties();
props.setProperty("user", "postgres");
props.setProperty("password", "1234");
connection = DriverManager.getConnection("jdbc:postgresql://192.168.100.10:5432/andersen_hw2", props);
if (connection.getMetaData().supportsTransactionIsolationLevel(TRANSACTION_READ_COMMITTED)) {
connection.setTransactionIsolation(TRANSACTION_READ_COMMITTED);
}
}
public PreparedStatement prepareStatement(String SQL) throws SQLException {
if (isClosed()) {
openConnection();
}
return connection.prepareStatement(SQL);
}
public boolean isClosed() throws SQLException {
return connection == null || connection.isClosed();
}
public void closeConnection() throws SQLException {
log.info("Connection close");
connection.close();
}
}
|
SQL | UTF-8 | 855 | 3.875 | 4 | [] | no_license | CREATE TABLE IF NOT EXISTS redes_sociais(
id BIGSERIAL PRIMARY KEY,
nome VARCHAR(50) NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS enderecos(
id BIGSERIAL PRIMARY KEY,
rua VARCHAR NOT NULL,
pais VARCHAR(100) NOT NULL,
cidade VARCHAR(100) NOT NULL
);
CREATE TABLE IF NOT EXISTS usuarios(
id BIGSERIAL PRIMARY KEY,
nome VARCHAR(100),
email VARCHAR NOT NULL UNIQUE,
senha VARCHAR NOT NULL,
endereco_id INTEGER NOT NULL,
FOREIGN KEY (endereco_id) REFERENCES enderecos (id)
);
CREATE TABLE IF NOT EXISTS usuario_rede_sociais(
id BIGSERIAL PRIMARY KEY,
usuario_id INTEGER NOT NULL,
rede_social_id INTEGER NOT NULL,
FOREIGN KEY (usuario_id) REFERENCES usuarios (id),
FOREIGN KEY (rede_social_id) REFERENCES redes_sociais (id)
); |
C# | UTF-8 | 2,532 | 2.671875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShowScaffolding.Models;
namespace ShowScaffolding.Controllers
{
public class MoviesController : Controller
{
private readonly IMovieRepository movieRepository;
// If you are using Dependency Injection, you can delete the following constructor
public MoviesController() : this(new MovieRepository())
{
}
public MoviesController(IMovieRepository movieRepository)
{
this.movieRepository = movieRepository;
}
//
// GET: /Movies/
public ViewResult Index()
{
return View(movieRepository.All);
}
//
// GET: /Movies/Details/5
public ViewResult Details(long id)
{
return View(movieRepository.Find(id));
}
//
// GET: /Movies/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Movies/Create
[HttpPost]
public ActionResult Create(Movie movie)
{
if (ModelState.IsValid) {
movieRepository.InsertOrUpdate(movie);
movieRepository.Save();
return RedirectToAction("Index");
} else {
return View();
}
}
//
// GET: /Movies/Edit/5
public ActionResult Edit(long id)
{
return View(movieRepository.Find(id));
}
//
// POST: /Movies/Edit/5
[HttpPost]
public ActionResult Edit(Movie movie)
{
if (ModelState.IsValid) {
movieRepository.InsertOrUpdate(movie);
movieRepository.Save();
return RedirectToAction("Index");
} else {
return View();
}
}
//
// GET: /Movies/Delete/5
public ActionResult Delete(long id)
{
return View(movieRepository.Find(id));
}
//
// POST: /Movies/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(long id)
{
movieRepository.Delete(id);
movieRepository.Save();
return RedirectToAction("Index");
}
protected override void HandleUnknownAction(string actionName) {
Response.Write("I have no idea what " + actionName + " is!");
}
}
}
|
Java | UTF-8 | 1,451 | 2.03125 | 2 | [] | no_license |
package com.ljwd.plms.web.wsdl.webservice.service;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for searchRefundApply complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="searchRefundApply">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="param" type="{http://webservice.loan.mfbms.flinkmf.com/}refundApplyParamDto" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "searchRefundApply", propOrder = {
"param"
})
public class SearchRefundApply {
protected RefundApplyParamDto param;
/**
* Gets the value of the param property.
*
* @return
* possible object is
* {@link RefundApplyParamDto }
*
*/
public RefundApplyParamDto getParam() {
return param;
}
/**
* Sets the value of the param property.
*
* @param value
* allowed object is
* {@link RefundApplyParamDto }
*
*/
public void setParam(RefundApplyParamDto value) {
this.param = value;
}
}
|
C# | UTF-8 | 1,531 | 2.640625 | 3 | [] | no_license | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using RecognitionOfPassports;
namespace WebApplication.Controllers
{
public class RecognitionController : ApiController
{
private const string TempPath = @"C:\Users\Artem\Desktop\RecognitionOfPassports1\RecognitionOfPassports\data\temp.jpg";
private const string ResultImgPath = @"C:\Users\Artem\Desktop\passp\website\public\static_content\result.jpg";
private const string RecognitionResult = @"C:\Users\Artem\Desktop\RecognitionOfPassports1\RecognitionOfPassports\data\result.txt";
[Route("api/recognizeImage"), HttpPost]
public async Task<IEnumerable<string>> Recognize()
{
var content = await Request.Content.ReadAsMultipartAsync();
var fileContent = content.Contents.First();
var stream = await fileContent.ReadAsStreamAsync();
using (var fileStream = File.Create(TempPath))
{
using (var inputStream = stream)
{
inputStream.CopyTo(fileStream);
fileStream.Close();
inputStream.Close();
}
}
var form = new Form1();
var img = form.открытьToolStripMenuItem_Click(TempPath, RecognitionResult);
img.Save(ResultImgPath);
return File.ReadAllLines(RecognitionResult);
}
}
}
|
C++ | UTF-8 | 2,842 | 2.59375 | 3 | [] | no_license | #include "Artnet.h"
// General pointer to facilitate calling back to non-static function Artnet::on_DMX_frame()
void* pt2Object;
bool connect_wifi(void)
{
START;
char* ssid = "Trap_House";
char* password = "ThIsHoUsEisatrap72";
boolean state = true;
int i = 0;
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("Connecting to WiFi");
// Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
if (i > 40) {
state = false;
break;
}
i++;
}
if (state) {
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
else {
Serial.println("");
Serial.println("Connection failed.");
}
MEM;
END;
return state;
}
Artnet::Artnet(LED_Fixture* new_fixture, LED_Group* new_group)
:Animation(new_fixture, new_group),
send_frame(1),
previous_data_length(0)
{
START;
num_universes = (num_leds * 3) / 512 + (((num_leds * 3) % 512) ? 1 : 0);
universes_received = new bool[num_universes];
connect_wifi();
artnet.begin();
THING;
artnet.setArtDmxCallback(Artnet::on_DMX_frame_wrapper);
THING;
pt2Object = (void*) this;
END;
}
void Artnet::run()
{
START;
artnet.read();
END;
}
void Artnet::on_DMX_frame(uint16_t universe, uint16_t length, uint8_t sequence, uint8_t* data)
{
START;
//for (int i = 0; i < length / 3; i++)
//{
// //int led = i + (universe - startUniverse) * (previousDataLength / 3);
// if (i < 144)
// {
// leds[i + universe * 144] = CRGB(data[i * 3], data[i * 3 + 1], data[i * 3 + 2]);
// }
//}
send_frame = 1;
// set brightness of the whole strip
if (universe == 15)
{
FastLED.setBrightness(data[0]);
//FastLED.show();
//FastLED_Show_ESP32();
}
// Store which universe has got in
if ((universe - start_universe) < num_universes) {
universes_received[universe - start_universe] = 1;
}
for (int i = 0; i < num_universes; i++)
{
if (universes_received[i] == 0)
{
//Serial.println("Broke");
send_frame = 0;
break;
}
}
// read universe and put into the right part of the display buffer
for (int i = 0; i < length / 3; i++)
{
int led = i + (universe - start_universe) * (previous_data_length / 3);
if (led < num_leds)
leds[led] = CRGB(data[i * 3], data[i * 3 + 1], data[i * 3 + 2]);
}
previous_data_length = length;
if (send_frame)
{
//FastLED.show();
//FastLED_Show_ESP32();
// Reset universeReceived to 0
memset(universes_received, 0, num_universes);
}
END;
}
void Artnet::on_DMX_frame_wrapper(uint16_t universe, uint16_t length, uint8_t sequence, uint8_t* data)
{
START;
// explicitly cast to a pointer to Classname
Artnet* mySelf = (Artnet*)pt2Object;
// call member
mySelf->on_DMX_frame(universe, length, sequence, data);
END;
} |
PHP | UTF-8 | 1,106 | 2.71875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: EPOP
* Date: 6/6/2018
* Time: 3:59 PM
*/
require_once __DIR__.'/_PDO.php';
class ModelProjectPhaseLog extends _PDO
{
function addLog($phase_id,$user_id,$message){
//connect DB
$this->connect();
$sql = "INSERT INTO b2i_project_phase_log (phase_id,user_id,message)
VALUES (:phase_id,:user_id,:message)";
$params= array(
':phase_id'=> $phase_id,
':user_id'=> $user_id,
':message'=> $message
);
$lastId = $this->insert($sql,$params);
//close DB
$this->close();
return $lastId;
}
function getLogByPhase($phase_id){
$this->connect();
$sql = "select name , surname , username , role , message ,b2i_project_phase_log.createat from b2i_project_phase_log
left join b2i_user on b2i_project_phase_log.user_id = b2i_user.id
where phase_id=:phase_id";
$params= array(':phase_id'=> $phase_id);
$result = $this->queryAll($sql,$params);
$this->close();
return $result;
}
} |
Java | UTF-8 | 4,582 | 2.125 | 2 | [] | no_license | package com.maogousoft.logisticsmobile.driver.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.maogousoft.logisticsmobile.driver.Constants;
import com.maogousoft.logisticsmobile.driver.R;
import com.maogousoft.logisticsmobile.driver.activity.home.NewSourceActivity;
import com.maogousoft.logisticsmobile.driver.activity.share.ShareActivity;
import com.maogousoft.logisticsmobile.driver.api.AjaxCallBack;
import com.maogousoft.logisticsmobile.driver.api.ApiClient;
import com.maogousoft.logisticsmobile.driver.api.ResultCode;
import com.maogousoft.logisticsmobile.driver.db.CityDBUtils;
import com.maogousoft.logisticsmobile.driver.model.NewSourceInfo;
import com.maogousoft.logisticsmobile.driver.utils.MyAlertDialog;
import com.ybxiang.driver.model.FocusLineInfo;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 关注路线的的adapter 省市区
*
* @author ybxiang
*
*/
public class FocusLineInfoListAdapter extends BaseListAdapter<FocusLineInfo> {
private CityDBUtils dbUtils;
public FocusLineInfoListAdapter(Context context) {
super(context);
dbUtils = new CityDBUtils(application.getCitySDB());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = mInflater.inflate(R.layout.listitem_focusline_info, parent, false);
holder.wayBegin = (TextView) convertView.findViewById(R.id.wayBegin);
holder.wayEnd = (TextView) convertView.findViewById(R.id.wayEnd);
holder.deleteView = convertView.findViewById(R.id.delete_btn);
} else {
holder = (Holder) convertView.getTag();
}
final FocusLineInfo focusLineInfo = mList.get(position);
holder.wayBegin.setText(dbUtils.getCityInfo(focusLineInfo.getStart_province(), focusLineInfo.getStart_city(), focusLineInfo.getStart_district()));
holder.wayEnd.setText(dbUtils.getCityInfo(focusLineInfo.getEnd_province(), focusLineInfo.getEnd_city(), focusLineInfo.getEnd_district()));
holder.deleteView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteFocusLine(focusLineInfo);
}
});
convertView.setTag(R.id.common_city_selected, focusLineInfo);
convertView.setTag(holder);
return convertView;
}
/**
* 删除已关注线路
* @param info
*/
private void deleteFocusLine(final FocusLineInfo info) {
final JSONObject jsonObject = new JSONObject();
try {
// 搜索新货源
jsonObject.put(Constants.ACTION, Constants.DELETE_ALL_FOCUS_LINE);
jsonObject.put(Constants.TOKEN, application.getToken());
jsonObject.put(Constants.JSON, new JSONObject().put("id", info.getId()).toString());
showProgress("正在删除...");
ApiClient.doWithObject(Constants.DRIVER_SERVER_URL, jsonObject,
FocusLineInfo.class, new AjaxCallBack() {
@Override
public void receive(int code, Object result) {
dismissProgress();
switch (code) {
case ResultCode.RESULT_OK:
if (result != null) {
showMsg("删除成功");
mList.remove(info);
}
notifyDataSetChanged();
case ResultCode.RESULT_ERROR:
if (result != null)
showMsg(result.toString());
break;
case ResultCode.RESULT_FAILED:
if (result != null)
showMsg(result.toString());
break;
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
class Holder {
private TextView wayBegin;
private TextView wayEnd;
private View deleteView;
}
}
|
C# | UTF-8 | 2,875 | 3.09375 | 3 | [] | no_license | // <copyright file="Url.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace WebScrapingEngine
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Encapsulates a Url.
/// </summary>
public class Url
{
/// <summary>
/// Initializes a new instance of the <see cref="Url"/> class.
/// </summary>
/// <param name="url">page url.</param>
public Url(string url)
{
this.FullUrl = url;
}
/// <summary>
/// Gets Domain name of the website.
/// </summary>
public string DomainName
{
get
{
return this.GetDomainName(this.FullUrl);
}
}
/// <summary>
/// Gets and sets Full url.
/// </summary>
public string FullUrl { get; set; }
/// <summary>
/// Gets and sets filePath.
/// </summary>
public string[] FilePath
{
get
{
return this.GetFilePath(this.FullUrl);
}
}
/// <summary>
/// Gets Query of the url.
/// </summary>
public UrlQuery Query
{
get
{
return this.GetQuery();
}
}
public bool Contains(string filePath)
{
foreach (string path in this.FilePath)
{
if (path == filePath)
{
return true;
}
}
return false;
}
private string GetDomainName(string url)
{
url = this.TrimHttps(url);
if (url.Contains('/'))
{
url = url.Substring(0, url.IndexOf('/'));
}
return url;
}
private string[] GetFilePath(string url)
{
url = this.TrimHttps(url);
url = url.Replace(this.DomainName + '/', string.Empty);
var v = url.Split('/');
if (v[v.Length - 1].Contains('?'))
{
var temp = v[v.Length - 1];
temp = temp.Substring(0, temp.IndexOf('?'));
v[v.Length - 1] = temp;
}
return v;
}
private UrlQuery GetQuery()
{
if (this.FullUrl.Contains('?'))
{
return new UrlQuery(this.FullUrl.Substring(this.FullUrl.IndexOf('?')));
}
return null;
}
private string TrimHttps(string url)
{
var trimmedString = url.Replace("https://", string.Empty);
return trimmedString;
}
}
}
|
C++ | UTF-8 | 565 | 2.9375 | 3 | [
"MIT"
] | permissive | /**
* @file
*
* $Id: Hitbox.hpp $
* @author Bill Eggert
*/
#pragma once
#include <entityx/Entity.h>
class Position;
/**
* A hitbox component. Ships, bullets, black holes have these.
*/
class Hitbox : public entityx::Component<Hitbox>
{
public:
Hitbox(
const float width,
const float height);
bool collides(
const Position &thisPos,
const Position &otherPos,
const Hitbox &otherBox) const;
float getWidth() const;
float getHeight() const;
private:
const float mWidth;
const float mHeight;
};
|
Python | UTF-8 | 5,194 | 2.96875 | 3 | [] | no_license | try:
from Tkinter import *
except ImportError:
from tkinter import *
from BaseGrid import *
import cPickle as pickle
class PLLGrid(BaseGrid):
selected_color = "light goldenrod"
def __init__(self, master):
BaseGrid.__init__(self, master)
self.selected = None
self.type = None
self.orientations = None
self.reset()
self.setOnClick(self.onObjectClick)
def onObjectClick(self, event):
for i in range(3):
for j in range(3):
if i == 1 and j == 1:
continue
if event.widget.find_closest(event.x, event.y)[0] == self.squares[i][j]:
if not self.selected:
if is_edge(i, j):
self.type = 'e'
else:
self.type = 'c'
self.setSquareColor(i, j, PLLGrid.selected_color)
self.selected = [i,j]
elif self.selected == [i,j]:
self.setSquareColor(i, j, 'yellow')
self.selected = None
self.type = None
elif is_edge(i, j) and self.type == 'e':
k, l = self.selected
self.setSquareColor(k, l, "yellow")
self.swapSquares(i, j, k, l)
self.selected = None
self.type = None
elif is_corner(i, j) and self.type == 'c':
k, l = self.selected
self.setSquareColor(k, l, "yellow")
self.swapSquares(i, j, k, l)
self.selected = None
self.type = None
else: return
def setPattern(self, pattern):
color_map = {'b':'blue',
'o':'orange',
'r':'red',
'g':'green'}
for i in range(3):
for j in range(3):
if i == 1 and j == 1:
continue
elif is_edge(i,j):
index = map_edge(j, i)
self.setEdgeColor(index, color_map[pattern[i][j]])
self.orientations[i][j] = pattern[j][i]
elif is_corner(i,j):
index = map_corner(j, i)
self.setCornerColor(index,0,color_map[pattern[i][j][0]])
self.setCornerColor(index,1,color_map[pattern[i][j][1]])
self.orientations[i][j] = pattern[j][i]
def reset(self):
self.orientations = [['bo', 'o', 'og'],
['b', None, 'g'],
['rb', 'r', 'gr']]
self.setEdgeColor(0,'orange')
self.setEdgeColor(1, 'blue')
self.setEdgeColor(2, 'green')
self.setEdgeColor(3, 'red')
self.setCornerColor(0, 0, 'blue')
self.setCornerColor(0, 1, 'orange')
self.setCornerColor(1, 0, 'orange')
self.setCornerColor(1, 1, 'green')
self.setCornerColor(2, 0, 'red')
self.setCornerColor(2, 1, 'blue')
self.setCornerColor(3, 0, 'green')
self.setCornerColor(3, 1, 'red')
if self.selected:
self.setSquareColor(self.selected[0], self.selected[1])
self.selected = None
def swapSquares(self, i, j, k, l):
# swapping orientations
temp = self.orientations[i][j]
self.orientations[i][j] = self.orientations[k][l]
self.orientations[k][l] = temp
# edge case
if is_edge(i, j) and is_edge(k, l):
id1 = self.edges[map_edge(i, j)]
id2 = self.edges[map_edge(k, l)]
color = self.itemcget(id1, "fill")
self.setEdgeColor(map_edge(i, j), self.itemcget(id2, "fill"))
self.setEdgeColor(map_edge(k, l), color)
return
# corner case
elif is_corner(i, j) and is_corner(k, l):
id11 = self.corners[map_corner(i, j)][0]
id12 = self.corners[map_corner(i, j)][1]
id21 = self.corners[map_corner(k, l)][0]
id22 = self.corners[map_corner(k, l)][1]
color1 = self.itemcget(id11, "fill")
color2 = self.itemcget(id12, "fill")
self.setCornerColor(map_corner(i, j), 0, self.itemcget(id21, "fill"))
self.setCornerColor(map_corner(i, j), 1, self.itemcget(id22, "fill"))
self.setCornerColor(map_corner(k, l), 0, color1)
self.setCornerColor(map_corner(k, l), 1, color2)
else:
print "error in PLLGrid.swapSquares"
exit()
def getValues(self):
return self.orientations
if __name__ == "__main__":
root = Tk()
grid = PLLGrid(root)
grid.pack()
with open("data/standard_PLL.p", 'rb') as f:
s = f.read()
d = pickle.loads(s)
pattern = d['Ua']
for line in pattern:
print line
#pattern = (('rb', 'b', 'gr'),
# ('r', None, 'o'),
# ('bo', 'g', 'og'))
grid.setPattern(pattern)
mainloop() |
TypeScript | UTF-8 | 579 | 2.5625 | 3 | [] | no_license | import { produce } from 'immer'
import { fetchProjectDataProducer } from './producers'
import { IProjectState } from 'reducerTypes/project'
import { IProjectAction } from 'actionTypes/project'
const initialState: IProjectState = {
name: '',
surname: '',
}
const project = (
state: IProjectState = initialState,
action: IProjectAction
): IProjectState => {
return produce(state, (draft: IProjectState) => {
switch (action.type) {
case 'FETCH_PROJECT_DATA':
fetchProjectDataProducer(action)(draft)
break
}
})
}
export default project
|
Shell | UTF-8 | 650 | 3.40625 | 3 | [
"MIT"
] | permissive | #!/bin/sh -f
#
# Copyright (c) 2000-2001 Silicon Graphics, Inc. All Rights Reserved.
#
OPTS=" "
DBOPTS=" "
USAGE="usage: xfs_ncheck [-sfV] [-l logdev] [-i ino]... special"
while getopts "b:fi:l:svV" c
do
case $c in
s) OPTS=$OPTS"-s ";;
i) OPTS=$OPTS"-i "$OPTARG" ";;
v) OPTS=$OPTS"-v ";;
f) DBOPTS=$DBOPTS" -f";;
l) DBOPTS=$DBOPTS" -l "$OPTARG" ";;
V) xfs_db -p xfs_ncheck -V
status=$?
exit $status
;;
\?) echo $USAGE 1>&2
exit 2
;;
esac
done
set -- extra $@
shift $OPTIND
case $# in
1) xfs_db$DBOPTS -r -p xfs_ncheck -c "blockget -ns" -c "ncheck$OPTS" $1
status=$?
;;
*) echo $USAGE 1>&2
exit 2
;;
esac
exit $status
|
Java | UTF-8 | 3,462 | 1.96875 | 2 | [] | no_license | package com.cubrid.cubridmanager.core.replication.task;
import com.cubrid.common.core.util.StringUtil;
import com.cubrid.cubridmanager.core.SetupEnvTestCase;
import com.cubrid.cubridmanager.core.SystemParameter;
import com.cubrid.cubridmanager.core.Tool;
import com.cubrid.cubridmanager.core.common.socket.MessageUtil;
import com.cubrid.cubridmanager.core.common.socket.TreeNode;
public class GetReplicatedTablesTaskTest extends
SetupEnvTestCase {
public void testSend() throws Exception {
if (StringUtil.isEqual(
SystemParameter.getParameterValue("useMockTest"), "y"))
return;
String filepath = this.getFilePathInPlugin("/com/cubrid/cubridmanager/core/replication/task/test.message/GetReplicatedTables_send");
String msg = Tool.getFileContent(filepath);
//replace "token" field with the latest value
msg = msg.replaceFirst("token:.*\n", "token:" + token + "\n");
//composite message
GetReplicatedTablesTask task = new GetReplicatedTablesTask(serverInfo);
task.setDistdbName("distdb");
task.setMasterdbName("mdb");
task.setSlavedbName("sdb");
task.setDistdbPassword("123456");
task.setRunningMode(true);
assertEquals(msg, Tool.decryptContent(serverInfo, task.getRequest()));
task.setRunningMode(false);
msg = msg.replaceFirst("mode:C", "mode:S");
assertEquals(msg, Tool.decryptContent(serverInfo, task.getRequest()));
}
public void testReceive() throws Exception {
if (StringUtil.isEqual(
SystemParameter.getParameterValue("useMockTest"), "y"))
return;
//case 1
String filepath = this.getFilePathInPlugin("/com/cubrid/cubridmanager/core/replication/task/test.message/GetReplicatedTables_receive");
String msg = Tool.getFileContent(filepath);
TreeNode node = MessageUtil.parseResponse(msg);
GetReplicatedTablesTask task = new GetReplicatedTablesTask(serverInfo);
task.setResponse(node);
String[] tables = task.getReplicatedTables();
assertTrue(tables.length == 2);
boolean isReplAll = task.isReplicateAll();
assertFalse(isReplAll);
//case 2
msg = msg.replaceFirst("all_repl:Y", "all_repl:N");
node = MessageUtil.parseResponse(msg);
task.setResponse(node);
task.isReplicateAll();
msg = msg.replaceFirst("all_repl:N", "");
node = MessageUtil.parseResponse(msg);
task.setResponse(node);
task.isReplicateAll();
//case 3
msg = msg.replaceFirst("open:repl_group_tablelist", "open:aa");
node = MessageUtil.parseResponse(msg);
task.setResponse(node);
task.getReplicatedTables();
msg = msg.replaceFirst("open:aa", "");
msg = msg.replaceFirst("close:repl_group_tablelist", "");
node = MessageUtil.parseResponse(msg);
task.setResponse(node);
task.getReplicatedTables();
//exception case1
task.setResponse(null);
tables = task.getReplicatedTables();
assertTrue(tables == null);
isReplAll = task.isReplicateAll();
assertFalse(isReplAll);
//exception case2
task.setResponse(node);
task.setErrorMsg("hasError");
tables = task.getReplicatedTables();
assertTrue(tables == null);
isReplAll = task.isReplicateAll();
assertFalse(isReplAll);
}
public void test() throws Exception {
if (!isConnectRealEnv) {
return;
}
GetReplicatedTablesTask task = new GetReplicatedTablesTask(serverInfo);
task.setDistdbName("dist_biaodb");
task.setMasterdbName("src_biaodb");
task.setSlavedbName("dest_biaodb");
task.setDistdbPassword("123456");
task.execute();
// compare
assertEquals(true, task.isSuccess());
}
}
|
JavaScript | UTF-8 | 3,683 | 2.734375 | 3 | [] | no_license | const getNoradIdsFromLaunch = require('./norad-ids-from-launch')
const { ApolloServer, gql } = require('apollo-server')
const moment = require('moment')
const rawLaunches = require('./spacex_launches.json')
const launches = rawLaunches.map(launch => ({
launch_date_friendly: moment.unix(launch.launch_date_unix).toLocaleString(),
...launch
}))
// I decided to not support time, just date, I didn't think launches happened a ton of times on the same day
// I'm not a fan of snake case but decided to stick with the data format
// I didn't see a reason to add all the values from data and focused on filtering and type shapes
// Normally I would split up this file if it got any bigger but no reason for this project
const typeDefs = gql`
# Normally I would make the input required always but it does make the endpoint easy to use by not requiring it to be passed in and expecting all to be returned (hence the comment in schema)
type Query {
"Returns all launches if no input provided"
launches(input: MissionsInput): [Launch]
}
input MissionsInput {
"Partial or full mission name (not case sensitive)"
mission_name: String
"YYYY-MM-DD date format (no time)"
start_date: String
"YYYY-MM-DD date format (no time)"
end_date: String
norad_ids: [Int]
flight_number: Int
launch_success: Boolean
}
type Launch {
flight_number: Int
mission_name: String
"Unix epoch time"
launch_date_unix: Int
launch_date_friendly: String # # This is just to be easier to know the date probably shouldn't be left on the graph
rocket: Rocket
launch_success: Boolean
}
type Rocket {
payloads: [RocketPayload]
}
type RocketPayload {
norad_id: [Int]
}
`
const resolvers = {
Query: {
launches(_, { input }) {
// I'm assuming if date(s) are provided they are in the proper format 🤷♂️
const { mission_name, start_date, end_date, norad_ids, flight_number, launch_success } = input || {}
console.log('Your input', input)
let filteredLaunches = launches; // Not the safest but not altering our source variable
if (mission_name) {
filteredLaunches = filteredLaunches.filter(launch => launch.mission_name.toLowerCase().includes(mission_name))
}
if (start_date) {
const _startDate = moment(start_date)
const _endDate = end_date ? moment(end_date) : _startDate
filteredLaunches = filteredLaunches.filter(launch => {
const launchDate = moment.unix(launch.launch_date_unix)
return launchDate.isBetween(_startDate, _endDate, 'days', '[]')
})
}
if (norad_ids && norad_ids.length > 0) {
filteredLaunches = filteredLaunches.filter(launch => {
const foundNoradIds = getNoradIdsFromLaunch(launch)
return norad_ids.some(id => foundNoradIds.includes(id))
})
}
if (norad_ids && norad_ids.length === 0) {
filteredLaunches = filteredLaunches.filter(launch => {
return getNoradIdsFromLaunch(launch).length === 0
})
}
if (flight_number) {
filteredLaunches = filteredLaunches.filter(launch => launch.flight_number === flight_number)
}
if (launch_success !== void 0) {
filteredLaunches = filteredLaunches.filter(launch => launch.launch_success === launch_success)
}
return filteredLaunches
}
}
}
const server = new ApolloServer({ typeDefs, resolvers })
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`)
})
|
Java | UTF-8 | 4,983 | 2.765625 | 3 | [] | no_license | package br.ce.wcaquino.tasks.functional;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TasksTest {
public WebDriver acessarAplicacao() throws MalformedURLException {
System.setProperty("webdriver.chrome.driver", "C:\\webdrivers\\chromedriver\\85\\chromedriver.exe");
// Inicialização normal (sem Grid)
WebDriver driver = new ChromeDriver();//como foi colocado no path o caminho até o ChromeDriver, não precisa setar o caminho do driver aqui (mas no build do Jenkins dá erro, aí preciso colocar o caminho aqui)
// Inicialização usando Selenium Grid
//DesiredCapabilities cap = DesiredCapabilities.chrome();
//WebDriver driver;
//driver = new RemoteWebDriver(new URL("http://192.168.99.100:4444/wd/hub"), cap);//peguei essa URL do prompt onde o hub está rodando
// se quiser rodar na minha máquina, o ip é: 192.168.1.106
// se quiser rodar no ambiente dockerizado, o ip é: 192.168.99.100
//Daqui pra baixo é igual usando Selenium Grid ou não
//driver.navigate().to("http://192.168.1.106:8080/tasks");//não dá pra usar localhost se rodar em ambiente dockerizado, pq a aplicação não estará dentro dos containeres!
driver.navigate().to("localhost:8080/tasks");//só dá para rodar assim se não usar o Grid
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
@Test
public void deveSalvarTarefaComSucesso() throws MalformedURLException {
WebDriver driver = acessarAplicacao();
try {
//clicar em Add Todo
driver.findElement(By.id("addTodo")).click();
//escrever a descrição
driver.findElement(By.id("task")).sendKeys("Teste via Selenium");
//escrever a data
driver.findElement(By.id("dueDate")).sendKeys("10/10/2030");
//clicar em salvar
driver.findElement(By.id("saveButton")).click();
//validar mensagem de sucesso
String message = driver.findElement(By.id("message")).getText();
Assert.assertEquals("Success!", message);
} finally {
//fechar o browser
driver.quit();
}
}
@Test
public void naoDeveSalvarTarefaSemDescricao() throws MalformedURLException {
WebDriver driver = acessarAplicacao();
try {
//clicar em Add Todo
driver.findElement(By.id("addTodo")).click();
//escrever a data
driver.findElement(By.id("dueDate")).sendKeys("10/10/2030");
//clicar em salvar
driver.findElement(By.id("saveButton")).click();
//validar mensagem de sucesso
String message = driver.findElement(By.id("message")).getText();
Assert.assertEquals("Fill the task description", message);
} finally {
//fechar o browser
driver.quit();
}
}
@Test
public void naoDeveSalvarTarefaSemData() throws MalformedURLException {
WebDriver driver = acessarAplicacao();
try {
//clicar em Add Todo
driver.findElement(By.id("addTodo")).click();
//escrever a descrição
driver.findElement(By.id("task")).sendKeys("Teste via Selenium");
//clicar em salvar
driver.findElement(By.id("saveButton")).click();
//validar mensagem de sucesso
String message = driver.findElement(By.id("message")).getText();
Assert.assertEquals("Fill the due date", message);
} finally {
//fechar o browser
driver.quit();
}
}
@Test
public void naoDeveSalvarTarefaComDataPassada() throws MalformedURLException {
WebDriver driver = acessarAplicacao();
try {
//clicar em Add Todo
driver.findElement(By.id("addTodo")).click();
//escrever a descrição
driver.findElement(By.id("task")).sendKeys("Teste via Selenium");
//escrever a data
driver.findElement(By.id("dueDate")).sendKeys("10/10/2010");
//clicar em salvar
driver.findElement(By.id("saveButton")).click();
//validar mensagem de sucesso
String message = driver.findElement(By.id("message")).getText();
Assert.assertEquals("Due date must not be in past", message);
} finally {
//fechar o browser
driver.quit();
}
}
@Test
public void deveRemoverTarefaComSucesso() throws MalformedURLException {
WebDriver driver = acessarAplicacao();
try {
//inserir tarefa
driver.findElement(By.id("addTodo")).click();
driver.findElement(By.id("task")).sendKeys("Teste via Selenium");
driver.findElement(By.id("dueDate")).sendKeys("10/10/2030");
driver.findElement(By.id("saveButton")).click();
String message = driver.findElement(By.id("message")).getText();
Assert.assertEquals("Success!", message);
//remover a tarefa
driver.findElement(By.xpath("//a[@class='btn btn-outline-danger btn-sm']")).click();
message = driver.findElement(By.id("message")).getText();
Assert.assertEquals("Success!", message);
} finally {
//fechar o browser
driver.quit();
}
}
}
|
Java | UTF-8 | 424 | 1.648438 | 2 | [] | no_license | package com.youpin.item.vo;
import com.youpin.item.pojo.Sku;
import com.youpin.item.pojo.SpuDetail;
import lombok.Data;
import java.util.List;
/**
* @Author :cjy
* @description :
* @CreateTime :Created in 2019/9/17 9:18
*/
@Data
public class GoodsVo {
private String subTitle;
private Long brandId;
private List<CategoryVo> categories;
private SpuDetail spuDetail;
private List<Sku> skus;
}
|
Python | UTF-8 | 3,392 | 2.71875 | 3 | [] | no_license | from __future__ import division
import cv2
import time
import sys
img = cv2.imread("../chopi.png")
def detectFaceOpenCVDnn(net, frame):
frameOpencvDnn = frame.copy()
frameHeight = frameOpencvDnn.shape[0]
frameWidth = frameOpencvDnn.shape[1]
blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], False, False)
net.setInput(blob)
detections = net.forward()
bboxes = []
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > conf_threshold:
x1 = int(detections[0, 0, i, 3] * frameWidth)
y1 = int(detections[0, 0, i, 4] * frameHeight)
x2 = int(detections[0, 0, i, 5] * frameWidth)
y2 = int(detections[0, 0, i, 6] * frameHeight)
bboxes.append([x1, y1, x2, y2])
tmp = cv2.resize(img, (x2 - max(x1, 0), y2 - max(y1, 0)))
# I want to put logo on top-left corner, So I create a ROI
rows, cols, channels = tmp.shape
roi = frameOpencvDnn[0:rows, 0:cols]
# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(tmp, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(tmp, tmp, mask=mask)
# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg, img2_fg)
frameOpencvDnn[max(y1, 0):y2, max(x1, 0): x2] = dst
# cv2.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0), int(round(frameHeight / 150)), 8)
return frameOpencvDnn, bboxes
if __name__ == "__main__":
# OpenCV DNN supports 2 networks.
# 1. FP16 version of the original caffe implementation ( 5.4 MB )
# 2. 8 bit Quantized version using Tensorflow ( 2.7 MB )
modelFile = "models/opencv_face_detector_uint8.pb"
configFile = "models/opencv_face_detector.pbtxt"
net = cv2.dnn.readNetFromTensorflow(modelFile, configFile)
conf_threshold = 0.7
source = 0
if len(sys.argv) > 1:
source = sys.argv[1]
cap = cv2.VideoCapture(source)
hasFrame, frame = cap.read()
vid_writer = cv2.VideoWriter('output-dnn-{}.avi'.format(str(source).split(".")[0]),
cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 15, (frame.shape[1], frame.shape[0]))
frame_count = 0
tt_opencvDnn = 0
while 1:
hasFrame, frame = cap.read()
if not hasFrame:
break
frame_count += 1
t = time.time()
outOpencvDnn, bboxes = detectFaceOpenCVDnn(net, frame)
tt_opencvDnn += time.time() - t
fpsOpencvDnn = frame_count / tt_opencvDnn
label = "OpenCV DNN ; FPS : {:.2f}".format(fpsOpencvDnn)
cv2.putText(outOpencvDnn, label, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
cv2.imshow("Face Detection Comparison", outOpencvDnn)
vid_writer.write(outOpencvDnn)
if frame_count == 1:
tt_opencvDnn = 0
k = cv2.waitKey(50)
if k == 27:
break
cv2.destroyAllWindows()
vid_writer.release()
|
Markdown | UTF-8 | 6,091 | 3.265625 | 3 | [] | no_license | ---
layout: tminterface-docs
title: TMInterface Guide
---
## Working with triggers
Triggers are a part of the builtin TMInterface bruteforce script that allow you to optimize a section of a track that does not consist of a checkpoint or a finish. A trigger is a cube placed somewhere on the map that acts as a point of an evaluation for the script. If the car enters the trigger, the state of the car is evaluated and the bruteforce script can accept a new solution, based on this evaluation.
Because triggers are a custom feature of TMInterface, they can be evaluated much more precisely than a simple finish/checkpoint time. There are different metrics available to choose how a trigger should be evaluated.
### Stadium coordinate system
A trigger is marked with begin and end point coordinates that lie within the track. The available Stadium building area itself has a size of **1024x256x1024** units:
<img style="margin-top: 40px; width: 100%; margin-bottom: 30px" src="{{ site.baseurl }}/assets/images/trigger_stad_1.png"/>
**A single platform block (`6-2-1`) has dimensions of 32x8x32:**
<img style="margin-top: 40px; width: 100%; margin-bottom: 30px" src="{{ site.baseurl }}/assets/images/trigger_stad_2.png"/>
### What do triggers look like?
**The syntax for adding a trigger on the map is:**
```
add_trigger x1 y1 z1 x2 y2 z2
```
The `x1 y1 z1` parameters mark the starting point of the trigger cube and the `x2 y2 z2` parameters - the end of it, for example:
```
add_trigger 512 9 412 544 41 444
```
would add a trigger to the map like this:
<img style="margin-top: 40px; width: 100%; margin-bottom: 30px" src="{{ site.baseurl }}/assets/images/trigger_stad_3.png"/>
This particular trigger has a size of 32x8x32, however, you can add triggers with any size in any direction. The point cooridnates can be swapped in the command without any difference on how the trigger will be placed: `add_trigger 512 9 412 544 41 444` is equivalent to `add_trigger 544 41 444 512 9 412`.
### How do I place a trigger on the map for bruteforce to optimize for?
You can deduce starting and end points by driving the car to the desired points and then using the **Properties** display available within TMInterface. After your car is in e.g. the starting position, execute `toggle_info` in the console to bring up the Properties display, which displays your current car **position**. These coordiantes are your `x1 y1 z1` parameters. You can then save the coordinates somewhere for later and then drive to the ending point of the trigger. Repeat the process for the ending coordinates. The ending coordinates are your `x2 y2 z2` coordinates.
With your coordinates ready, execute the following command, supplying your points as parameters:
```
add_trigger x1 y1 z1 x2 y2 z2
```
### Testing your trigger placement
<div style="display: flex; margin-top: 30px">
<div class="card shadow" style="width: 100%;">
<div class="card-body">
<h5 class="card-title">Note</h5>
<p class="card-text">
Visualizing trigger placement in-game is not yet available.
</p>
</div>
</div>
</div>
<br>
You can test your newly placed trigger by driving into the trigger area. If you have hit the trigger, an information should be displayed in the console window about the hit:
```
[Triggers] Activated trigger 1 at 8.48 (velocity: 73.0647)
```
which in this case, means that the car has hit the trigger at 8.48s with a velocity of 73.0647.
### Configuring bruteforce for optimizing your trigger
After successfully adding a trigger to your map, you are ready to configure the bruteforce script to optimize your trigger:
1. Bring up the **Settings** panel, go to **Bruteforce**.
2. Tick the **Enable Bruteforce** option.
3. Expand the **Optimization** header.
4. Choose **Trigger time** for the **Optimization Target**.
5. Enter `1` for the **Target Trigger** if it is not already entered.
6. Choose **Distance** for the **Evaluation Metric**.
7. [Launch the Bruteforce script]({{ site.baseurl }}/tminterface/what-is-bf#launching-bruteforce).
This configuration will optimize for the **distance** metric, meaning that bruteforce will accept any solution that was closer to the trigger or reached it faster than the base run.
**Optimizing a trigger has some key differences from other targets:**
* If the trigger you have added was not reached by the base run at all, bruteforce will try to reach it first.
* After reaching the trigger, the further race is completely discarded. Bruteforce will not attempt to finish the run, but will always only optimize for the trigger.
* It is often required that the trigger is placed in an optimal spot, otherwise you may find out that the result is not what you initially wanted to achieve.
* It is likely that at the beginning of each bruteforce session you will get a lot of improvements quickly. This is because even the tiniest improvements are accepted by the script.
### Evaluation metrics
As part of the builtin trigger evaluation, these metrics are available:
* **Distance**: the default metric, compares the time the car reached the trigger first, then the distance to the trigger one tick before the car reached the trigger
* **Distance Then Velocity**: like distance, but if the difference in distance is within 0.01 units, velocity (speed) is compared
* **Velocity**: after reaching the trigger, only velocity (speed) is compared
### Managing triggers
You can see a list of triggers you have added with the `triggers` command:
```
triggers
```
which will display information about currently placed triggers:
```
Trigger 1: Pos (512, 9, 412); Size: (32, 8, 32)
```
If you need to edit a trigger you have placed before, remove it first by executing the `remove_trigger` command:
```
remove_trigger 1
```
which will remove the first trigger added. While TMInterface itself supports adding multiple triggers to the map, the bruteforce script is not able to optimize for multiple triggers at once yet. After removing the trigger, you can add a new trigger with updated coordinates. |
Markdown | UTF-8 | 908 | 2.640625 | 3 | [] | no_license | # TRAGDOR TRANSLATOR!!!!
## Description
This crazy translator was an excersise to practice adding event listeners to elements of the DOM. This project was also used to strengthen our existing understanding of objects, array's and loops.
I challenged myself to dynamically target JS object's based on the ID of the button clicked.
## Screenshots

## How to run
1. Requires node.js
1. Requires git bash
1. clone down this repo ``` https://github.com/awieckert/Translator```
1. In bash terminal ```npm install http-server ```
1. Navigate to local directory
1. type ```hs -p 8080``` into terminal
1. In browser navigate to ```localhost:8080```
1. enter following command if nothing is displayed ``` ctrl + shift + r```
## Contributors
[Adam Wieckert](https://github.com/awieckert/awieckert.github.io) |
PHP | UTF-8 | 1,168 | 3.1875 | 3 | [] | no_license | <?php
class ListSurveys
{
/**
* GetSurvey constructor.
*
* required call $getSurveys to get Surveys List
*/
public function __construct()
{
}
/**
* @return array return array with questions
*/
public function getSurveys(): array
{
$con = null;
require_once __DIR__ . "/../connection.php"; // include $con
$query = "SELECT ID, TITLE, DESCRIPTION, CREATION_DATE FROM SURVEYS ORDER BY ID DESC;";
$prepare = mysqli_stmt_init($con);
if (mysqli_stmt_prepare($prepare, $query)) {
$array = [];
mysqli_stmt_execute($prepare);
mysqli_stmt_bind_result($prepare, $id, $title, $description, $date);
while (mysqli_stmt_fetch($prepare)) {
array_push($array, ["id" => $id, "title" => $title, "desc" => $description, "creationDate" => $date]);
}
mysqli_stmt_close($prepare);
return $array;
} else {
return [["id" => 0, "title" => "Error en el servidor", "desc" => "Ocurrió un error el procesar la solicitud", "creationDate" => "0000-00-00"]];
}
}
} |
Python | UTF-8 | 806 | 4.21875 | 4 | [] | no_license |
'''
Search a sorted array for entry equal to its index
Design an efficient algorithm that takes a sorted array of distinct integers,
and returns an index i such that the element at i is equal to i.
For example
A = [-2, 0, 2, 3, 6, 7, 9]
returns 2 or 3
'''
# Notice that we can search a different array that is the difference
# between the value and its index. Then we reduce it to binary search for value 0
def search_entry_equal_to_its_index(A):
left, right, result = 0, len(A)-1, -1
while left <= right:
mid = (left+right) // 2
difference = A[mid] - mid
# A[mid] == mid if and only if difference == 0
if difference > 0:
right = mid - 1
elif difference == 0:
return mid
else:
left = mid + 1
return result |
JavaScript | UTF-8 | 433 | 3.34375 | 3 | [
"MIT"
] | permissive | export default function Queue() {
const arr = [];
//入队操作
this.push = function(element) {
arr.push(element);
return true;
};
//出队操作
this.pop = function() {
return arr.shift();
};
//清空队列
this.clear = function() {
arr = [];
};
//获取队长
this.size = function() {
return length;
};
// map
this.map = function (callback) {
return arr.map(callback);
};
}
|
Ruby | UTF-8 | 139 | 3.046875 | 3 | [] | no_license | class String
def eight_bit_number?
/\A([0-9]|[1-8][0-9]|9[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\z/.match(self) ? true : false
end
end |
Python | UTF-8 | 4,867 | 2.765625 | 3 | [] | no_license | import pandas
import numpy as np
import matplotlib.pyplot as plt
import re
ph_fpositive=open('phone_positive.txt','r')
ph_positive=[line.strip() for line in ph_fpositive]
ph_fnegative=open('phone_negative.txt','r')
ph_negative=[line.strip() for line in ph_fnegative]
sys_fpositive=open('system_positive.txt','r')
sys_positive=[line.strip() for line in sys_fpositive]
sys_fnegative=open('system_negative.txt','r')
sys_negative=[line.strip() for line in sys_fnegative]
iphone=open('iphone.txt','r')
samsung=open('samsung.txt','r')
lumia=open('lumia.txt','r')
ios=open('ios.txt','r')
android=open('android.txt','r')
windowsphone=open('windowsphone.txt','r')
filename=[iphone,samsung,lumia,ios,android,windowsphone]
productname=['Iphone','Galaxy','Lumia','Ios','Android','Windowsphone']
def creat_dict(filename,dproduct,positive,negative):
global pos_frame
global neg_frame
for p in range(0,len(positive)):
pos_frame[p][dproduct]=0
for p in range(0,len(negative)):
neg_frame[p][dproduct]=0
line=filename.readline()
while line:
for p in range(0,len(positive)):
if re.findall(positive[p],line):
pos_frame[p][dproduct] +=1
for p in range(0,len(negative)):
if re.findall(negative[p],line):
neg_frame[p][dproduct] +=1
line=filename.readline()
pos_total=0
neg_total=0
for p in range(0,len(positive)):
pos_total +=pos_frame[p][dproduct]
for p in range(0,len(negative)):
neg_total +=neg_frame[p][dproduct]
for p in range(0,len(positive)):
percent='%.2f' % ((float (pos_frame[p][dproduct]*100))/(float (pos_total)))
pos_frame[p][dproduct]=float(percent)
for p in range(0,len(negative)):
percent='%.2f' % ((float (neg_frame[p][dproduct]*100))/(float (neg_total)))
neg_frame[p][dproduct]=float(percent)
#for phone
pos_frame=[]
neg_frame=[]
for word in ph_positive:
pos_frame.append({})
for word in ph_negative:
neg_frame.append({})
for i in range(0,3):
creat_dict(filename[i],productname[i],ph_positive,ph_negative)
ph_pos_df=pandas.DataFrame(pos_frame)
ph_neg_df=pandas.DataFrame(neg_frame)
#for system
pos_frame=[]
neg_frame=[]
for word in sys_positive:
pos_frame.append({})
for word in sys_negative:
neg_frame.append({})
for i in range(3,6):
creat_dict(filename[i],productname[i],sys_positive,sys_negative)
sys_pos_df=pandas.DataFrame(pos_frame)
sys_neg_df=pandas.DataFrame(neg_frame)
ph_pos_ind=[]
ph_neg_ind=[]
sys_pos_ind=[]
sys_neg_ind=[]
for i in range(0,3):
ph_pos_ind.append(np.arange(0.3*i,len(ph_positive)+0.3*i))
ph_neg_ind.append(np.arange(0.3*i,len(ph_negative)+0.3*i))
sys_pos_ind.append(np.arange(0.3*i,len(sys_positive)+0.3*i))
sys_neg_ind.append(np.arange(0.3*i,len(sys_negative)+0.3*i))
bar_color=['r','g','y']
#for phone
pos_product_bar=[]
neg_product_bar=[]
plt.figure(figsize=(20,15))
for i in range(0,3):
bar_chart=plt.bar(ph_pos_ind[i],ph_pos_df[productname[i]],0.3,color=bar_color[i])
pos_product_bar.append(bar_chart[0])
plt.xlabel('Positive Words')
plt.ylabel('Percentage in Total Positive Words(%)')
plt.title('Positive Aspects of Three Brands of Phone')
plt.xticks(ph_pos_ind[0]+0.45,(ph_positive))
plt.legend((pos_product_bar),(productname[0:3]))
plt.savefig('ph_pos_bar.png')
plt.figure(figsize=(20,15))
for i in range(0,3):
bar_chart=plt.bar(ph_neg_ind[i],ph_neg_df[productname[i]],0.3,color=bar_color[i])
neg_product_bar.append(bar_chart[0])
plt.xlabel('Negative Words')
plt.ylabel('Percentage in Total Negative Words(%)')
plt.title('Negative Aspects of Three Brands of Phone')
plt.xticks(ph_neg_ind[0]+0.45,(ph_negative))
plt.legend((neg_product_bar),(productname[0:3]))
plt.savefig('ph_neg_bar.png')
#for system
pos_product_bar=[]
neg_product_bar=[]
plt.figure(figsize=(20,15))
for i in range(0,3):
bar_chart=plt.bar(sys_pos_ind[i],sys_pos_df[productname[i+3]],0.3,color=bar_color[i])
pos_product_bar.append(bar_chart[0])
plt.xlabel('Positive Words')
plt.ylabel('Percentage in Total Positive Words(%)')
plt.title('Positive Aspects of Three Phone Systems')
plt.xticks(sys_pos_ind[0]+0.45,(sys_positive))
plt.legend((pos_product_bar),(productname[3:6]))
plt.savefig('sys_pos_bar.png')
plt.figure(figsize=(20,15))
for i in range(0,3):
bar_chart=plt.bar(sys_neg_ind[i],sys_neg_df[productname[i+3]],0.3,color=bar_color[i])
neg_product_bar.append(bar_chart[0])
plt.xlabel('Negative Words')
plt.ylabel('Percentage in Total Negative Words(%)')
plt.title('Negative Aspects of Three Phone Systems')
plt.xticks(sys_neg_ind[0]+0.45,(sys_negative))
plt.legend((neg_product_bar),(productname[3:6]))
plt.savefig('sys_neg_bar.png')
ph_fpositive.close()
ph_fnegative.close()
sys_fpositive.close()
sys_fnegative.close()
for f in filename:
f.close()
|
Python | UTF-8 | 3,215 | 3.453125 | 3 | [
"MIT"
] | permissive | # # Simple recursive approach. Time Limit Exceeded
# class Solution(object):
# def isInterleave(self, s1, s2, s3):
# """
# :type s1: str
# :type s2: str
# :type s3: str
# :rtype: bool
# """
# return self.isInterleaveHelper(s1, s2, s3, 0, 0, 0)
#
#
# def isInterleaveHelper(self, s1, s2, s3, s1Idx, s2Idx, s3Idx):
# """
# :type s1: str
# :type s2: str
# :type s3: str
# :rtype: bool
# """
# s1Len, s2Len, s3Len = len(s1), len(s2), len(s3)
#
# # if we have reached the end of the all the strings, because we have consumed all the string and the string in interleaving
# if s1Idx == s1Len and s2Idx == s2Len and s3Idx == s3Len:
# return True
#
# # if we have reached the end of 'p' but 'm' or 'n' still has some characters left
# if s3Idx == s3Len:
# return False
#
# c1, c2 = False, False
# if s1Idx < s1Len and s1[s1Idx] == s3[s3Idx]:
# c1 = self.isInterleaveHelper(s1, s2, s3, s1Idx + 1, s2Idx, s3Idx + 1)
#
# if s2Idx < s2Len and s2[s2Idx] == s3[s3Idx]:
# c2 = self.isInterleaveHelper(s1, s2, s3, s1Idx, s2Idx + 1, s3Idx + 1)
#
# return c1 or c2
class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
s1Len, s2Len, s3Len = len(s1), len(s2), len(s3)
# dp[mIndex][nIndex] will be storing the result of string interleaving
# up to p[0..mIndex+nIndex-1]
dp = [[False for _ in range(s2Len + 1)] for _ in range(s1Len + 1)]
# for the empty pattern, we have one matching
if s1Len + s2Len != s3Len:
return False
for s1Index in range(s1Len + 1):
for s2Index in range(s2Len + 1):
# if 'm' and 'n' are empty, then 'p' must have been empty too.
if s1Index == 0 and s2Index == 0:
dp[s1Index][s2Index] = True
# if 'm' is empty, we need to check the interleaving with 'n' only
elif s1Index == 0 and s2[s2Index - 1] == s3[s1Index + s2Index - 1]:
dp[s1Index][s2Index] = dp[s1Index][s2Index - 1]
# if 'n' is empty, we need to check the interleaving with 'm' only
elif s2Index == 0 and s1[s1Index - 1] == s3[s1Index + s2Index - 1]:
dp[s1Index][s2Index] = dp[s1Index - 1][s2Index]
else:
# if the letter of 'm' and 'p' match, we take whatever is matched till mIndex-1
if s1Index > 0 and s1[s1Index - 1] == s3[s1Index + s2Index - 1]:
dp[s1Index][s2Index] = dp[s1Index - 1][s2Index]
# if the letter of 'n' and 'p' match, we take whatever is matched till nIndex-1 too
# note the '|=', this is required when we have common letters
if s2Index > 0 and s2[s2Index - 1] == s3[s1Index + s2Index - 1]:
dp[s1Index][s2Index] |= dp[s1Index][s2Index - 1]
return dp[s1Len][s2Len]
|
Markdown | UTF-8 | 4,668 | 3.4375 | 3 | [
"MIT"
] | permissive | ---
metaTitle: "R - Random Numbers Generator"
description: "Random permutations, Random number generator's reproducibility, Generating random numbers using various density functions"
---
# Random Numbers Generator
## Random permutations
To generate random permutation of 5 numbers:
```r
sample(5)
# [1] 4 5 3 1 2
```
To generate random permutation of any vector:
```r
sample(10:15)
# [1] 11 15 12 10 14 13
```
One could also use the package `pracma`
```r
randperm(a, k)
# Generates one random permutation of k of the elements a, if a is a vector,
# or of 1:a if a is a single integer.
# a: integer or numeric vector of some length n.
# k: integer, smaller as a or length(a).
# Examples
library(pracma)
randperm(1:10, 3)
[1] 3 7 9
randperm(10, 10)
[1] 4 5 10 8 2 7 6 9 3 1
randperm(seq(2, 10, by=2))
[1] 6 4 10 2 8
```
## Random number generator's reproducibility
When expecting someone to reproduce an R code that has random elements in it, the `set.seed()` function becomes very handy.
For example, these two lines will always produce different output (because that is the whole point of random number generators):
```r
> sample(1:10,5)
[1] 6 9 2 7 10
> sample(1:10,5)
[1] 7 6 1 2 10
```
These two will also produce different outputs:
```r
> rnorm(5)
[1] 0.4874291 0.7383247 0.5757814 -0.3053884 1.5117812
> rnorm(5)
[1] 0.38984324 -0.62124058 -2.21469989 1.12493092 -0.04493361
```
However, if we set the seed to something identical in both cases (most people use 1 for simplicity), we get two identical samples:
```r
> set.seed(1)
> sample(letters,2)
[1] "g" "j"
> set.seed(1)
> sample(letters,2)
[1] "g" "j"
```
and same with, say, `rexp()` draws:
```r
> set.seed(1)
> rexp(5)
[1] 0.7551818 1.1816428 0.1457067 0.1397953 0.4360686
> set.seed(1)
> rexp(5)
[1] 0.7551818 1.1816428 0.1457067 0.1397953 0.4360686
```
## Generating random numbers using various density functions
Below are examples of generating 5 random numbers using various probability distributions.
### **Uniform** distribution between 0 and 10
```r
runif(5, min=0, max=10)
[1] 2.1724399 8.9209930 6.1969249 9.3303321 2.4054102
```
### **Normal** distribution with 0 mean and standard deviation of 1
```r
rnorm(5, mean=0, sd=1)
[1] -0.97414402 -0.85722281 -0.08555494 -0.37444299 1.20032409
```
### **Binomial** distribution with 10 trials and success probability of 0.5
```r
rbinom(5, size=10, prob=0.5)
[1] 4 3 5 2 3
```
### **Geometric** distribution with 0.2 success probability
```r
rgeom(5, prob=0.2)
[1] 14 8 11 1 3
```
### **Hypergeometric** distribution with 3 white balls, 10 black balls and 5 draws
```r
rhyper(5, m=3, n=10, k=5)
[1] 2 0 1 1 1
```
### **Negative Binomial** distribution with 10 trials and success probability of 0.8
```r
rnbinom(5, size=10, prob=0.8)
[1] 3 1 3 4 2
```
### **Poisson** distribution with mean and variance (lambda) of 2
```r
rpois(5, lambda=2)
[1] 2 1 2 3 4
```
### **Exponential** distribution with the rate of 1.5
```r
rexp(5, rate=1.5)
[1] 1.8993303 0.4799358 0.5578280 1.5630711 0.6228000
```
### **Logistic** distribution with 0 location and scale of 1
```r
rlogis(5, location=0, scale=1)
[1] 0.9498992 -1.0287433 -0.4192311 0.7028510 -1.2095458
```
### **Chi-squared** distribution with 15 degrees of freedom
```r
rchisq(5, df=15)
[1] 14.89209 19.36947 10.27745 19.48376 23.32898
```
### **Beta** distribution with shape parameters a=1 and b=0.5
```r
rbeta(5, shape1=1, shape2=0.5)
[1] 0.1670306 0.5321586 0.9869520 0.9548993 0.9999737
```
### **Gamma** distribution with shape parameter of 3 and scale=0.5
```r
rgamma(5, shape=3, scale=0.5)
[1] 2.2445984 0.7934152 3.2366673 2.2897537 0.8573059
```
### **Cauchy** distribution with 0 location and scale of 1
```r
rcauchy(5, location=0, scale=1)
[1] -0.01285116 -0.38918446 8.71016696 10.60293284 -0.68017185
```
### **Log-normal** distribution with 0 mean and standard deviation of 1 (on log scale)
```r
rlnorm(5, meanlog=0, sdlog=1)
[1] 0.8725009 2.9433779 0.3329107 2.5976206 2.8171894
```
### **Weibull** distribution with shape parameter of 0.5 and scale of 1
```r
rweibull(5, shape=0.5, scale=1)
[1] 0.337599112 1.307774557 7.233985075 5.840429942 0.005751181
```
### **Wilcoxon** distribution with 10 observations in the first sample and 20 in second.
```r
rwilcox(5, 10, 20)
[1] 111 88 93 100 124
```
### **Multinomial** distribution with 5 object and 3 boxes using the specified probabilities
```r
rmultinom(5, size=5, prob=c(0.1,0.1,0.8))
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 1 1 0
[2,] 2 0 1 1 0
[3,] 3 5 3 3 5
```
|
Java | UTF-8 | 516 | 1.601563 | 2 | [] | no_license | package com.ssm.aop;
import com.ssm.bean.User;
import com.ssm.dao.UserMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* description:
* author:张腾
* date:2020-11-25
*/
@Component
@Aspect
public class userCheck {
@Autowired
UserMapper userMapper;
}
|
PHP | UTF-8 | 1,526 | 2.796875 | 3 | [] | no_license | <?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With');
// Get the raw data
$data = json_decode(file_get_contents('php://input'));
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($data->teacher_id)){
// Include required files
include_once '../../config/Database.php';
include_once '../../models/Events.php';
// Create database instance
$database = new Database();
$db = $database->connection();
// Create add event instance
$add_event = new Events($db);
// Set event properties
$add_event->teacher_id = $data->teacher_id;
$add_event->title = $data->title;
$add_event->start_date = $data->startTime;
$add_event->end_date = $data->endTime;
$add_event->message = $data->message;
if($add_event->add_event()){
echo json_encode(
array(
'message' => 'New event has been added',
'status' => true
)
);
}else{
echo json_encode(
array(
'message' => 'Something went wrong, event not added',
'status' => false
)
);
}
} |
Markdown | UTF-8 | 2,065 | 2.84375 | 3 | [] | no_license | ---
layout: post
title: 3 WordPress Security Plugins you must have to keep hackers at bay.
excerpt: WordPress has a bad reputation for getting hacked. It's opensource, so anyone can figure out how it works and where it's weaknesses are. And most new owners don't take very basic measures to protect themselves because they don't know how. So here's an excerpt from my resource Essential WordPress Plugins to help guide would-be victims.
permalink: /2009/02/3-wordpress-security-plugins-you-must-have-to-keep-hackers-at-bay/
categories:
- wordpress
---
WordPress has a bad reputation for getting hacked. It's opensource, so anyone can figure out how it works and where it's weaknesses are. And most new owners don't take very basic measures to protect themselves because they don't know how. So here's an excerpt from my resource <a href="http://rachelnabors.com/essential-wordpress-plugins-a-web-designers-best-friend/"><em>Essential WordPress Plugins</em></a> to help guide would-be victims:
<ul>
<li><a title="Visit plugin homepage" href="http://akismet.com/">Akismet</a> comes standard with every Wordpress install. It prevents spammers from abusing your blog. Make sure it is activated ASAP! It does, however, require you to get an API key by registering at WordPress.org.</li>
<li><a title="Visit plugin homepage" href="http://www.askapache.com/htaccess/htaccess-security-block-spam-hackers.html">AskApache Password Protect</a> protects your blog by locking it down with a handful of extra passwords and .htaccess edits. Great at walling malicious password crackers.</li>
<li><a title="Visit plugin homepage" href="http://semperfiwebdesign.com/plugins/wp-security-scan/">WP Security Scan</a> scans your installation and alerts you to any major holes in your security that icky people might try to exploit. Did you realize that your default "admin" user is a liability? Or that your database tables should begin with anything but <em>wp_?</em></li>
</ul>
I'll take this moment to preen that all my WordPress-based sites come with these babies in place. |
Java | UTF-8 | 5,905 | 2.1875 | 2 | [] | no_license | package com.itechart.contacts.core.unit.attachment.service;
import com.itechart.contacts.core.utils.testutil.TestUtil;
import com.itechart.contacts.core.attachment.dto.AttachmentDto;
import com.itechart.contacts.core.attachment.dto.SaveAttachmentDto;
import com.itechart.contacts.core.attachment.entity.Attachment;
import com.itechart.contacts.core.attachment.repository.AttachmentRepository;
import com.itechart.contacts.core.attachment.service.AttachmentServiceImpl;
import com.itechart.contacts.core.person.entity.Person;
import com.itechart.contacts.core.person.repository.PersonRepository;
import com.itechart.contacts.core.utils.ObjectMapperUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
public class AttachmentServiceImplTest {
@InjectMocks
private AttachmentServiceImpl attachmentService;
@Mock
private AttachmentRepository attachmentRepository;
@Mock
private PersonRepository personRepository;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
private TestUtil testUtil = new TestUtil();
@Test
public void createAttachmentPositiveTest() {
Person person = new Person();
person.setId(1L);
Attachment expected = testUtil.initAttachment("TestString");
expected.setId(1L);
when(attachmentRepository.save(expected)).thenReturn(expected);
when(personRepository.getOne(1L)).thenReturn(person);
SaveAttachmentDto saveAttachmentDto = ObjectMapperUtils.map(expected, SaveAttachmentDto.class);
saveAttachmentDto.setPersonId(1L);
Attachment actual = ObjectMapperUtils.map(attachmentService.create(saveAttachmentDto), Attachment.class);
assertNotNull(actual);
assertEquals(expected, actual);
}
@Test
public void createAttachmentNegativeTest() {
Person person = new Person();
person.setId(1L);
Attachment expected = testUtil.initAttachment("TestString");
Attachment unexpected = testUtil.initAttachment("Another TestString");
when(attachmentRepository.save(expected)).thenReturn(expected);
when(personRepository.getOne(1L)).thenReturn(person);
SaveAttachmentDto saveAttachmentDto = ObjectMapperUtils.map(expected, SaveAttachmentDto.class);
saveAttachmentDto.setPersonId(1L);
Attachment actual = ObjectMapperUtils.map(attachmentService.create(saveAttachmentDto), Attachment.class);
assertNotNull(actual);
assertNotEquals(unexpected, actual);
}
@Test(expected = IllegalArgumentException.class)
public void createAttachmentNegativeTestIllArgExc() {
attachmentService.create(null);
}
@Test(expected = NullPointerException.class)
public void createAttachmentNegativeTestNPE() {
Person person = new Person();
person.setId(1L);
Attachment attachment = new Attachment();
SaveAttachmentDto saveAttachmentDto = ObjectMapperUtils.map(attachment, SaveAttachmentDto.class);
when(attachmentRepository.save(attachment)).thenReturn(attachment);
AttachmentDto attachmentDto = attachmentService.create(saveAttachmentDto);
// Should generate NullPointerException
String comments = attachmentDto.getComments();
assertNull(attachmentDto.getLoadDate());
assertNull(attachmentDto.getFileName());
assertEquals(attachmentDto.getId(), 0);
}
@Test
public void readAttachmentPositiveTest() {
Attachment expected = testUtil.initAttachment("TestString");
when(attachmentRepository.findById(1L)).thenReturn(java.util.Optional.of(expected));
AttachmentDto attachmentDto = attachmentService.getAttachment(1L);
Attachment actual = ObjectMapperUtils.map(attachmentDto, Attachment.class);
assertNotNull(actual);
assertEquals(expected, actual);
}
@Test
public void readAttachmentNegativeTest() {
Attachment expected = testUtil.initAttachment("TestString");
Attachment unexpected = testUtil.initAttachment("Another TestString");
when(attachmentRepository.findById(1L)).thenReturn(java.util.Optional.of(expected));
AttachmentDto attachmentDto = attachmentService.getAttachment(1L);
Attachment actual = ObjectMapperUtils.map(attachmentDto, Attachment.class);
assertNotNull(attachmentDto);
assertNotEquals(unexpected, actual);
}
@Test
public void updateAttachmentPositiveTest() {
Attachment prevAttachment = testUtil.initAttachment("TestString");
Attachment expected = testUtil.initAttachment("Updated TestString");
when(attachmentRepository.findById(1L)).thenReturn(java.util.Optional.of(prevAttachment));
AttachmentDto attachmentDto = attachmentService.update(1L, ObjectMapperUtils.map(expected, SaveAttachmentDto.class));
Attachment actual = ObjectMapperUtils.map(attachmentDto, Attachment.class);
assertNotNull(attachmentDto);
assertEquals(expected, actual);
}
@Test
public void updateAttachmentNegativeTest() {
Attachment prevAttachment = testUtil.initAttachment("TestString");
Attachment expected = testUtil.initAttachment("Updated TestString");
Attachment unexpected = testUtil.initAttachment("Another TestString");
when(attachmentRepository.findById(1L)).thenReturn(java.util.Optional.of(prevAttachment));
AttachmentDto attachmentDto = attachmentService.update(1L, ObjectMapperUtils.map(expected, SaveAttachmentDto.class));
Attachment actual = ObjectMapperUtils.map(attachmentDto, Attachment.class);
assertNotNull(actual);
assertNotEquals(unexpected, actual);
}
} |
Python | UTF-8 | 3,511 | 3.515625 | 4 | [] | no_license | import numpy as np
import logging
class KnnClassifier(object):
@staticmethod
def euclidean(x,y):
"""
Inputput
x: a 1-dimensional numpy array
y: a 1-dimensional numpy array
Output
A single number, the euclidean distance between x and y
"""
return(np.sqrt(np.sum((x - y)**2)))
@staticmethod
def many_distances(x,Y):
"""
Input
x: a single point as a numpy array
Y: a 2-dimensional numpy array
Output
a numpy array of euclidean distances
"""
result = np.zeros(Y.shape[0])
for idx in range(0, Y.shape[0]):
dist = KnnClassifier.euclidean(x, Y[idx])
result[idx] = dist
return(result)
@staticmethod
def closest_indices(dists, n):
"""
Input
dists: a numpy array of distances (1 dimensional)
n: the number of lowest values to find
Output
a numpy array with the indexes in dists where the
n lowest values are located.
"""
arrIndexes = np.argsort(dists)
return(arrIndexes[0:n])
@staticmethod
def get_values_by_index(indices, values):
"""
Input
indices: a numpy array of indices
values: a list of values
Output
a list of elements from values whose indexes
are the values in indices
"""
arr = np.array(values)
return(arr[indices])
@staticmethod
def get_mode(values):
"""
Input
values: a lists of values
Output
the most common value in the list.
If there's a tie, break it any way you want to.
"""
counts = np.unique(values, return_counts=True)
cnt = np.argsort(counts[1])
colorIndex = cnt[len(cnt) -1]
label = counts[0][colorIndex]
return(label)
@staticmethod
def knn(ind, test_pts, train_pts, labels, k):
"""
Input
test: A 2-D numpy array of points (rows) and features (cols)
train: A 2-D numpy array of points (rows) and features (cols)
labels: A list of labels associated with train points
Output
A list of best guesses for the test labels
"""
output = []
startIdx = ind[0]
endIdx = ind[1]
subsetOfPoints = test_pts[startIdx:endIdx]
for i in range(0,subsetOfPoints.shape[0]):
dists = KnnClassifier.many_distances(subsetOfPoints[i],train_pts)
label_indices = KnnClassifier.closest_indices(dists, k)
labelSet = KnnClassifier.get_values_by_index(label_indices, labels)
predictedLabel = KnnClassifier.get_mode(labelSet)
output.append(predictedLabel)
return output
@staticmethod
def multiclass_accuracy(truth,predictions):
"""
Input
truth: a list of true labels
predictions: a list of predicted labels
Output
a single value - the multiclass accuracy
"""
cmp = np.array(truth) == np.array(predictions)
wrong = len(cmp[cmp == False])
right = len(cmp[cmp == True])
accuracy = right/(wrong + right)
return(accuracy) |
JavaScript | UTF-8 | 2,764 | 2.75 | 3 | [] | no_license | import React, { Component } from "react";
import { connect } from "react-redux";
import {
VerticalBarSeries,
XAxis,
YAxis,
FlexibleWidthXYPlot
} from "react-vis";
import "./css/BarChart.css";
class BarChart extends Component {
constructor() {
super();
this.state = {
hour: null
};
}
render() {
const { date, list, showF } = this.props;
const data = [];
let lowest = 1000;
let highest = -1000;
for (let item of list) {
if (date === item.dt_txt.slice(0, 10)) {
if (showF === true) {
let fahrenheit = ((item.main.temp - 273.15) * 9) / 5 + 32;
if (lowest > fahrenheit) lowest = fahrenheit;
if (highest < fahrenheit) highest = fahrenheit;
data.push({
y: fahrenheit,
x: item.dt_txt.slice(11, 16)
});
} else {
let celcius = item.main.temp - 273.15;
if (lowest > celcius) lowest = celcius;
if (highest < celcius) highest = celcius;
data.push({
y: celcius,
x: item.dt_txt.slice(11, 16)
});
}
}
}
//indicates lowest and highest point on y-axis
// add or subtract 2 to widen the range
const chartDomain = [lowest - 2, highest + 2];
const degree = showF ? "°F" : "°C";
const { hour } = this.state;
let temp;
if (showF && this.state.hour) {
data.find(data => {
return data.x === this.state.hour ? (temp = data.y.toFixed(2)) : null;
});
} else {
data.find(data => {
return data.x === this.state.hour ? (temp = data.y.toFixed(2)) : null;
});
}
return (
<div>
<br />
<h3 className='center'>
Weather for {date} in {degree}
</h3>
<h4 className='center'>
<i>Click on bars to see details</i>
</h4>
<p className='hover-data center'>
{hour ? `Temperature at ${hour}: ${temp} ${degree}` : null}
</p>
<div className='bar-graph-wrapper'>
<FlexibleWidthXYPlot
margin={{ bottom: 55 }}
className='bar-graph'
xType='ordinal'
height={200}
yDomain={chartDomain}
>
<XAxis tickFormat={v => `${v}`} tickLabelAngle={-90} />
<YAxis />
<VerticalBarSeries
data={data}
onValueClick={(datapoint, event) => {
this.setState({
hour: datapoint.x
});
}}
/>
</FlexibleWidthXYPlot>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
list: state.list
};
};
export default connect(mapStateToProps)(BarChart);
|
Markdown | UTF-8 | 676 | 2.875 | 3 | [] | no_license | # My Data Science Learning Journey
This is my repo to learning-by-doing Data Science.
## My Main Resources
I'm using multiple resources to study and apply what I learn here with examples. This is a list of **main** resources I use (_I will update this list whenever I use a new resource_):
* [Data Science Fundamentals: Learning Basic Concepts, Data Wrangling, and Databases with Python](https://www.safaribooksonline.com/library/view/data-science-fundamentals/9780134660141/). Created by Jonathan Dinu.
* [Course Materials](https://github.com/hopelessoptimism/data-science-fundamentals).
* Data Sources:
- [Airbnb Data](http://insideairbnb.com/get-the-data.html). |
Java | UTF-8 | 3,922 | 2.046875 | 2 | [] | no_license | package com.example.intern.giftest.effects;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import com.example.intern.giftest.adapter.Adapter;
import com.example.intern.giftest.clipart.OnVideoActionFinishListener;
import com.example.intern.giftest.effects.Utils.OnEffectApplyFinishedListener;
import com.example.intern.giftest.items.GalleryItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
/**
* Created by AramNazaryan on 7/17/15.
*/
public abstract class BaseVideoAction<T> {
private Activity activity = null;
private OnVideoActionFinishListener listener = null;
protected abstract Bitmap doActionOnBitmap(Bitmap videoFrameBitmap);
public BaseVideoAction(Activity activity, T... params) {
this.activity = activity;
}
public void startAction(final ArrayList<GalleryItem> galleryItems, final Adapter adapter, final T... parameters) {
AsyncTask<Void, Integer, Void> doActionTask = new AsyncTask<Void, Integer, Void>() {
ProgressDialog progressDialog;
@Override
protected Void doInBackground(Void... params) {
int count = galleryItems.size();
for (int i = 0; i < count; i++) {
GalleryItem item = galleryItems.get(i);
if (item.isSeleted()) {
Bitmap bitmapAfterAction = doActionOnBitmap(item.getBitmap());
item.setBitmap(bitmapAfterAction);
galleryItems.set(i, item);
onProgressUpdate(i, count);
}
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(adapter.getSelected().size());
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ImageLoader.getInstance().clearDiskCache();
ImageLoader.getInstance().clearMemoryCache();
if (listener != null) {
listener.onSuccess();
}
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (progressDialog != null) {
progressDialog.setProgress(values[0] + 1);
}
}
};
doActionTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void setOnVideoFinishListener(OnVideoActionFinishListener listener) {
this.listener = listener;
}
public void applyOnOneFrame(final Bitmap bitmap, final OnEffectApplyFinishedListener listener, final T... parameters) {
AsyncTask<Void, Void, Bitmap> doActionTask = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Bitmap bitmapAfterAction = doActionOnBitmap(mutableBitmap);
// mutableBitmap.recycle();
return bitmapAfterAction;
}
@Override
protected void onPostExecute(Bitmap bmp) {
if (listener != null) {
listener.onFinish(bmp);
}
}
};
doActionTask.execute();
}
}
|
Java | UTF-8 | 1,078 | 2.359375 | 2 | [] | no_license | package edu.sysuedaily.cache;
import java.util.Date;
import android.content.Context;
import edu.sysuedaily.cachedatabase.JsonCacheDatabase;
public class WeiboJsonCache extends BaseJsonCache {
protected WeiboJsonCache(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public static WeiboJsonCache getWeiboJsonCache(Context context) {
if (jsonCache == null) {
jsonCache = new WeiboJsonCache(context);
return (WeiboJsonCache) jsonCache;
}
else {
return (WeiboJsonCache) jsonCache;
}
}
@Override
public void cacheJson(String json) {
// TODO Auto-generated method stub
JsonCacheDatabase weiboJsonCacheDatabase = new JsonCacheDatabase(context);
weiboJsonCacheDatabase.cacheWeiboJson(new Date(), json);
}
@Override
public String getCacheJson() {
// TODO Auto-generated method stub
//return null;
JsonCacheDatabase weiboJsonCacheDatabase = new JsonCacheDatabase(context);
String json = weiboJsonCacheDatabase.getWeiboCacheJson();
if (json != null) {
return json;
}
else {
return null;
}
}
}
|
Markdown | UTF-8 | 4,751 | 3.140625 | 3 | [
"MIT"
] | permissive | # WhatIs: DefaultAction
A DefaultAction is a task performed by the browser. DefaultActions are **queued in the event loop**, and they are always **preceded by a native trigger event**. In this respect, DefaultActions very much resemble native CascadeEvents.
DefaultActions are *cancelable*. If you call `.preventDefault()` on the preceding trigger event, then the browser will not perform the DefaultAction. There are some rare exceptions to this rule: in Chrome, calling `.preventDefault()` from a passive eventListeners for `touchstart` will not stop the native `Scrolling` DefaultAction (for more, see Chapter7: TouchGestures).
DefaultActions interact superficially with the DOM. DefaultActions can *read* data from the DOM associated with their triggering event, but they will not *alter* data in the DOM during their processing. Instead, DefaultActions use the data from the triggering event to perform some action in the underlying browser app. This makes them universal: they will invoke the same response on any web page.
## HowTo: Imitate DefaultActions?
When we call `.preventDefault()` on the event preceding a DefaultAction, we stop that DefaultAction from running. But, what if we change our mind? Can we restart a DefaultAction once `.preventDefault()` has been called?
The simple answer is "no". `.preventDefault()` is a one-way street. There is no method `event.reEnableDefault()`, and it's not possible to set `event.defaultPrevented = false;`. But, even though we cannot re-enable DefaultActions, we might be able to imitate them.
To imitate a DefaultAction simply means to manually reproduce, from scratch in JS, the same functionality as the DefaultAction. But, not all DefaultActions can be imitated, or imitated well. Therefore, we can split DefaultActions into three subgroups:
1. **Imitable**: Imitable DefaultActions, such as `Navigation`, can be imitated successfully.
2. **Shimmable**: Shimmable DefaultActions, such as `Scrolling`, can be imitated, but the imitations does not perform as good as the native DefaultAction would.
3. **Irreplicable**: Irreplicable DefaultActions, such as `NativeContextMenu`, cannot be reproduced from JS.
## List of all DefaultActions
1. `click => Navigation` (Imitable)
The DefaultAction when a user `click`s on a link, is for the browser to navigate to the url described by the link. We call this DefaultAction `Navigation`.
To imitate `Navigation`, simply set `location = clickEvent.target.href;`. For more, see ImitateNavigation in Chapter 8: Routing.
2. `submit => Navigation` (Imitable)
3. `pull => Refresh` (Imitable)
3. `keypress => Refresh` (Imitable)
All the keypress events should be listed under their mouse/touch version??
1. `scroll => Scrolling` ( * (wheel-to-scrollevent-that-eventually-will-)scroll)
2. `touchmove => Scrolling`
1. `contextmenu => ShowDefaultContextMenu`
The DefaultAction when a user right `click` on an element in the DOM, is for the browser to show the native, default context menu relevant for the element. The content of the native, default context menu varies slightly depending on what type of element is right clicked: for example, if you right click on an image, you can open the image itself in a new tab, if you right click on a link, you can for example choose to download the target url or open the target url in a new tab. We call this DefaultAction `ShowDefaultContextMenu`.
`ShowDefaultContextMenu` *cannot* be imitated. The browser *only* shows the default context menu when prompted by a user generated, `isTrusted` mouse or touch event (ie. mouse long-press on Mac, touch long-press in mobile browsers, or right-click on other PCs).
2. `mousedown => TextSelection`
3. `touchstart => TextSelection`
## References
*
## old
However, the default action of browsers is often associated with their own specialized event. Before the browser actually will scroll, it will dispatch a native, composed `scroll` event *after* the `touchmove` event and *before* the task of actually scrolling the viewport. The event order is touchmove (event) -> scroll (event) -> scroll (task). To call `preventDefault()` on the `scroll` event will cancel the scroll task. To call `preventDefault()` on the `touchmove` event will cancel the `scroll` event which in turn will cancel the scroll task.
## the table is not easy to make look good on a phone
defaultAction | trigger event | context premise | can be preventDefault()? | JS reproduction
---|---|---|---|---
navigation | click | on a link | yes | location = "bbc.com"
show context menu | contextmenu | generated by an `isTrusted` right button mouse or touch long-press event or keydown context menu key) | show the context menu | NO
|
Python | UTF-8 | 1,773 | 4.28125 | 4 | [] | no_license | """ https://leetcode.com/problems/sort-characters-by-frequency/description/
451. Sort Characters By Frequency - Medium
08/11/2021 17:21 Accepted https://leetcode.com/submissions/detail/537086251/
Given a string s, sort it in decreasing order based on the frequency of characters, and return the sorted string.
Example 1:
Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input: s = "Aabb"
Output: "bbAa"
Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
Constraints:
1 <= s.length <= 5 * 105
s consists of English letters and digits.
"""
class Solution:
def frequencySort(self, s: str) -> str:
"""
time complexity: O(n)
- O(n) to build the histo
- O(n) to sort the histo
- O(n) to join the list comprehension
space complexity: O(n)
"""
# create a histogram to count the frequency of each character
histogram = {}
for char in s:
histogram[char] = histogram.get(char, 0) + 1
# sort the histogram in descending order
sorted_histogram = sorted(histogram.items(), key=lambda x: x[1], reverse=True)
return "".join([k * v for k, v in sorted_histogram])
if __name__ == '__main__':
# s = "Aabb"
s = "cccaaa"
solution = Solution().frequencySort(s)
print(solution)
|
JavaScript | UTF-8 | 1,239 | 2.59375 | 3 | [] | no_license | import React, { useEffect, useState } from "react";
import journeyImage from "./images/the-Heroines-Journey-map-1024x770.jpg";
import { journeyAreas, quadrantToShow } from "./helpers/journeyAreas";
// this is the service which connects to the json API
import httpGet from "./services/journeyService";
// image and sensitive areas
import Journey from "./components/Journey";
// we are going to read json from the API which is listening
// on por 3000 for the time being
function App() {
const [journey, setJourney] = useState([]);
useEffect(() => {
const loadJourney = async () => {
try {
const res = await httpGet();
setJourney(res.data);
} catch (err) {
console.log(err);
}
};
loadJourney();
console.log("Journey=" + journey);
}, []);
const journeyMap = {
name: "journey",
areas: journeyAreas.map((area, index) => {
const rectArea = {
_id: index,
shape: "rect",
coords: area,
href: "",
quadrant: quadrantToShow[index],
};
return rectArea;
}),
};
console.log("Journey = " + journey);
return <Journey journeys={journey} image={journeyImage} areas={journeyMap} />;
}
export default App;
|
Python | UTF-8 | 517 | 2.921875 | 3 | [
"MIT"
] | permissive | def Monkey(n, M):
if n == 0 or M == 1:
return 0
L = list(map(list, list(enumerate([True] * n, start=1))))
counter = 0
while [L[i][1] for i in range(len(L))].count(True) > (M - 1):
for i in range(len(L)):
if L[i][1] == True:
counter += 1
if counter % M == 0 and L[i][1] == True:
L[i][1] = False
print(L[i][0])
return list(filter(lambda x:x[1] == True, L))
# return L
result = Monkey(41, 3)
print(result)
|
Java | UTF-8 | 2,420 | 3.203125 | 3 | [] | no_license | package org.sugarcubes.serialization;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* https://github.com/stoklund/varint
*
* @author Maxim Butov
*/
public class IntegerVariableLengthEncoding {
/**
* Tests the long value fits 32 bits. I.e. the value can be cast to int and back to long without data loss.
*
* @param value long value
*
* @return true if it can be represented as int
*/
public static boolean fits32(long value) {
return value == (int) value;
}
/**
* Finds the number of significant bits of a signed integer.
* If the highest significant bit is 1, then value is negative, and vice versa.
*
* @param value integer value
*
* @return number of significant bits
*/
public static int numBits(int value) {
int bits = 1;
for (int next, prev = value; (next = prev >> 1) != prev; prev = next) {
bits++;
}
return bits;
}
public static int numBits(long value) {
return fits32(value) ? numBits((int) value) : 32 + numBits((int) (value >> 32));
}
public static void writeIntLeb128(OutputStream out, int value) throws IOException {
writeLongLeb128(out, (long) value);
}
public static void writeLongLeb128(OutputStream out, long value) throws IOException {
int numBits = numBits(value);
int numBytes = (numBits + 6) / 7;
byte[] bytes = new byte[numBytes];
int numBytesMinusOne = numBytes - 1;
for (int n = numBytesMinusOne; n >= 0; n--) {
bytes[n] = (byte) (((int) value) & 0x7F);
value >>= 7;
}
for (int n = 0; n < numBytesMinusOne; n++) {
bytes[n] += 0x80;
}
out.write(bytes);
}
public static int readIntLeb128(InputStream in) throws IOException {
long value = readLongLeb128(in);
if (!fits32(value)) {
throw new IllegalStateException("Not an int32");
}
return (int) value;
}
public static long readLongLeb128(InputStream in) throws IOException {
int b = in.read();
long value = (b & 0x40) == 0x40 ? -1L : 0;
value = (value << 7) + (b & 0x7F);
while ((b & 0x80) == 0x80) {
b = in.read();
value = (value << 7) + (b & 0x7F);
}
return value;
}
}
|
JavaScript | UTF-8 | 1,753 | 2.734375 | 3 | [] | no_license | $( document ).ready(function(){
let $uploadfile = $('#register .upload-profile-image input[type="file"]');
$uploadfile.change(function(){
readURL(this);
});
$("#reg-form").submit(function(event){
let $password = $("#password");
let $confirm = $("#password_pwd");
let $error = $("#confirm_error");
if($password.val() === $confirm.val()){
return true;
}else{
$error.text("Passwords do not match");
event.preventDefault();
}
});
});
function readURL(input) {
if(input.files && input.files[0]){
let reader = new FileReader();
reader.onload = function (e) {
$("#register .upload-profile-image .img").attr('src', e.target.result);
$("#register .upload-profile-image .camera-icon").css({display: "none"});
}
reader.readAsDataURL(input.files[0]);
}
}
//let password = document.querySelector('#password');
//let confirm = document.querySelector('#password_pwd');
//let checkPasswordMatch = document.querySelector()
//function checkpassword () {
// result.innerText = password.value == confirm.value ? 'Matching' : 'Not Matching';
//}
//password.addEventListener('keyup', ()=> {
// if (pass2.value.length != 0) checkpassword();
//})
//
//confirm.addEventListener('keyup', ()=> {
// if (confirm.value.length != 0) checkpassword();
//})
//function checkPasswordMatch() {
// var password = $("#password").val();
// var confirm_pwd = $("#password_pwd").val();
//
// if (password != password_pwd)
// $("#checkPasswordMatch").html("Passwords do not match").addClass('text-danger').removeClass('text-success');
// else
// $("#checkPasswordMatch").html("Passwords match").addClass('text-success').removeClass('text-danger');
//}
|
Java | UTF-8 | 4,230 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package com.messagebus.client.model;
import java.io.Serializable;
/**
* representation a node of the topology
*/
public class Node implements Serializable, Comparable<Node> {
private String nodeId;
private String secret;
private String name;
private String value;
private String parentId;
private String type; //0: exchange 1: queue
private String routerType;
private String routingKey;
private boolean available;
private String appId;
private boolean isInner;
private boolean isVirtual;
private boolean canBroadcast;
private String communicateType;
private String rateLimit;
private String threshold;
private String msgBodySize;
private String ttl;
private String ttlPerMsg;
private String compress;
public Node() {
}
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRouterType() {
return routerType;
}
public void setRouterType(String routerType) {
this.routerType = routerType;
}
public String getRoutingKey() {
return routingKey;
}
public void setRoutingKey(String routingKey) {
this.routingKey = routingKey;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public boolean isVirtual() {
return isVirtual;
}
public void setVirtual(boolean isVirtual) {
this.isVirtual = isVirtual;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public boolean isInner() {
return isInner;
}
public void setInner(boolean isInner) {
this.isInner = isInner;
}
public String getRateLimit() {
return rateLimit;
}
public void setRateLimit(String rateLimit) {
this.rateLimit = rateLimit;
}
public String getCommunicateType() {
return communicateType;
}
public void setCommunicateType(String communicateType) {
this.communicateType = communicateType;
}
public String getThreshold() {
return threshold;
}
public void setThreshold(String threshold) {
this.threshold = threshold;
}
public String getMsgBodySize() {
return msgBodySize;
}
public void setMsgBodySize(String msgBodySize) {
this.msgBodySize = msgBodySize;
}
public String getTtl() {
return ttl;
}
public void setTtl(String ttl) {
this.ttl = ttl;
}
public String getTtlPerMsg() {
return ttlPerMsg;
}
public void setTtlPerMsg(String ttlPerMsg) {
this.ttlPerMsg = ttlPerMsg;
}
public boolean isCanBroadcast() {
return canBroadcast;
}
public void setCanBroadcast(boolean canBroadcast) {
this.canBroadcast = canBroadcast;
}
public String getCompress() {
return compress;
}
public void setCompress(String compress) {
this.compress = compress;
}
@Override
public int compareTo(Node o) {
if (o == null) return -1;
if (this.nodeId.equals(o.getNodeId())) {
return 0;
} else if (Integer.parseInt(this.nodeId) < Integer.parseInt(o.getNodeId())) {
return -1;
} else {
return 1;
}
}
}
|
C++ | UTF-8 | 511 | 2.609375 | 3 | [] | no_license | #ifndef __PhysicsObject_h_
#define __PhysicsObject_h_
class Explosion;
enum PHYSICS_OBJECT_TYPE {
UNDEFINED,
TOWER_CHUNK,
PLATFORM,
PLAYER,
ROCKET
};
class PhysicsObject
{
public:
PhysicsObject()
: type(UNDEFINED)
{}
PhysicsObject(PHYSICS_OBJECT_TYPE type)
: type(type)
{}
virtual ~PhysicsObject() {}
virtual void explode(Explosion *explosion) {};
PHYSICS_OBJECT_TYPE type;
};
#endif // #ifndef __PhysicsObject_h_
|
PHP | UTF-8 | 153 | 3.328125 | 3 | [] | no_license | <?php
$array = ["Andy", "Bety", "Carol"];
// aaray_reverse 要素を逆順にした配列を返す
$reverse = array_reverse($array);
print_r($reverse); |
Markdown | UTF-8 | 1,488 | 3.015625 | 3 | [] | no_license | # CS250
How do I interpret user needs and implement them into a program? How does creating “user stories” help with this?
User needs are first described using face to face interactions with the users, which I then break down into criteria that needs to be met by the product backlog. Creating user stories helps to organize each need into an idividual item that can be easily interpreted by all members of the team. User stories help identify specific functions and features that should be implemented into a program.
How do I approach developing programs? What agile processes do I hope to incorporate into my future development work?
I approach developing programs as a large task that should be broken down into smaller pieces to produce the best possible product. I hope to incorporate Scrum frameworks and sprints into my future development work as opposed to the current waterfall methods of planning almost 100%, development, and then testing. The agile process of simultaneously testing and developing is what I hope to incorporate into my future development work as well.
What does it mean to be a good team member in software development?
Being a good team member in software development means being a focused, active participant and a good communicator. A good team member should meet deadlines and be vocal about impediments that would slow down progress to a project. A good team member should also listen to other team members and offer assistance when needed.
|
C++ | UTF-8 | 2,989 | 2.96875 | 3 | [
"MIT"
] | permissive | //
// Created by Alex on 9/14/2018.
//
#pragma once
#include <stdio.h>
#include "types.hpp"
#include "vector_bit_ops.hpp"
namespace apollo {
typedef size_t FamilyID;
class Family {
private:
std::vector<bool> all_bits_;
std::vector<std::vector<bool>> one_bits_;
std::vector<bool> none_bits_;
template <typename C>
Family& with_one_of_helper(std::vector<bool> bits) {
ComponentType type = Types::component_type<C>();
set_vector_bit(bits, static_cast<size_t>(type));
one_bits_.push_back(bits);
return *this;
}
template <typename C0, typename C1, typename... Args>
Family& with_one_of_helper(std::vector<bool> bits) {
ComponentType type = Types::component_type<C0>();
set_vector_bit(bits, static_cast<size_t>(type));
return with_one_of_helper<C1, Args...>(bits);
}
public:
Family() : all_bits_(), one_bits_(), none_bits_() {}
Family(const Family& other) :
all_bits_(other.all_bits_),
one_bits_(other.one_bits_),
none_bits_(other.none_bits_)
{}
template <typename C>
Family& with_all_of() {
ComponentType type = Types::component_type<C>();
set_vector_bit(all_bits_, static_cast<size_t>(type));
return *this;
}
template <typename C0, typename C1, typename... Args>
Family& with_all_of() {
ComponentType type = Types::component_type<C0>();
set_vector_bit(all_bits_, static_cast<size_t>(type));
return with_all_of<C1, Args...>();
}
template <typename C>
Family& with_one_of() {
return with_one_of_helper<C>(std::vector<bool>());
}
template <typename C0, typename C1, typename... Args>
Family& with_one_of() {
return with_one_of_helper<C0, C1, Args...>(std::vector<bool>());
}
template <typename C>
Family& with_none_of() {
ComponentType type = Types::component_type<C>();
set_vector_bit(none_bits_, static_cast<size_t>(type));
return *this;
}
template <typename C0, typename C1, typename... Args>
Family& with_none_of() {
ComponentType type = Types::component_type<C0>();
set_vector_bit(none_bits_, static_cast<size_t>(type));
return with_none_of<C1, Args...>();
}
bool matches(const std::vector<bool>& bits) const {
if (!vector_check_all(all_bits_, bits)) {
return false;
}
for (auto& one_bits : one_bits_) {
if (!vector_check_one(one_bits, bits)) {
return false;
}
}
if (vector_check_one(none_bits_, bits)) {
return false;
}
return true;
}
};
} |
Ruby | UTF-8 | 370 | 3.96875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
min_val=nil
name_hash.each {|key, value|
min_val=value if min_val==nil || value < min_val
}
name_hash.key(min_val)
end
# hash = {:blake => 500, :ashley => 2, :adam => 1}
# puts key_for_min_value(hash)
|
C# | UTF-8 | 2,478 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | using System.Data;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using Dapper;
using X4_DataExporterWPF.Entity;
namespace X4_DataExporterWPF.Export
{
/// <summary>
/// モジュール建造に関する情報抽出用クラス
/// </summary>
class ModuleProductionExporter : IExporter
{
/// <summary>
/// ウェア情報xml
/// </summary>
private readonly XDocument _WaresXml;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="waresXml">ウェア情報xml</param>
public ModuleProductionExporter(XDocument waresXml)
{
_WaresXml = waresXml;
}
/// <summary>
/// 抽出処理
/// </summary>
/// <param name="cmd"></param>
public void Export(IDbConnection connection)
{
//////////////////
// テーブル作成 //
//////////////////
{
connection.Execute(@"
CREATE TABLE IF NOT EXISTS ModuleProduction
(
ModuleID TEXT NOT NULL,
Method TEXT NOT NULL,
Time REAL NOT NULL,
PRIMARY KEY (ModuleID, Method),
FOREIGN KEY (ModuleID) REFERENCES Module(ModuleID)
) WITHOUT ROWID");
}
////////////////
// データ抽出 //
////////////////
{
var items = _WaresXml.Root.XPathSelectElements("ware[@tags='module']").SelectMany
(
module => module.XPathSelectElements("production").Select
(
prod =>
{
var moduleID = module.Attribute("id")?.Value;
if (string.IsNullOrEmpty(moduleID)) return null;
var method = prod.Attribute("method")?.Value;
if (string.IsNullOrEmpty(method)) return null;
double time = double.Parse(prod.Attribute("time")?.Value ?? "0.0");
return new ModuleProduction(moduleID, method, time);
})
)
.Where
(
x => x != null
);
connection.Execute("INSERT INTO ModuleProduction (ModuleID, Method, Time) VALUES (@ModuleID, @Method, @Time)", items);
}
}
}
}
|
C | UTF-8 | 3,498 | 3.03125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "answer07.h"
Image * Image_load(const char * filename)
{
int read_header;
int read;
//int read1;
int read2;
FILE * fptr = NULL;
ImageHeader header; //= NULL;
Image * img; //= NULL;
fptr = fopen(filename, "rb");
if ( fptr == NULL)
{
return NULL;
}
read_header = fread(&header, sizeof(ImageHeader), 1, fptr);
if (read_header != 1)
{
fprintf(stderr, "Failed to open file '%s'\n", filename);
fclose(fptr);
return NULL;
}
if (header.magic_number != ECE264_IMAGE_MAGIC_NUMBER)
{
fprintf(stderr, "Failed to open file '%s'\n", filename);
fclose(fptr);
return NULL;
}
if (header.width == 0 || header.width > 16000000 || header.height == 0 || header.height > 16000000)
{
fprintf(stderr, "Failed to open file '%s'\n", filename);
fclose(fptr);
return NULL;
}
if (header.comment_len == 0 || header.comment_len > 16000000)
{
fprintf(stderr, "Failed to open file '%s'\n", filename);
fclose(fptr);
return NULL;
}
img = malloc(sizeof(Image));
if (img == NULL)
{
fprintf(stderr, "Failed to open file '%s'\n", filename);
fclose(fptr);
free(img);
return NULL;
}
img->width = header.width;
img->height = header.height;
img->comment = malloc(header.comment_len * sizeof(char));
if (img->comment == NULL)
{
fprintf(stderr, "Failed to open file '%s'\n", filename);
fclose(fptr);
//free(img);
free(img->comment);
free(img);
return NULL;
}
img->data = malloc(sizeof(unsigned char) * img->width * img->height);
if (img ->data == NULL)
{
fprintf(stderr, "Failed to open file '%s'\n", filename);
fclose(fptr);
//free(img);
free(img->comment);
free(img->data);
free(img);
return NULL;
}
read = fread(img->comment, (sizeof(char) * header.comment_len), 1, fptr);
if (read != 1 || img->comment[header.comment_len - 1] != '\0')
{
fclose(fptr);
free(img->comment);
free(img->data);
free(img);
return NULL;
}
read2 = fread(img->data, (sizeof(uint8_t) * header.width * header.height), 1, fptr);
if (read2 != 1)
{
fclose(fptr);
free(img->comment);
free(img->data);
free(img);
return NULL;
}
uint8_t byte_check;
if (fread(&byte_check, sizeof(uint8_t),1 , fptr) != 0)
{
fclose(fptr);
free(img->comment);
free(img->data);
free(img);
return NULL;
}
/*
if (fgetc(fptr) != EOF)
{
return NULL;
}*/
fclose(fptr);
return img;
}
int Image_save(const char * filename, Image * image)
{
ImageHeader header_1;
header_1.magic_number = ECE264_IMAGE_MAGIC_NUMBER;
header_1.width = image->width;
header_1.height = image->height;
header_1.comment_len = strlen(image->comment) + 1;
FILE * fptr = NULL;
fptr = fopen(filename, "w");
if (fptr == NULL)
{
return 0;
}
if (fwrite(&(header_1), sizeof(ImageHeader), 1, fptr) != 1)
{
fclose(fptr);
return 0;
}
if (fwrite((image->comment), sizeof(char), header_1.comment_len , fptr) != header_1.comment_len)
{
fclose(fptr);
return 0;
}
if (fwrite((image->data), sizeof(unsigned char) * header_1.height * header_1.width, 1, fptr) != 1)
{
fclose(fptr);
return 0;
}
fclose(fptr);
return 1;
}
void Image_free(Image * image)
{
if (image != NULL)
{
free(image->data);
free(image->comment);
free(image);
}
}
void linearNormalization(int width, int height, uint8_t * intensity)
{
int ind;
int minimum = intensity[0];
int maximum = intensity[0];
int lcv;
for (ind = 0; ind < width * height; ind++)
{
if (minimum > intensity[ind])
{
minimum = intensity[ind];
}
if (maximum < intensity[ind])
{
maximum = intensity[ind];
}
}
for (lcv = 0; lcv < width * height; lcv++)
{
intensity[lcv] = (intensity[lcv] - minimum) * 255.0 / (maximum - minimum);
}
}
|
C++ | UTF-8 | 1,978 | 3.09375 | 3 | [] | no_license | #include "Camera.h"
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtc/matrix_transform.hpp>
//The up vector is inverted because of vulkans inverted y-axis
const glm::vec3 UP_VECTOR = glm::vec3(0.0f, -1.0f, 0.0f);
const glm::vec3 FORWARD_VECTOR = glm::vec3(0.0f, 0.0f, 1.0f);
Camera::Camera()
: m_Projection(1.0f),
m_ProjectionInv(1.0f),
m_View(1.0f),
m_ViewInv(1.0f),
m_Position(0.0f),
m_Rotation(0.0f),
m_Direction(0.0f),
m_Right(0.0f),
m_Up(0.0f),
m_IsDirty(true)
{
}
void Camera::setDirection(const glm::vec3& direction)
{
m_Direction = glm::normalize(direction);
calculateVectors();
m_IsDirty = true;
}
void Camera::setPosition(const glm::vec3& position)
{
m_Position = position;
m_IsDirty = true;
}
void Camera::setProjection(float fovDegrees, float width, float height, float nearPlane, float farPlane)
{
m_Projection = glm::perspective(glm::radians(fovDegrees), width / height, nearPlane, farPlane);
m_ProjectionInv = glm::inverse(m_Projection);
}
void Camera::setRotation(const glm::vec3& rotation)
{
m_Rotation = rotation;
m_Rotation.x = std::max(std::min(m_Rotation.x, 89.0f), -89.0f);
glm::mat3 rotationMat = glm::eulerAngleYXZ(glm::radians(m_Rotation.y), glm::radians(m_Rotation.x), glm::radians(m_Rotation.z));
m_Direction = glm::normalize(rotationMat * FORWARD_VECTOR);
calculateVectors();
m_IsDirty = true;
}
void Camera::rotate(const glm::vec3& rotation)
{
setRotation(m_Rotation + rotation);
}
void Camera::translate(const glm::vec3& translation)
{
m_Position += (m_Right * translation.x) + (m_Up * translation.y) + (m_Direction * translation.z);
m_IsDirty = true;
}
void Camera::update()
{
if (m_IsDirty)
{
//Update view
m_View = glm::lookAt(m_Position, m_Position + m_Direction, m_Up);
m_ViewInv = glm::inverse(m_View);
m_IsDirty = false;
}
}
void Camera::calculateVectors()
{
m_Right = glm::normalize(glm::cross(m_Direction, UP_VECTOR));
m_Up = glm::normalize(glm::cross(m_Right, m_Direction));
}
|
Java | UTF-8 | 257 | 1.820313 | 2 | [] | no_license | package com.ncu.outpatient.service;
import com.ncu.pojo.common.Employee;
/**
* @author : 城南有梦
* @date : 2020-07-17 22:13:19
* @description:
*/
public interface EmployeeService {
Employee findByNameAndDepart(String name,String departId);
}
|
C# | UTF-8 | 840 | 3 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace PracticeHW6
{
public class CarSales
{
//vin,make,color,year,model,sale_price
public string vin { get; set; }
public string make { get; set; }
public string color { get; set; }
public string year { get; set; }
public string model { get; set; }
public string sale_price { get; set; }
public CarSales()
{
vin = string.Empty;
make = string.Empty;
color = string.Empty;
year = string.Empty;
model = string.Empty;
sale_price = string.Empty;
}
public override string ToString()
{
return $"{year} {make} - {model} {color}";
}
}
}
|
Java | UTF-8 | 8,071 | 1.742188 | 2 | [] | no_license | /**
*/
package org.odysseus.models.socialnetwork.media.impl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import org.odysseus.models.socialnetwork.activity.ActivityPackage;
import org.odysseus.models.socialnetwork.activity.impl.ActivityPackageImpl;
import org.odysseus.models.socialnetwork.media.MediaData;
import org.odysseus.models.socialnetwork.media.MediaFactory;
import org.odysseus.models.socialnetwork.media.MediaPackage;
import org.odysseus.models.socialnetwork.media.MediaType;
import org.odysseus.models.socialnetwork.user.UserPackage;
import org.odysseus.models.socialnetwork.user.impl.UserPackageImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class MediaPackageImpl extends EPackageImpl implements MediaPackage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass mediaDataEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EEnum mediaTypeEEnum = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see org.odysseus.models.socialnetwork.media.MediaPackage#eNS_URI
* @see #init()
* @generated
*/
private MediaPackageImpl() {
super(eNS_URI, MediaFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
*
* <p>This method is used to initialize {@link MediaPackage#eINSTANCE} when that field is accessed.
* Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static MediaPackage init() {
if (isInited) return (MediaPackage)EPackage.Registry.INSTANCE.getEPackage(MediaPackage.eNS_URI);
// Obtain or create and register package
MediaPackageImpl theMediaPackage = (MediaPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof MediaPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new MediaPackageImpl());
isInited = true;
// Obtain or create and register interdependencies
ActivityPackageImpl theActivityPackage = (ActivityPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(ActivityPackage.eNS_URI) instanceof ActivityPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(ActivityPackage.eNS_URI) : ActivityPackage.eINSTANCE);
UserPackageImpl theUserPackage = (UserPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(UserPackage.eNS_URI) instanceof UserPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(UserPackage.eNS_URI) : UserPackage.eINSTANCE);
// Create package meta-data objects
theMediaPackage.createPackageContents();
theActivityPackage.createPackageContents();
theUserPackage.createPackageContents();
// Initialize created meta-data
theMediaPackage.initializePackageContents();
theActivityPackage.initializePackageContents();
theUserPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theMediaPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(MediaPackage.eNS_URI, theMediaPackage);
return theMediaPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getMediaData() {
return mediaDataEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getMediaData_Name() {
return (EAttribute)mediaDataEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getMediaData_Type() {
return (EAttribute)mediaDataEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getMediaData_Content() {
return (EAttribute)mediaDataEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getMediaData_UploadDate() {
return (EAttribute)mediaDataEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EEnum getMediaType() {
return mediaTypeEEnum;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MediaFactory getMediaFactory() {
return (MediaFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
// Create classes and their features
mediaDataEClass = createEClass(MEDIA_DATA);
createEAttribute(mediaDataEClass, MEDIA_DATA__NAME);
createEAttribute(mediaDataEClass, MEDIA_DATA__TYPE);
createEAttribute(mediaDataEClass, MEDIA_DATA__CONTENT);
createEAttribute(mediaDataEClass, MEDIA_DATA__UPLOAD_DATE);
// Create enums
mediaTypeEEnum = createEEnum(MEDIA_TYPE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents() {
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
// Initialize classes, features, and operations; add parameters
initEClass(mediaDataEClass, MediaData.class, "MediaData", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getMediaData_Name(), ecorePackage.getEString(), "name", null, 0, 1, MediaData.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getMediaData_Type(), this.getMediaType(), "type", "IMAGE", 0, 1, MediaData.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getMediaData_Content(), ecorePackage.getEByteArray(), "content", null, 0, 1, MediaData.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getMediaData_UploadDate(), ecorePackage.getEDate(), "uploadDate", null, 0, 1, MediaData.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
// Initialize enums and add enum literals
initEEnum(mediaTypeEEnum, MediaType.class, "MediaType");
addEEnumLiteral(mediaTypeEEnum, MediaType.IMAGE);
addEEnumLiteral(mediaTypeEEnum, MediaType.VIDEO);
addEEnumLiteral(mediaTypeEEnum, MediaType.AUDIO);
// Create resource
createResource(eNS_URI);
}
} //MediaPackageImpl
|
Python | UTF-8 | 1,639 | 3.03125 | 3 | [] | no_license | #Format Data for frontend data from google/kaggle style output
import csv
confereceOrder = ("W", "X", "Z", "Y")
teams = {}
with open('kaggle_data/MTeams.csv') as file:
csv_reader = csv.reader(file, delimiter=',')
for line in csv_reader:
teams[str(line[0])] = str(line[1])
def format(data):
games = []
for round in range(1,5):
for conference in confereceOrder:
for g in getOrder(round):
game = "R" + str(round) + conference + str(g)
row = data.loc[data['Slot'] == game]
if round == 1 or g == 1:
games.append(row.iloc[0]["TeamID_x"])
games.append(row.iloc[0]["TeamID_y"])
else:
games.append(row.iloc[0]["TeamID_y"])
games.append(row.iloc[0]["TeamID_x"])
#Cross region games
row = data.loc[data['Slot'] == "R5WX"]
games.append(row.iloc[0]["TeamID_x"])
games.append(row.iloc[0]["TeamID_y"])
row = data.loc[data['Slot'] == "R5YZ"]
games.append(row.iloc[0]["TeamID_y"])
games.append(row.iloc[0]["TeamID_x"])
row = data.loc[data['Slot'] == "R6CH"]
games.append(row.iloc[0]["TeamID_x"])
games.append(row.iloc[0]["TeamID_y"])
games.append(row.iloc[0]["Winner"])
return getTeamNames(games)
def getTeamNames(games):
names = []
for g in games:
names.append(teams[str(int(g))])
return names
def getOrder(round):
if round == 1:
return [1,8,5,4,6,3,7,2]
elif round == 2:
return [1,4,3,2]
elif round == 3:
return [1,2]
else:
return [1]
|
Markdown | UTF-8 | 4,322 | 2.734375 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: 我的软件使用汇总
description: Some Description
date: 2014-03-04 11:16:24 +08:00
tags: "Software"
---
## 我的软件使用汇总
### 效率软件
**AutoHotkey**:AutoHotkey是简易而功能强大的热键脚本语言,由于十分的强大,所以我使用的也只是一部分而已,基本上是要用到才去学习。
目前使用:
* 快捷键打开软件。定义快捷键来批量打开和关闭软件,减少鼠标重复劳动。
* 便捷搜索:你只需要选取文本,使用Alt+b和Alt+g来打开网页进行百度和Google的搜索,不需要重复以前的打开网页,再进行输入。
* 重定义快捷键:这个不如Mac修改快捷键方便,但是在win下修改也是很好用的。Evernote的高亮快捷键是Ctrl+Shift+H,当你在大量使用时就十分不方便,我将之修改为Alt+H,轻松便捷。
基本使用就这么多,后期会再根据自己的使用情况来进行功能添加。
**Evernote**:这个不用多说,经典的笔记应用软件,多平台同步,必备软件。我通常用它来进行PKM管理,个人计划回顾等,将它当成一个生活库来使用。
**Pocket**:与Evernote配套成收集整理工具。使用Pocket是比较后面的事情,原先的想法是看文章何必要缓存到一个地方呢?我随时上网随时看。但是,当每天的时间紧凑,不够时间来浏览文章的时候,Pocket的用处就体现出来了。将微信上和feedly,知乎日报的文章保存进去,在公交车时间看。可惜的是自己的消化能力不够,无法及时的消化,容易造成文章堆积。
**Doit.im**:我付费的GTD软件,可以比较好的进行任务管理,也是多平台同步的。每天我在这上面安排我的工作计划,清空我的头脑,让我更有效率的工作。之前是想使用Omnifocus,但是iPhone丢失,所以转战了。发现Doit的Android版本有个很好用的收集功能,下拉通知栏就能够快速输入,可以很方便的收集想法。
**Wiz**:主要用来记录工作遇到的问题,每日的工作笔记。由于已经有Evernote了,所以也没有过多的开发这个的功能。
**atimelooger**:时间记录软件,我将自己的每日生活时间给分类掉,然后利用这个软件来进行时间记录,每日导入excel中,每周对自己的时间进行分析,掌握一个时间的大体走向。在奇特的一生当中,柳比歇夫的记录方法让我很感兴趣,可惜我没有办法做到像他那么细致,不过可以慢慢的改善,最终掌控自己的时间。
**RescueTime**:同时间记录软件,不过是在PC机上的。能够记录在电脑上的所有操作,使用软件,打开什么网站等。内有分类,主要是用来计算时间效率的分类。每周发送一次报告,报告能够解析你的时间效率。这个暂时还没有去研究,所以效率时间不够精确,只能以后再说。
**Ditto**:电脑上必备软件,用于多次复制黏贴使用,不用再重复性的点击-复制-点窗口-复制的操作了,一次性复制完,然后再慢慢黏贴。
**everything**: win下的搜索文件工具,比自带的不知道好用多少倍,速度快!
**XorTime**:番茄时钟软件,这个我只用番茄功能,来提醒我50分钟休息一次,能够记录一天使用了多少番茄。
### 常用软件
**CCleaner**:清理垃圾软件,不用套装软件。
**1Password**:主力的密码记录软件,通过dropbox来进行同步,可生成复杂的随机密码,让你的密码更安全,只需要记住一个打开密码即可。
**XMind 2013**: 简单易用的MindMap软件,不喜欢用mindmanager,感觉太大太繁琐了,Xmind十分的小巧,而且操作也好用,两个系统都用它。
**dropbox**:同步网盘,重要的excel记录,mindmap文件等都放在上面,虽然空间比较小,但是却放着我重要的文件。
**360网盘**:资料和pdf保存,偶尔使用。
**MarkdownPad 2**:以前使用Mou,现在使用它。把写博客,写每日工作记录(保存在wiz上的),思考和总结等都在上面写了,然后保存在各种地方,软件很好的做了一个过度的作用。
暂时这么多,以后再添加。
|
C++ | UTF-8 | 1,361 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include <queue>
#include <vector>
#include <memory.h>
using namespace std;
int N, M, res = 987654321;
int p[1001][1001]; // 0 : 지나갈 수 있음, 1 : 벽 또는 불
int visit[1001][1001];
int dx[4] = { -1,0,0,1 };
int dy[4] = { 0,-1,1,0 };
int jx, jy;
queue<pair<int, int>> q;
void bfs() {
q.push({ jx,jy });
visit[jx][jy] = 1;
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
q.pop();
if (p[x][y] == 0 && (x == 1 || x == N || y == 1 || y == M)) {
res = visit[x][y];
return;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx<1 || ny < 1 || nx>N || ny>M) continue;
if (p[nx][ny] == 1) continue;
if (visit[nx][ny] == -1) {
visit[nx][ny] = visit[x][y] + 1;
p[nx][ny] = p[x][y];
q.push({ nx,ny });
}
}
}
}
int main()
{
cin >> N >> M;
memset(visit, -1, sizeof(visit));
for (int i = 1; i <= N; i++) {
string str;
cin >> str;
for (int j = 1; j <= M; j++) {
if (str[j - 1] == '#')
p[i][j] = 1;
else if (str[j - 1] == 'F') {
p[i][j] = 1;
q.push({ i,j });
visit[i][j] = 0;
}
else if (str[j - 1] == 'J') {
p[i][j] = 0;
jx = i, jy = j;
}
else
p[i][j] = 0;
}
}
bfs();
if (res == 987654321)
cout << "IMPOSSIBLE";
else
cout << res;
} |
Java | UTF-8 | 4,197 | 3.015625 | 3 | [] | no_license | import java.util.Scanner;
public class pokerHands
{
private static Scanner scanner=new Scanner(System.in); static{scanner.useDelimiter(System.getProperty("line.separator"));}
public static void main(String[] args)
{
int numCards = 0;
int r1 = 0;
int r2 = 0;
int r3 = 0;
int r4 = 0;
int r5 = 0;
int s1 = 0;
int s2 = 0;
int s3 = 0;
int s4 = 0;
int s5 = 0;
int lowest = r1;
int lowest2nd = r2;
int medium = r3;
int highest2nd = r4;
int highest = r5;
int tmp;
String result = "";
while (numCards < 5) {
System.out.print("Enter Rank: ");
String r = System.console().readLine();
System.out.print("Enter Suit: ");
String s = System.console().readLine();
int rValue = 0;
int sValue = 0;
boolean rCorrect = true;
boolean sCorrect = true;
if (r.equals("1") || r.equals("2") || r.equals("3") || r.equals("4") || r.equals("5") ||
r.equals("6") || r.equals("7") || r.equals("8") || r.equals("9") || r.equals("10") ||
r.equals("11")) {
rValue = Integer.parseInt(r);
} else if (r.equals("J")) {
rValue = 11;
} else if (r.equals("Q")) {
rValue = 12;
} else if (r.equals("K")) {
rValue = 13;
} else {
rCorrect = false;
}
if (numCards == 0) {
r1 = rValue;
lowest = rValue;
} else if (numCards == 1) {
r2 = rValue;
lowest2nd = rValue;
} else if (numCards == 2) {
r3 = rValue;
medium = rValue;
} else if (numCards == 3) {
r4 = rValue;
highest2nd = rValue;
} else {
r5 = rValue;
highest = rValue;
}
if (s.equals("spades") || s.equals("hearts") || s.equals("diamonds") || s.equals("clubs")) {
if (s.equals("spades")) {
sValue = 1;
} else if (s.equals("hearts")) {
sValue = 2;
} else if (s.equals("diamonds")) {
sValue = 3;
} else {
sValue = 4;
}
} else {
sCorrect = false;
}
if (numCards == 0) {
s1 = sValue;
} else if (numCards == 1) {
s2 = sValue;
} else if (numCards == 2) {
s3 = sValue;
} else if (numCards == 3) {
s4 = sValue;
} else {
s5 = sValue;
}
if (rCorrect && sCorrect) {
numCards += 1;
} else {
System.out.println("Invalid input!");
}
}
// sort ranks
int loops = 0;
while (loops < 5) {
if (lowest > lowest2nd) {
tmp = lowest2nd;
lowest2nd = lowest;
lowest = tmp;
}
if (lowest2nd > medium) {
tmp = medium;
medium = lowest2nd;
lowest2nd = tmp;
}
if (medium > highest2nd) {
tmp = highest2nd;
highest2nd = medium;
medium = tmp;
}
if (highest2nd > highest) {
tmp = highest;
highest = highest2nd;
highest2nd = tmp;
}
loops++;
}
// consecutive?
boolean consec = false;
if (lowest == lowest2nd - 1 && lowest2nd == medium - 1 && medium == highest2nd - 1 &&
highest2nd == highest - 1) {
consec = true;
}
// how many same rank?
int sameRank = 0;
if (lowest == lowest2nd) {
sameRank = sameRank + 2;
}
if (lowest2nd == medium) {
sameRank++;
}
if (medium == highest2nd) {
sameRank++;
}
if (highest2nd == highest) {
sameRank++;
}
// sort suits
lowest = s1;
lowest2nd = s2;
medium = s3;
highest2nd = s4;
highest = s5;
loops = 0;
while (loops < 5) {
if (lowest > lowest2nd) {
tmp = lowest2nd;
lowest2nd = lowest;
lowest = tmp;
}
if (lowest2nd > medium) {
tmp = medium;
medium = lowest2nd;
lowest2nd = tmp;
}
if (medium > highest2nd) {
tmp = highest2nd;
highest2nd = medium;
medium = tmp;
}
if (highest2nd > highest) {
tmp = highest;
highest = highest2nd;
highest2nd = tmp;
}
loops++;
}
// same suits?
int sameSuits = 0;
if (s1 == s2 && s2 == s3 && s3 == s4 && s4 == s5) {
sameSuits = 5;
} else if (s1 == s2 && s2 == s3 && s3 == s4 ||
s2 == s3 && s3 == s4 && s4 == s5) {
sameSuits = 4;
} else if (s1 == s2 && s2 == s3 ||
s2 == s3 && s3 == s4 ||
s3 == s4 && s4 == s5) {
sameSuits = 3;
} else if (s1 == s2 ||
s2 == s3 ||
s3 == s4 ||
s4 == s5) {
sameSuits = 2;
}
// Result
if (sameSuits == 5 && consec) {
result = "Straight flush";
} else if (sameRank == 4) {
result = "Poker";
//} else if (
} else if (sameSuits == 5) {
result = "Flush";
} else if (consec) {
result = "Straight";
} else if (sameRank == 3) {
result = "Three of a kind";
} else if (sameRank == 2) {
result = "Two pairs";
}
System.out.print("Result: " + result);
}}
|
Markdown | UTF-8 | 4,397 | 3.9375 | 4 | [] | no_license | # 创建具有不同类型项的列表
我们通常需要创建显示不同类型内容的列表。例如,我们可能正在处理一个列表,该列表显示一个标题,后面跟着几个与标题相关的项,然后是另一个标题,依此类推。
我们怎样才能创造出这样一种Flutter的结构呢?
## 指南
1、使用不同类型的项创建数据源
2、将数据源转换为小部件列表
## 1、使用不同类型的项创建数据源
为了在列表中表示不同类型的项,我们需要为每种类型的项定义一个类。
在本例中,我们将开发一个应用程序,它显示一个标题,后面跟着五个消息。因此,我们将创建三个类:`ListItem`、`HeadingItem`和`MessageItem`。
```dart
//可以包含的不同类型项的基类
abstract class ListItem {}
//包含显示标题的数据的ListItem
class HeadingItem implements ListItem {
final String heading;
HeadingItem(this.heading);
}
// 包含显示消息的数据的ListItem
class MessageItem implements ListItem {
final String sender;
final String body;
MessageItem({this.sender,this.body});
}
```
大多数情况下,我们会从互联网或本地数据库中获取数据,并将这些数据转换为项目列表。
对于本例,我们将生成要使用的列表。该列表将包含一个标题,后面是五条消息。然后重复。
```dart
final items = new List<ListItem>.generate(
1200,
(i) => i % 6 == 0
? HeadingItem("Heading ${i}")
: MessageItem("Sender ${i}", "Message body ${i}")
);
```
## 2、将数据源转换为小部件列表
为了将每个项转换为Widget,我们将使用[`ListView.Builder`](https://docs.flutter.io/flutter/widgets/ListView/ListView.builder.html)构造函数。
通常,我们希望提供一个`builder`函数来检查我们所处理的项目的类型,并为该类型的项返回适当的Widget。
在本例中,使用`is`关键字检查我们正在处理的项的类型是很方便的。它很快,并将自动将每个项目转换为适当的类型。但是,如果您喜欢另一种模式,则有不同的方法来处理这个问题!
```dart
new ListView.builder(
itemCoount: items.length,
itemBuilder: (context, index){
final item = items[index];
if(item is HeadingItem){
return new ListTile(
titll: new Text(
item.heading,
style: Theme.of(context).textTheme.headline
)
);
}else if(item is MessageItem){
return new ListTile(
title: new Text(item.sender),
subtitle: new Text(item.body)
);
}
}
)
```
## 完整示例
```dart
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main(){
runApp(new MyApp(
items: new List<ListItem>.generate(
1200,
(i) => i % 6 == 0
? HeadingItem("Heading ${i}")
: MessageItem("Sender ${i}", "Message body ${i}")
)
}
class MyApp extends StatelessWidget {
final List<ListItem> items;
MyApp({Key: key, @required this.items}) : super(key:key);
@override
Widget build(BuildContext context){
final title = 'Mixed List';
return new MaterialApp(
title: title,
home: new Scaffold(
appBar: new AppBar(
title: new Text(title),
),
body: new ListView.builder(
itemCount: items.length,
itemBuilder: (context, index){
final item = items[index];
if(item is HeadingItem){
return new ListTile(
titll: new Text(
item.heading,
style: Theme.of(context).textTheme.headline
)
);
}else if(item is MessageItem){
return new ListTile(
title: new Text(item.sender),
subtitle: new Text(item.body)
);
}
}
)
)
);
}
}
//可以包含的不同类型项的基类
abstract class ListItem {}
//包含显示标题的数据的ListItem
class HeadingItem implements ListItem {
final String heading;
HeadingItem(this.heading);
}
// 包含显示消息的数据的ListItem
class MessageItem implements ListItem {
final String sender;
final String body;
MessageItem({this.sender,this.body});
}
```
 |
PHP | UTF-8 | 4,988 | 2.546875 | 3 | [] | no_license | <?php
include ROOT_PATH . '/plugin/wx-pay/index.php';
include_once ROOT_PATH . '/core/utils.php';
class Order extends WxPay {
private $empty;
private $cookieValid;
private $config;
public function __construct($config) {
parent::__construct($config['DB_NAME'], $config['DB_USR'], $config['DB_PWD']);
$this->cookieValid = $config['COOKIE_VALID'];
$this->config = $config;
}
private function selectCookie($userId, $cookie) {
return $this->query("SELECT `id`,`login_time`,`cookie` FROM `ekm_auth_user` WHERE `id` = ? AND `cookie` = ?", [$userId, $cookie]);
}
private function getOpenid($code) {
$ret = Utils::httpRequest('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->config['APP_ID'] .
'&secret=' . $this->config['APP_SECRET'] . '&code=' . $code . '&grant_type=authorization_code');
if ($ret['errcode']) {
return false;
} else {
return $ret['openid'];
}
}
private function buy($params) {
if (Utils::isEmpty($params['user'], $params['product'], $params['cookie'])) {
$ret = $this->empty;
} else {
$resUser = $this->selectCookie($params['user'], $params['cookie']);
if ($resUser === false) {
$ret = Utils::ret(-310001, Utils::ERR_DB);
} else if (empty($resUser)) {
$ret = Utils::ret(-310002, 'invalid cookie');
} else if ($resUser[0]['login_time'] + $this->cookieValid < time()) {
$ret = Utils::ret(-310003, 'cookie expired');
} else {
$resItem = $this->query('SELECT * FROM `ekm_item_info` WHERE `id`=?', [$params['product']]);
if ($resItem === false) {
$ret = Utils::ret(-310004, Utils::ERR_DB);
} else if (empty($resItem)) {
$ret = Utils::ret(-310005, 'undefined product');
} else {
$resItem = $resItem[0];
$resProduct = $this->query('SELECT * FROM `ekm_item_main` WHERE `id`=?',
[$resItem['sort']]);
if ($resProduct === false) {
$ret = Utils::ret(-310006, Utils::ERR_DB);
} else if (empty($resProduct)) {
$ret = Utils::ret(-310007, 'undefined sort');
} else {
$resProduct = $resProduct[0];
$ret = $this->newOrder($resItem['name'] . '-' . $resProduct['name'], $params['user'],
$params['product'], $resItem['price'], $params['remark'] ? $params['remark'] : '/');
}
}
}
}
return $ret;
}
public function get($e, $params) {
$this->empty = Utils::ret(-300002, Utils::ERR_EMPTY_PARAM);
switch ($e[0] ? $e[0] : '') {
case 'buy':
$ret = $this->buy($params);
break;
case 'checkOrder':
if (Utils::isEmpty($params['order'])) {
$ret = $this->empty;
} else {
$res = $this->query('SELECT * FROM `ekm_order` WHERE `order` = ?', [$params['order']]);
if ($res === false) {
$ret = Utils::ret(-330002, Utils::ERR_DB);
} else if (empty($res)) {
$ret = Utils::ret(-330001, 'undefined order');
} else {
$ret = $this->checkOrder($params['order']);
}
}
break;
case 'getOrder':
if (Utils::isEmpty($params['order'])) {
$ret = $this->empty;
} else {
$order = $this->query('SELECT * FROM `ekm_order` WHERE `order` = ?', [$params['order']]);
if ($order === false) {
$ret = Utils::ret(-320002, Utils::ERR_DB);
} else if (empty($order)) {
$ret = Utils::ret(-320001, 'undefined order');
} else {
$order = $order[0];
$resUser = $this->query('SELECT `id`,`user`,`wechat` FROM `ekm_auth_user` WHERE `id`=?',
[$order['user']]);
$resUser = $resUser[0];
$order['user'] = $resUser;
$ret = Utils::ret(0, $order);
}
}
break;
case 'getUserOrder':
if (Utils::isEmpty($params['user'], $params['cookie'])) {
$ret = $this->empty;
} else {
$res = $this->selectCookie($params['user'], $params['cookie']);
if ($res === false) {
$ret = Utils::ret(-330001, Utils::ERR_DB);
} else if (empty($res)) {
$ret = Utils::ret(-330002, Utils::ERR_COOKIE_INVALID);
} else {
$res = $this->query('SELECT * from `ekm_order` WHERE `user` = ?', [$params['user']]);
if ($res === false) {
$ret = Utils::ret(-330003, Utils::ERR_DB);
} else {
$ret = Utils::ret(0, $res);
}
}
}
break;
case 'generateOrder':
if (Utils::isEmpty($params['order'], $params['code'])) {
$ret = $this->empty;
} else {
$res = $this->query('SELECT * from `ekm_order` WHERE `order` = ?', [$params['order']]);
if ($res === false) {
$ret = Utils::ret(-340001, Utils::ERR_DB);
} else if (empty($res)) {
$ret = Utils::ret(-340002, 'undefined order');
} else {
$res = $res[0];
$openid = $this->getOpenid($params['code']);
if ($openid) {
$ret = $this->generateOrder($res['name'], $res['user'], $res['price'], $res['order'], $openid);
} else {
$ret = Utils::ret(-340003, 'invalid code');
}
}
}
break;
default:
$ret = Utils::ret(-300001, 'request denied');
break;
}
return $ret;
}
} |
C | UTF-8 | 14,984 | 2.609375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../headers/util.h"
#include "../headers/syntactic.h"
#include "../headers/domain.h"
Token *crtTk, *consumedTk;
Symbols *symbols;
Symbol *crtFunc;
Symbol *crtStruct;
int crtDepth;
int expr();
int stm();
int stmCompound();
int declVar();
int typeName();
int consume(int code) {
if(crtTk->code == code) {
consumedTk=crtTk;
crtTk=crtTk->next;
return 1;
}
return 0;
}
Symbol *addSymbol(Symbols *symbols, const char *name, int cls) {
Symbol *s;
if(symbols->end == symbols->after) {
int count = symbols->after - symbols->begin;
int n = count * 2;
if(n == 0) {
n = 1;
}
symbols->begin = (Symbol**)realloc(symbols->begin, n*sizeof(Symbols*));
if(symbols->begin == NULL) {
err("not enough memory");
}
symbols->end = symbols->begin+count;
symbols->after = symbols->begin+n;
}
SAFEALLOC(s, Symbol);
*symbols->end++=s;
s->name=name;
s->cls=cls;
s->depth=crtDepth;
return s;
}
Symbol *findSymbol(Symbols *symbols, const char *name) {
int i, n;
n=symbols->end-symbols->begin;
for(i=n-1; i>=0; i--) {
if(strcmp(symbols->begin[i]->name, name) == 0) {
return symbols->begin[i];
}
}
return NULL;
}
void deleteSymbolsAfter(Symbols *symbols, Symbol *start) {
int i, n = symbols->end - symbols->begin;
for (i = n - 1; i >= 0; i--) {
if (strcmp(symbols->begin[i]->name, start->name) != 0) {
free(symbols->begin[i]);
symbols->begin[i] = NULL;
}
else {
break;
}
}
symbols->end = &symbols->begin[i+1];
}
void addVariableSymbol(Token *token, Type *t) {
Symbol *s;
if (crtStruct) {
if (findSymbol(&crtStruct->members, token->text)) {
tkerr(crtTk, "symbol redefinition: %s", token->text);
}
s = addSymbol(&crtStruct->members, token->text, CLS_VAR);
}
else if (crtFunc) {
s = findSymbol(symbols, token->text);
if (s && s->depth == crtDepth) {
tkerr(crtTk, "symbol redefinition: %s", token->text);
}
s = addSymbol(symbols, token->text, CLS_VAR);
s->mem = MEM_LOCAL;
}
else {
if (findSymbol(symbols, token->text)) {
tkerr(crtTk, "symbol redefinition: %s", token->text);
}
s = addSymbol(symbols, token->text, CLS_VAR);
s->mem = MEM_GLOBAL;
}
s->type = *t;
}
void initSymbols(Symbols *symbols) {
symbols->begin = symbols->end = symbols->after = NULL;
}
void printSymbols(Symbols *symbols) {
int i;
int n = symbols->end - symbols->begin;
for (i = 0; i < n; i++) {
printf("%s\n", symbolToString(symbols->begin[i]));
}
}
int exprPrimary() {
if(consume(ID)) {
if(consume(LPAR)) {
if(expr()) {
while(1) {
if(consume(COMMA)) {
if(!expr()) tkerr(crtTk, "missing expression after ,");
}
else break;
}
}
if(!consume(RPAR)) tkerr(crtTk, "missing )");
}
return 1;
}
else if(consume(CT_INT) || consume(CT_REAL) || consume(CT_CHAR) || consume(CT_STRING)) {
return 1;
}
else if(consume(LPAR)) {
if(!expr()) tkerr(crtTk, "invalid expression");
if(!consume(RPAR)) tkerr(crtTk, "missing )");
return 1;
}
return 0;
}
int exprPostfix1() {
if(consume(LBRACKET)) {
if(!expr()) tkerr(crtTk, "invalid expression");
if(!consume(RBRACKET)) tkerr(crtTk, "missing ]");
if(!exprPostfix1()) tkerr(crtTk, "missing postfix1 expression");
return 1;
}
else if(consume(DOT)) {
if(!consume(ID)) tkerr(crtTk, "missing ID");
if(!exprPostfix1()) tkerr(crtTk, "missing postfix1 expression");
return 1;
}
return 1;
}
int exprPostfix() {
if(!exprPrimary()) return 0;
if(!exprPostfix1()) tkerr(crtTk, "missing postfix1 expression");
return 1;
}
int exprUnary() {
if(consume(SUB) || consume(NOT)) {
if(!exprUnary()) tkerr(crtTk, "missing unary expression");
return 1;
}
else if(exprPostfix()) {
return 1;
}
return 0;
}
int exprCast() {
Type t;
if(consume(LPAR)) {
if(!typeName(&t)) tkerr(crtTk, "missing type name");
if(!consume(RPAR)) tkerr(crtTk, "missing )");
if(!exprCast()) tkerr(crtTk, "missing cast expression");
return 1;
}
else if(exprUnary()) {
return 1;
}
return 0;
}
int exprMul1() {
if(consume(MUL) || consume(DIV)) {
if(!exprCast()) tkerr(crtTk, "missing cast expression after (*//)");
if(!exprMul1()) tkerr(crtTk, "missing mul1 expression");
return 1;
}
return 1;
}
int exprMul() {
if(!exprCast()) return 0;
if(!exprMul1()) tkerr(crtTk, "missing mul1 expression");
return 1;
}
int exprAdd1() {
if(consume(ADD) || consume(SUB)) {
if(!exprMul()) tkerr(crtTk, "mising mul expression after (+/-)");
if(!exprAdd1()) tkerr(crtTk, "missing add1 expression");
return 1;
}
return 1;
}
int exprAdd() {
if(!exprMul()) return 0;
if(!exprAdd1()) tkerr(crtTk, "missing add1 expression");
return 1;
}
int exprRel1() {
if(consume(LESS) || consume(LESSEQ) || consume(GREATER) || consume(GREATEREQ)) {
if(!exprAdd()) tkerr(crtTk, "missing add expression after (</<=/>/>=)");
if(!exprRel1()) tkerr(crtTk, "missing rel1 expression");
return 1;
}
return 1;
}
int exprRel() {
if(!exprAdd()) return 0;
if(!exprRel1()) tkerr(crtTk, "missing rel1 expression");
return 1;
}
int exprEq1() {
if(consume(EQUAL) || consume(NOTEQ)) {
if(!exprRel()) tkerr(crtTk, "missing rel expression after (==/!=)");
if(!exprEq1()) tkerr(crtTk, "missing eq1 expression");
return 1;
}
return 1;
}
int exprEq() {
if(!exprRel()) return 0;
if(!exprEq1()) tkerr(crtTk, "missing eq1 expression");
return 1;
}
int exprAnd1() {
if(consume(AND)) {
if(!exprEq()) tkerr(crtTk, "missing eq expression after &&");
if(!exprAnd1()) tkerr(crtTk, "missing and1 expression");
return 1;
}
return 1;
}
int exprAnd() {
if(!exprEq()) return 0;
if(!exprAnd1()) tkerr(crtTk, "missing and1 expression");
return 1;
}
int exprOr1() {
if(consume(OR)) {
if(!exprAnd()) tkerr(crtTk, "missing and expression after ||");
if(!exprOr1()) tkerr(crtTk, "missing or1 expression");
return 1;
}
return 1;
}
int exprOr() {
if(!exprAnd()) return 0;
if(!exprOr1()) tkerr(crtTk, "missing or1 expression");
return 1;
}
int exprAssign() {
Token *startTk = crtTk;
if(exprUnary()) {
if(consume(ASSIGN)) {
if(exprAssign()) {
return 1;
}
}
crtTk=startTk;
}
if(exprOr()) {
return 1;
}
return 0;
}
int expr() {
if(!exprAssign()) return 0;
return 1;
}
int ruleIf() {
if(!consume(IF)) return 0;
if(!consume(LPAR)) tkerr(crtTk, "missing ( after if");
if(!expr()) tkerr(crtTk, "invalid condition expression for if");
if(!consume(RPAR)) tkerr(crtTk, "missing )");
if(!stm()) tkerr(crtTk, "missing if statement");
if(consume(ELSE)) {
if(!stm()) tkerr(crtTk, "missing else statement");
}
return 1;
}
int ruleWhile() {
if(!consume(WHILE)) return 0;
if(!consume(LPAR)) tkerr(crtTk, "missing ( after while");
if(!expr()) tkerr(crtTk, "invalid conditional expression for while");
if(!consume(RPAR)) tkerr(crtTk, "missing )");
if(!stm()) tkerr(crtTk, "missing while statement");
return 1;
}
int ruleFor() {
if(!consume(FOR)) return 0;
if(!consume(LPAR)) tkerr(crtTk, "missing ( after for");
expr();
if(!consume(SEMICOLON)) tkerr(crtTk, "missing ; inside for condition");
expr();
if(!consume(SEMICOLON)) tkerr(crtTk, "missing ; inside for condition");
expr();
if(!consume(RPAR)) tkerr(crtTk, "missing )");
if(!stm()) tkerr(crtTk, "missing for statement");
return 1;
}
int ruleBreak() {
if(!consume(BREAK)) return 0;
if(!consume(SEMICOLON)) tkerr(crtTk, "missing ; after break");
return 1;
}
int ruleReturn() {
if(!consume(RETURN)) return 0;
expr();
if(!consume(SEMICOLON)) tkerr(crtTk, "missing ; after return");
return 1;
}
int ruleExprLine() {
expr();
// if(!consume(SEMICOLON)) tkerr(crtTk, "missing ; after expression");
if(consume(SEMICOLON)) {
return 1;
}
return 0;
}
int stm() {
Token *startTk = crtTk;
if(stmCompound() || ruleIf() || ruleWhile() || ruleFor() || ruleBreak() || ruleReturn() || ruleExprLine()) {
return 1;
}
crtTk = startTk;
return 0;
}
int stmCompound() {
Symbol *start = symbols->end[-1];
if(!consume(LACC)) return 0;
crtDepth++;
while(1) {
if(declVar()) {}
else if(stm()) {}
else break;
}
if(!consume(RACC)) tkerr(crtTk, "missing ; or syntax error");
deleteSymbolsAfter(symbols, start);
crtDepth--;
return 1;
}
int arrayDecl(Type *ret) {
if(!consume(LBRACKET)) return 0;
expr();
ret->nElements = 0;
if(!consume(RBRACKET)) tkerr(crtTk, "missing ]");
return 1;
}
int typeBase(Type *ret) {
Token *startTk = crtTk;
Token *tkName;
if (consume(INT)) {
ret->typeBase = TB_INT;
return 1;
}
else if (consume(DOUBLE)) {
ret->typeBase = TB_DOUBLE;
return 1;
}
else if (consume(CHAR)) {
ret->typeBase = TB_CHAR;
return 1;
}
else if(consume(STRUCT)) {
if(!consume(ID)) tkerr(crtTk, "missing struct ID");
tkName = consumedTk;
Symbol *s = findSymbol(symbols, tkName->text);
if (s == NULL) {
tkerr(crtTk, "undefined symbol: %s", tkName->text);
}
if (s->cls != CLS_STRUCT) {
tkerr(crtTk, "%s is not a struct", tkName->text);
}
ret->typeBase = TB_STRUCT;
ret->s = s;
return 1;
}
crtTk = startTk;
return 0;
}
int typeName(Type *ret) {
if(!typeBase(ret)) return 0;
if(arrayDecl(ret) != 1) {
ret->nElements = -1;
}
return 1;
}
int funcArg() {
Type t;
if(!typeBase(&t)) return 0;
if(!consume(ID)) tkerr(crtTk, "missing ID for function argument");
Token *idToken = consumedTk;
if(!arrayDecl(&t)) {
t.nElements = -1;
}
Symbol *s = addSymbol(symbols, idToken->text, CLS_VAR);
s->mem = MEM_ARG;
s->type = t;
s = addSymbol(&crtFunc->args, idToken->text, CLS_VAR);
s->mem = MEM_ARG;
s->type = t;
return 1;
}
int declFunc() {
Token *startTk = crtTk;
Type t;
if(typeBase(&t)) {
if(consume(MUL)) {
t.nElements = 0;
}
else {
t.nElements = -1;
}
if(consume(ID)) {
Token *idToken = consumedTk;
if(consume(LPAR)) {
if (findSymbol(symbols, idToken->text)) {
tkerr(crtTk, "symbol redefinition: %s", idToken->text);
}
crtFunc = addSymbol(symbols, idToken->text, CLS_FUNC);
initSymbols(&crtFunc->args);
crtFunc->type = t;
crtDepth++;
if(funcArg()) {
while(1) {
if(consume(COMMA)) {
if(!funcArg()) tkerr(crtTk, "missing function argument");
}
else break;
}
}
if(!consume(RPAR)) tkerr(crtTk, "missing ) after function");
crtDepth--;
if(!stmCompound()) tkerr(crtTk, "missing function statement");
deleteSymbolsAfter(symbols, crtFunc);
crtFunc = NULL;
return 1;
}
}
}
else if(consume(VOID)) {
t.typeBase = TB_VOID;
if(!consume(ID)) tkerr(crtTk, "missing ID for function");
Token *idToken = consumedTk;
if(!consume(LPAR)) tkerr(crtTk, "missing ( after function");
if (findSymbol(symbols, idToken->text)) {
tkerr(crtTk, "symbol redefinition: %s", idToken->text);
}
crtFunc = addSymbol(symbols, idToken->text, CLS_FUNC);
initSymbols(&crtFunc->args);
crtFunc->type = t;
crtDepth++;
if(funcArg()) {
while(1) {
if(consume(COMMA)) {
if(!funcArg()) tkerr(crtTk, "missing function argument");
}
else break;
}
}
if(!consume(RPAR)) tkerr(crtTk, "missing ) after function");
crtDepth--;
if(!stmCompound()) tkerr(crtTk, "missing function statement");
deleteSymbolsAfter(symbols, crtFunc);
crtFunc = NULL;
return 1;
}
crtTk = startTk;
return 0;
}
int declVar() {
Type t;
if(!typeBase(&t)) return 0;
if(!consume(ID)) tkerr(crtTk, "missing ID");
Token *idToken = consumedTk;
if(arrayDecl(&t) != 1) {
t.nElements = -1;
}
addVariableSymbol(idToken, &t);
while(1) {
if(consume(COMMA)) {
if(!consume(ID)) tkerr(crtTk, "missing variable ID");
Token *idToken = consumedTk;
if(arrayDecl(&t) != 1) {
t.nElements = -1;
}
addVariableSymbol(idToken, &t);
}
else break;
}
if(!consume(SEMICOLON)) tkerr(crtTk, "missing ; after variable declaration");
return 1;
}
int declStruct() {
Token *startTk = crtTk;
if(consume(STRUCT)) {
if(consume(ID)) {
Token *idToken = consumedTk;
if(consume(LACC)) {
if (findSymbol(symbols, idToken->text)) {
tkerr(crtTk, "symbol redefinition: %s", idToken->text);
}
crtStruct = addSymbol(symbols, idToken->text, CLS_STRUCT);
initSymbols(&crtStruct->members);
while(1) {
if(declVar()) {}
else break;
}
if(!consume(RACC)) tkerr(crtTk, "missing } after struct declaration");
if(!consume(SEMICOLON)) tkerr(crtTk, "missing ; after struct");
crtStruct = NULL;
return 1;
}
}
}
crtTk=startTk;
return 0;
}
int unit() {
while(1) {
if(declStruct()) {}
else if(declFunc()) {}
else if(declVar()) {}
else break;
}
if(!consume(END)) tkerr(crtTk, "Failed to reach the END");
return 1;
}
void initSyntactic(Token *start) {
crtTk = start;
consumedTk = NULL;
crtDepth = 0;
SAFEALLOC(symbols, Symbols);
initSymbols(symbols);
}
void syntacticAnalysis(Token *start) {
initSyntactic(start);
unit();
printSymbols(symbols);
} |
Python | UTF-8 | 2,397 | 3.234375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# Import the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the datasheet
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 3].values
# Taking care of missing data
from sklearn.impute import SimpleImputer
# creating object for SimpleImputer class as "imputer"
imputer = SimpleImputer(missing_values = np.nan, strategy = 'mean', verbose=0)
imputer = imputer.fit(X[:, 1:3]) #upper bound is not included, but lower bound
X[:, 1:3] = imputer.transform(X[:, 1:3])
# Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder #LabelEncoder replaces texts by numbers not necessariliy in orders
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder # OneHotEncoder creates dummy variables
labelencoder_X = LabelEncoder()
"""Calling the "LabelEncoder" class by object labelencoder
applying labelencoder object to our required colum "Country" in the datasheet"""
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
columtransformer = ColumnTransformer(
[('one_hot_encoder', OneHotEncoder(categories='auto'), [0])], # The column numbers to be transformed (here is [0] but can be [0, 1, 3])
remainder='passthrough' ) # Leave the rest of the columns untouched
X = columtransformer.fit_transform(X)
# Encoding the dependent Variable
labelencoder_Y = LabelEncoder()
Y = labelencoder_Y.fit_transform(Y)
# Splitting the dataset into training set and test set
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
""" we do not need to do fit_transform for X_test, as they already accodmodate
themselves as per the X_train set (which got fit_transformed)"""
X_test = sc_X.transform(X_test)
"""Feature scaling is not required here for dependent variable Y, because it
is in a categorical classification scale. But we would need to do feature
scaling for dependent variable in case of regression problems as the dependent
variables in regression take place in between high range values. """
|
Python | UTF-8 | 4,887 | 3.296875 | 3 | [
"MIT"
] | permissive | import Image
import ImageDraw
import random
import operator
from collections import defaultdict
import matplotlib.delaunay as triang
import argparse
def edge_color(edg):
'''Returns a valid edge coloring of the given graph in the mathematical
sense. No two edges that are connected by a node share the same color.'''
#generate adjacency list
adj_list = defaultdict(list)
for i in range(0, len(edg)):
adj_list[edg[i][0]].append(i)
adj_list[edg[i][1]].append(i)
#color edges
edg_colors = [-1] * (len(edg) + 1)
for i in range(0, len(edg)):
#hack here to work around Python's lack of a do-while loop
stable_color = False
#loop until we find a 'stable' color
while not stable_color:
#assume that this pass results in a stable color
stable_color = True
#incirment our color
edg_colors[i] += 1
# check against adjacent edges
for edge_id in adj_list[edg[i][0]]:
if (edg_colors[edge_id] == edg_colors[i]) and (edge_id != i):
stable_color = False
for edge_id in adj_list[edg[i][1]]:
if (edg_colors[edge_id] == edg_colors[i]) and (edge_id != i):
stable_color = False
#done
return edg_colors
def generate_hipster_color():
'''Generates a pesudorandom physical color with certian properties.'''
minimum_value = 41
maximum_value = 240
average_value = 162
nudge_step = 10
#create two innital random values
alpha = random.randint(minimum_value, maximum_value)
beta = random.randint(minimum_value, maximum_value)
#try to create thrid value
gamma = average_value * 3 - alpha - beta
#too low?
while gamma < minimum_value:
#nudge alpha and beta down
alpha -= nudge_step
beta -= nudge_step
#recalculate gamma
gamma = average_value * 3 - alpha - beta
#too high?
while gamma > maximum_value:
#nudge alpha and beta down
alpha += nudge_step
beta += nudge_step
#recalculate gamma
gamma = average_value * 3 - alpha - beta
#return color
return (alpha, beta, gamma)
if __name__ == "__main__":
width = 1039 * 4
height = 697 * 4
arc_radius = 20
default_color = (205, 240, 41)
#parse command line arguments
parser = argparse.ArgumentParser(
description='Generate a graph for the back of a business card.')
parser.add_argument('--color-edges', '-c',
help='Individually color the edges', action='store_true')
args = parser.parse_args()
rg = random.randint
kpadding = height * 0.15
points = [(rg(0, int(width - kpadding)),
rg(0, int(height - kpadding))
) for i in range(0, 30)]
im = Image.new("RGB", (width, height))
draw = ImageDraw.Draw(im)
draw.rectangle((0, 0, width, height), fill=(70, 84, 87))
top, bottom, left, right = 10000, 0, 10000, 0
#compute the border of the rectangle bounding all the points
for x, y in points:
if x < left:
left = x
if x > right:
right = x
if y < top:
top = y
if y > bottom:
bottom = y
#figure out the center x and center y of the rectangle
rect_width = (right - left)
center_x = rect_width / 2
rect_height = (bottom - top)
center_y = rect_height / 2
#compute the amount to offset the points by
offset_from_center_x = width / 2 - (center_x) - left
offset_from_center_y = height / 2 - (center_y) - top
#actually offset the points
points = [(x + offset_from_center_x,
y + offset_from_center_y)
for x, y in points]
#compute the delunay triangulation
cens, edg, tri, neig = triang.delaunay([x for x, y in points],
[y for x, y in points])
if args.color_edges:
#perform edge coloring
edg_colors = edge_color(edg)
#remember the physical colors we've used
physical_colors = defaultdict(generate_hipster_color)
#draw the delunay triangulation lines
for i in range(0, len(edg)):
start, end = edg[i]
x = points[start][0]
y = points[start][1]
x2 = points[end][0]
y2 = points[end][1]
if args.color_edges:
draw.line((x, y, x2, y2), fill=physical_colors[edg_colors[i]],
width=4)
else:
draw.line((x, y, x2, y2), fill=default_color, width=4)
#draw the points
for x, y in points:
draw.ellipse((x - arc_radius, y - arc_radius,
x + arc_radius, y + arc_radius), fill=default_color)
#apply antialiasing
im.thumbnail((width / 4, height / 4), Image.ANTIALIAS)
#save
im.save("back.png", "PNG")
|
Java | UTF-8 | 2,285 | 2.390625 | 2 | [] | no_license | package com.hk.mechuri.dtos;
public class filterDto {
private String age10;
private String age20;
private String age30;
private String age40;
private String age50;
private String female;
private String male;
private String catelname;
private String catesname;
private String price;
public filterDto() {super(); }
public filterDto(String age10, String age20, String age30, String age40, String age50, String female, String male,
String catelname, String catesname) {
super();
this.age10 = age10;
this.age20 = age20;
this.age30 = age30;
this.age40 = age40;
this.age50 = age50;
this.female = female;
this.male = male;
this.catelname = catelname;
this.catesname = catesname;
}
public String getAge10() {
return age10;
}
public void setAge10(String age10) {
this.age10 = age10;
}
public String getAge20() {
return age20;
}
public void setAge20(String age20) {
this.age20 = age20;
}
public String getAge30() {
return age30;
}
public void setAge30(String age30) {
this.age30 = age30;
}
public String getAge40() {
return age40;
}
public void setAge40(String age40) {
this.age40 = age40;
}
public String getAge50() {
return age50;
}
public void setAge50(String age50) {
this.age50 = age50;
}
public String getFemale() {
return female;
}
public void setFemale(String female) {
this.female = female;
}
public String getMale() {
return male;
}
public void setMale(String male) {
this.male = male;
}
public String getCatelname() {
return catelname;
}
public void setCatelname(String catelname) {
this.catelname = catelname;
}
public String getCatesname() {
return catesname;
}
public void setCatesname(String catesname) {
this.catesname = catesname;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
@Override
public String toString() {
return "filterDto [age10=" + age10 + ", age20=" + age20 + ", age30=" + age30 + ", age40=" + age40 + ", age50="
+ age50 + ", female=" + female + ", male=" + male + ", catelname=" + catelname + ", catesname="
+ catesname + ", price=" + price + "]";
}
}
|
Python | UTF-8 | 2,638 | 3.46875 | 3 | [] | no_license | """"""
import pprint
import requests
import parsel
import csv
'''
1、明确需求:
爬取豆瓣Top250排行电影信息
电影名字
导演、主演
年份、国家、类型
评分、评价人数
电影简介
'''
# csv模块保存数据到Excel
f = open('file_output/豆瓣电影数据.csv', mode='a', encoding='utf-8', newline='')
csv_writer = csv.DictWriter(f, fieldnames=['电影名字', '参演人员', '上映时间', '拍摄国家', '电影类型',
'电影评分', '评价人数', '电影概述'])
csv_writer.writeheader() # 写入表头
# 模拟浏览器发送请求
for page in range(0, 251, 25):
url = f'https://movie.douban.com/top250?start={page}&filter='
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
# 把 response.text 文本数据转换成 selector 对象
selector = parsel.Selector(response.text)
# 获取所有li标签
lis = selector.css('.grid_view li')
# 遍历出每个li标签内容
for li in lis:
# 获取电影标题 hd 类属性 下面的 a 标签下面的 第一个span标签里面的文本数据 get()输出形式是 字符串获取一个 getall() 输出形式是列表获取所有
title = li.css('.hd a span:nth-child(1)::text').get() # get()输出形式是 字符串
movie_list = li.css('.bd p:nth-child(1)::text').getall() # getall() 输出形式是列表
star = movie_list[0].strip().replace('\xa0\xa0\xa0', '').replace('/...', '')
movie_info = movie_list[1].strip().split('\xa0/\xa0') # ['1994', '美国', '犯罪 剧情']
movie_time = movie_info[0] # 电影上映时间
movie_country = movie_info[1] # 哪个国家的电影
movie_type = movie_info[2] # 什么类型的电影
rating_num = li.css('.rating_num::text').get() # 电影评分
people = li.css('.star span:nth-child(4)::text').get() # 评价人数
summary = li.css('.inq::text').get() # 一句话概述
dit = {
'电影名字': title,
'参演人员': star,
'上映时间': movie_time,
'拍摄国家': movie_country,
'电影类型': movie_type,
'电影评分': rating_num,
'评价人数': people,
'电影概述': summary,
}
pprint.pprint(dit)
csv_writer.writerow(dit)
|
TypeScript | UTF-8 | 406 | 2.6875 | 3 | [] | no_license | export class Weather {
constructor(
public name: string,
public description: string,
public icon: string,
public temperature: WeatherTemperature,
public pressure: number,
public humidity: number,
public windSpeed: number
) {
}
}
export class WeatherTemperature {
constructor(
public temperature: number,
public min: number,
public max: number
) {
}
}
|
Python | UTF-8 | 263 | 2.625 | 3 | [] | no_license | from pandas import DataFrame
def cleanData(dFrame, keys):
# remove useless columns
for key in keys:
dFrame = dFrame.drop(key,1)
# remove Null columns and rows
dFrame = dFrame.dropna(axis=0,how='all')
dFrame = dFrame.dropna(axis=1,how='all')
return dFrame |
C++ | UTF-8 | 298 | 3.078125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
float a = 0;
float b = 0;
float c = 0;
float calc = 0;
cout << "escreva o valor A: ";
cin >> a;
cout << "escreva o valor B: ";
cin >> b;
cout << "escreva o valor C: ";
cin >> c;
calc = b * b - 4 * a * c;
cout << calc;
}
|
Java | UTF-8 | 4,720 | 2.15625 | 2 | [
"MIT"
] | permissive | package stevekung.mods.moreplanets.planets.fronos.blocks;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Mirror;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import stevekung.mods.moreplanets.init.MPBlocks;
import stevekung.mods.moreplanets.utils.blocks.BlockBushMP;
import stevekung.mods.stevekunglib.utils.BlockStateProperty;
public class BlockSidedFronosMushroom extends BlockBushMP
{
public BlockSidedFronosMushroom(String name)
{
super(Material.PLANTS);
this.setTranslationKey(name);
this.setDefaultState(this.blockState.getBaseState().withProperty(BlockStateProperty.FACING_HORIZON, EnumFacing.NORTH));
this.setTickRandomly(true);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
{
switch (state.getValue(BlockStateProperty.FACING_HORIZON))
{
case SOUTH:
return new AxisAlignedBB(0.3125D, 0.3125D, 0.6625D, 0.6875D, 0.75D, 1.0D);
case NORTH:
default:
return new AxisAlignedBB(0.3125D, 0.3125D, 0.0D, 0.6875D, 0.75D, 0.3375D);
case WEST:
return new AxisAlignedBB(0.0D, 0.3125D, 0.3125D, 0.3225D, 0.75D, 0.6875D);
case EAST:
return new AxisAlignedBB(0.6725D, 0.3125D, 0.3125D, 1.0D, 0.75D, 0.6875D);
}
}
@Override
public IBlockState withRotation(IBlockState state, Rotation rot)
{
return state.withProperty(BlockStateProperty.FACING_HORIZON, rot.rotate(state.getValue(BlockStateProperty.FACING_HORIZON)));
}
@Override
public IBlockState withMirror(IBlockState state, Mirror mirrorIn)
{
return state.withRotation(mirrorIn.toRotation(state.getValue(BlockStateProperty.FACING_HORIZON)));
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack)
{
EnumFacing enumfacing = EnumFacing.fromAngle(placer.rotationYaw);
world.setBlockState(pos, state.withProperty(BlockStateProperty.FACING_HORIZON, enumfacing), 2);
}
@Override
public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
if (!facing.getAxis().isHorizontal())
{
facing = EnumFacing.NORTH;
}
return this.getDefaultState().withProperty(BlockStateProperty.FACING_HORIZON, facing.getOpposite());
}
@Override
@SideOnly(Side.CLIENT)
public BlockRenderLayer getRenderLayer()
{
return BlockRenderLayer.CUTOUT;
}
@Override
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(BlockStateProperty.FACING_HORIZON, EnumFacing.byHorizontalIndex(meta));
}
@Override
public int getMetaFromState(IBlockState state)
{
return state.getValue(BlockStateProperty.FACING_HORIZON).getHorizontalIndex();
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, BlockStateProperty.FACING_HORIZON);
}
@Override
public BlockFaceShape getBlockFaceShape(IBlockAccess world, IBlockState state, BlockPos pos, EnumFacing facing)
{
return BlockFaceShape.UNDEFINED;
}
@Override
public boolean canPlaceBlockAt(World world, BlockPos pos)
{
return world.getBlockState(pos.north()).getBlock() == MPBlocks.OSCALEA_LOG || world.getBlockState(pos.south()).getBlock() == MPBlocks.OSCALEA_LOG || world.getBlockState(pos.east()).getBlock() == MPBlocks.OSCALEA_LOG || world.getBlockState(pos.west()).getBlock() == MPBlocks.OSCALEA_LOG;
}
@Override
public boolean canBlockStay(World world, BlockPos pos, IBlockState state)
{
return world.getBlockState(pos.north()).getBlock() == MPBlocks.OSCALEA_LOG || world.getBlockState(pos.south()).getBlock() == MPBlocks.OSCALEA_LOG || world.getBlockState(pos.east()).getBlock() == MPBlocks.OSCALEA_LOG || world.getBlockState(pos.west()).getBlock() == MPBlocks.OSCALEA_LOG;
}
} |
Go | UTF-8 | 709 | 2.8125 | 3 | [] | no_license | package main
import (
"fmt"
"gopkg.in/mgo.v2"
)
// Connect connects to a MongoDB instance
func Connect(url string) (*mgo.Session, error) {
fmt.Println("Connecting to the DataBase...")
session, err := mgo.Dial(url)
if err != nil {
return nil, err
}
fmt.Println("Connected!!!\n")
return session, nil
}
// EnsureIndex calls EnsureIndex on the microservice's DB Collection
func EnsureIndex(s *mgo.Session, DB DataBaseConfig) {
session := s.Copy()
defer session.Close()
c := session.DB(DB.Name).C(DB.Collection)
index := mgo.Index{
Key: []string{"_id"},
Unique: true,
DropDups: true,
Background: true,
}
err := c.EnsureIndex(index)
if err != nil {
panic(err)
}
}
|
C | UTF-8 | 1,340 | 3.21875 | 3 | [] | no_license | #include <stdio.h>
#include "definition.h"
int maxim (int *a, int n, int i, int j, int k) {
int m = i;
if (j < n && a[j] > a[m]) {
m = j;
}
if (k < n && a[k] > a[m]) {
m = k;
}
return m;
}
void downheap (dataArray *arr, int n, int k) {
while (1) {
int j = maxim(arr->data, n, k, 2*k+1, 2*k+2);
if (j == k) {
break;
}
int t = arr->data[k];
arr->data[k] = arr->data[j];
arr->data[j] = t;
k = j;
}
}
void heapsort (dataArray *arr) {
int i = (arr->size - 2) / 2;
for (i; i >= 0; i--) {
downheap(arr, arr->size, i);
}
for (i = 0; i < arr->size; i++) {
int t = arr->data[arr->size - i - 1];
arr->data[arr->size - i - 1] = arr->data[0];
arr->data[0] = t;
downheap(arr, arr->size - i - 1, 0);
}
}
int main () {
int x[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof x / sizeof x[0];
dataArray arr[n]; arr->size = n; arr->length = n+5; arr->swaps = 0;
for (int i = 0; i< n; i++){
arr->data[i]=x[i];
}
int i;
for (i = 0; i < n; i++)
printf("%d%s", arr->data[i], i == n - 1 ? "\n" : " ");
heapsort(arr);
for (i = 0; i < n; i++)
printf("%d%s", arr->data[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
TypeScript | UTF-8 | 1,281 | 2.890625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | import * as React from 'react';
import type { Theme, PartialTheme } from '@fluentui/theme';
import type { ICustomizerContext } from '@fluentui/utilities';
/* eslint-disable @typescript-eslint/naming-convention */
/**
* {@docCategory ThemeProvider}
* Props for the ThemeProvider component.
*/
export interface ThemeProviderProps extends React.HTMLAttributes<HTMLDivElement> {
/**
* A component that should be used as the root element of the ThemeProvider component.
*/
as?: React.ElementType;
/**
* Optional ref to the root element.
*/
ref?: React.Ref<HTMLElement>;
/**
* Defines the theme provided by the user.
*/
theme?: PartialTheme | Theme;
/**
* Defines where body-related theme is applied to.
* Setting to 'element' will apply body styles to the root element of ThemeProvider.
* Setting to 'body' will apply body styles to document body.
* Setting to 'none' will not apply body styles to either element or body.
*
* @defaultvalue 'element'
*/
applyTo?: 'element' | 'body' | 'none';
}
/**
* State for the ThemeProvider component.
*/
export type ThemeProviderState = Omit<ThemeProviderProps, 'theme' | 'ref'> & {
theme: Theme;
ref: React.RefObject<HTMLElement>;
customizerContext: ICustomizerContext;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.