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
|
|---|---|---|---|---|---|---|---|
JavaScript
|
UTF-8
| 2,453
| 2.609375
| 3
|
[] |
no_license
|
module.exports = class SettingsPage {
constructor({page}) {
this.page = page
this.firewallSwitchCss = 'span[id="infoFirewall"]'
this.IMAPSwitchCss = 'span[id="infoImap"]'
this.SMTPSwitchCss = 'span[id="infoSmtp"]'
this.switchStateOff = 'switchoff2'
this.switchStateOn = 'switchon2'
this.clickRetryCount = 2
}
async sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async click(selector) {
await this.page.waitFor(selector)
await this.sleep(1500)
return this.page.click(selector)
}
async type(selector, value) {
await this.page.waitFor(selector)
return this.page.type(selector, value)
}
async getAttribute(selector, attr) {
await this.page.waitFor(selector)
return this.page.$eval(
selector,
(el, attribute) => el.getAttribute(attribute),
attr
)
}
async checkSettingsSwitch({
switchName,
swithcSelector,
desiredStateName,
desiredStateAttribute
}) {
await this.page.goto('https://poczta.onet.pl/ustawienia/')
const status = await this.getAttribute(swithcSelector, 'class')
if (status !== desiredStateAttribute) {
for (let i = 0; i < this.clickRetryCount + 1; i++) {
await this.click(swithcSelector)
console.log(` * ${switchName} switch clicked, attempt: ${i + 1}`)
await this.page.reload()
await this.sleep(i * 1000)
const newStatus = await this.getAttribute(swithcSelector, 'class')
if (newStatus !== desiredStateAttribute) {
if (i >= this.clickRetryCount) {
return 'error: Too many attempts'
} else {
continue
}
}
break
}
}
return desiredStateName
}
async disableFirewall() {
return await this.checkSettingsSwitch({
switchName: 'Firewall',
desiredStateName: 'off',
swithcSelector: this.firewallSwitchCss,
desiredStateAttribute: this.switchStateOff
})
}
async enableIMAP() {
return await this.checkSettingsSwitch({
switchName: 'IMAP',
desiredStateName: 'on',
swithcSelector: this.IMAPSwitchCss,
desiredStateAttribute: this.switchStateOn
})
}
async enableSMTP() {
return await this.checkSettingsSwitch({
switchName: 'SMTP',
desiredStateName: 'on',
swithcSelector: this.SMTPSwitchCss,
desiredStateAttribute: this.switchStateOn
})
}
}
|
PHP
|
UTF-8
| 758
| 2.8125
| 3
|
[] |
no_license
|
<?php
require_once "config.php";
$faker = Faker\Factory::create();
class User extends Illuminate\Database\Eloquent\Model
{
//разрешено редактировать только это, остальное запрещено
protected $fillable = ['login', 'password', 'name', 'age', 'avatar_path', 'description'];
protected $table = 'users';
}
for($i=0;$i<10;$i++)
{
$user = new User();
$user->login = $faker->userName;
$user->password = password_hash('123', PASSWORD_DEFAULT);;
$user->name = $faker->name;
$user->age = $faker->numberBetween(1, 120);
$user->description = $faker->text;
$user->avatar_path = 'http://mvc/img/avatars/work-1.png';
$user->created_at = $faker->dateTime;
$user->save();
}
|
Java
|
UTF-8
| 1,903
| 3.015625
| 3
|
[] |
no_license
|
package gd26.asteroids;
import java.awt.*;
import java.util.Random;
/**
* Debris class
*
* Created by gdorwin26 on 3/30/2017.
*/
public class Debris extends GameObject
{
private Vec2D[] particles;
private Vec2D[] particleOriginals;
private double time;
public Debris(Vec2D position, Vec2D velocity)
{
setPos(position);
setVel(velocity);
time = 0;
particles = new Vec2D[Properties.DEBRIS_PARTICLE_COUNT];
particleOriginals = new Vec2D[Properties.DEBRIS_PARTICLE_COUNT];
Random random = new Random();
for(int i = 0; i < Properties.DEBRIS_PARTICLE_COUNT; i++)
{
particles[i] = new Vec2D(1, 0).rot(random.nextDouble() * Math.PI * 2).mult(1 +
random.nextDouble() * 4);
particleOriginals[i] = particles[i].copy();
}
}
@Override
public void update(double deltaTime)
{
super.update(deltaTime);
for(int i = 0; i < particles.length; i++)
{
Vec2D particle = particles[i];
particle.add(particleOriginals[i].copy().mult(Properties.DEBRIS_SPREAD * deltaTime));
}
time += deltaTime;
if(time >= Properties.DEBRIS_LIFETIME)
{
AsteroidsMain.DEBRIS_TO_REMOVE.add(this);
}
}
public void render(Graphics g)
{
Graphics2D g2d = (Graphics2D) g.create();
g2d.translate((int) getPos().getX(), (int) getPos().getY());
int alpha = (int) (255 * (Properties.DEBRIS_LIFETIME - time) / Properties.DEBRIS_LIFETIME);
g2d.setColor(new Color(32, 128, 255, alpha));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(Vec2D particle : particles)
{
g2d.fillOval((int) particle.getX(), (int) particle.getY(), 2, 2);
}
g2d.dispose();
}
}
|
Java
|
UTF-8
| 983
| 2.21875
| 2
|
[] |
no_license
|
package com.example.papl_887062;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class ExerciseThen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_then);
((DecisionStack) this.getApplication()).add(ExerciseThen.class);
InputCalculation.setExerciseFlag(true);
}
public void onClickMessage(View view) {
Intent myIntent = new Intent(ExerciseThen.this, Message15.class);
startActivity(myIntent);
}
public void onClickBack(View view) {
Class previous = ((DecisionStack) this.getApplication()).getPrevious(true);
try {
InputCalculation.restart();
Intent node01ToMain = new Intent(ExerciseThen.this, previous);
startActivity(node01ToMain);
} catch (Exception e) {
System.err.println(e);
}
}
}
|
Java
|
UTF-8
| 1,448
| 2.984375
| 3
|
[] |
no_license
|
import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;
public class Day_3 {
private static List<char[]> map;
public static void main(String[] args) {
loadData();
// map.stream().forEach(line -> System.out.println(Arrays.toString(line)));
int x = 0, y = 0;
int treeCount = 0;
while (y < map.size() - 1) {
y += 1;
x += 3;
x %= map.get(0).length;
if (map.get(y)[x] == '#')
treeCount++;
}
System.out.println(treeCount);
int[][] steps = { { 1, 1 }, { 3, 1 }, { 5, 1 }, { 7, 1 }, { 1, 2 } };
BigInteger product = Stream.of(steps).map(step -> {
int pos_x = 0, pos_y = 0;
int trees = 0;
while (pos_y < map.size() - 1) {
pos_x += step[0];
pos_y += step[1];
pos_x %= map.get(0).length;
if (map.get(pos_y)[pos_x] == '#')
trees++;
}
System.out.println(trees);
return BigInteger.valueOf(trees);
}).reduce(BigInteger.ONE, BigInteger::multiply);
System.out.println(product);
}
public static void loadData() {
map = new ArrayList<>();
try {
Scanner sc = new Scanner(new File("./Inputs/day_3.txt"));
while (sc.hasNextLine()) {
String inputLine = sc.nextLine();
map.add(inputLine.toCharArray());
}
} catch (FileNotFoundException e) {
System.err.println("couldn't open file");
}
}
}
|
C
|
UTF-8
| 406
| 2.6875
| 3
|
[
"MIT-Modern-Variant"
] |
permissive
|
#include "syscall.h"
int main()
{
int i , j , k;
int child[10] , status;
char *name = "testConsoleOutput.coff";
for (i = 0; i < 10; i++)
{
//printf("====run child %d====\n" , i);
child[i] = exec(name , 1 , &name);
//printf("====================\n");
}
for (i = 0; i < 10; i++)
{
if (join(child[i] , &status) == 1)
{
printf("child %d joined successfully\n" , i);
}
}
return 0;
}
|
Python
|
UTF-8
| 3,656
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
import numpy as np
import cv2
########################################################
# Facefinder
########################################################
class EyesFinder:
def __init__(self, imageSize = (640,480), minFaceSize = (200,40)):
self.imageSize = imageSize
self.minFaceSize = minFaceSize
# load frontal face classifier
self.faceDet = cv2.CascadeClassifier("/home/pi/SACLeptonRPi/haarcascade_frontaleyes.xml")
####################################################
# Sets the the transformation matrix (M) for mapping
# true color image onto thermal imaging image.
# Is a numpy array e.g.:
# np.array([[1.5689e-1, 8.6462e-3, -1.1660e+1],
# [1.0613e-4, 1.6609e-1, -1.4066e+1]])
####################################################
def setTransformMatrix(self, transformMatrix):
self.M = transformMatrix
####################################################
# Takes a true color RGB image and looks for a face.
# Return true if a face was found and false
# if none was found.
# Fills out the true color ROI.
####################################################
def getTcEyesContours(self, image):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
rects = self.faceDet.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=self.minFaceSize)
if len(rects) > 0:
# only consider first face found.
# rect comes in a tuple (x,y,w,h).
# todo: check for biggest bounding box.
self.tcROI = rects[0]
tcROI_x, tcROI_y, tcROI_w, tcROI_h = self.tcROI
cv2.rectangle(image,(tcROI_x,tcROI_y),(tcROI_x + tcROI_w,tcROI_y + tcROI_h), (200,255,150), 2)
return True
else:
# no faces found
self.tcROI = (-1,-1,-1,-1)
return False
def getTcEyesROIWidth(self):
return self.tcROI[2]
####################################################
# Uses the transformation matrix to transform
# the true color ROI to a thermal image ROI.
# Returns the contour points of the thermal
# image ROI.
####################################################
def getThEyesContours(self):
# transform the coordinates from true color image space to thermal image space using the affine transform matrix M
# See https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html
# [[xt][yt]] = M . [[x][y][1]], with x,y=original coords and xt,yt=transformed coords.
#
# --->x
# |
# | lt rt
# V x------------x
# y | |
# | |
# | |
# x------------x
# lb rb
#
tcROI_x, tcROI_y, tcROI_w, tcROI_h = self.tcROI
P_slt = np.array([[tcROI_x],[tcROI_y],[1]]) # 'slt' source left top vector
P_srt = np.array([[tcROI_x + tcROI_w],[tcROI_y],[1]]) # 'srt' source right top vector
P_slb = np.array([[tcROI_x],[tcROI_y + tcROI_h],[1]]) # 'slb' source left bottom vector
P_srb = np.array([[tcROI_x + tcROI_w],[tcROI_y + tcROI_h],[1]]) # 'srb' source right bottom vector
P_dlt = np.dot(self.M, P_slt)
P_drt = np.dot(self.M, P_srt)
P_dlb = np.dot(self.M, P_slb)
P_drb = np.dot(self.M, P_srb)
thROIPoints = np.array([P_dlt, P_drt, P_dlb, P_drb], dtype=np.float32)
return(thROIPoints)
|
Python
|
UTF-8
| 487
| 2.640625
| 3
|
[] |
no_license
|
from science import *
def column_for_levels(levels):
return pd.DataFrame(levels).cummax()[0]
if __name__ == "__main__":
import pandas as pd
import matplotlib.pyplot as plt
df = pd.concat(
[column_for_levels(lvls)
for lvls in [bitcoin_cash_levels(), bitcoin_core_levels(), litecoin_levels()]]
, axis=1, keys=["Bitcoin Cash", "Bitcoin", "Litecoin"])
df.plot().set(ylabel="interlink size", xlabel="block height")
plt.show()
|
Java
|
UTF-8
| 793
| 3.59375
| 4
|
[] |
no_license
|
package com.quantum.javabasics;
import java.util.Scanner;
public class AnagramFromHackerrank {
public void checkAnagram(String s)
{
int result =0;
if (s.length()%2 == 0)
{
for(int i=0;i<s.length()/2;i++)
{
int count =0;
for(int j=s.length()-1;j>=s.length()/2;j--)
{
if(s.charAt(i)!=s.charAt(j))
{
count++;
}
}
if(count == s.length()/2 )
{
result++;
}
}System.out.println(result+" no of changes ");
}
else
{
System.out.println(s+" is not anagram");
}
}
public static void main(String[] args)
{
AnagramFromHackerrank object = new AnagramFromHackerrank();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String string = sc.next();
object.checkAnagram(string);
}
}
|
C++
|
UTF-8
| 373
| 2.625
| 3
|
[] |
no_license
|
#include "include/controller.h"
#include "include/item.h"
#include "include/book.h"
using namespace std;
int main()
{
//Let the controller handle main program loop
Controller controller;
controller.Start();
//demonstrate overloaded operators
//get info
Book thesaurus;
cin >>thesaurus;
//show info
cout <<thesaurus;
return 0;
}
|
Python
|
UTF-8
| 8,450
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/python3
import argparse
import sys
import re
import codecs
import string
import collections
try:
from unidecode import unidecode
except:
sys.exit("Requires unidecode pip package to be installed. Run:\npip install unidecode\nor\npip3 install unidecode\ndepending on your installation and start the script again.\nMore info on installing packages: https://docs.python.org/3/installing/index.html")
#############################
###
### HoI Darkest Hour minister to HoI4 idea converter by Yard1, originally for Darkest Hour mod
### Requires pyton3-pip to be installed
### Requires unidecode pip package to be installed (pip install unidecode / pip3 install unidecode). More info on installing packages: https://docs.python.org/3/installing/index.html
### Written in Python 3.6
###
### Copyright (c) 2017 Antoni Baum (Yard1)
### Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
### The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
### THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
###
### usage: DHtoHoi4MinisterConverter_python3.py [-h] [-l LOCALISATION]
### input output
###
### Given a HoI Darkest Hour .csv Minister file, create a HoI 4 ideas file with a
### given name with those ministers converted. Default format is for Darkest Hour
### mod by Algierian General. A localisation file with the names of ministers can
### also be created.
###
### positional arguments:
### input Darkest Hour .csv minister file
### output Name of HoI4 ideas file to write (overwrites)
###
### optional arguments:
### -h, --help show this help message and exit
### -l LOCALISATION, --localisation LOCALISATION
### Localisation file to write (overwrites)
###
#############################
if not sys.version_info >= (3,0):
sys.exit("Wrong Python version. Version 3.0 or higher is required to run this script!")
blocked_positions = ["Head of State"]
positions = collections.OrderedDict([("Head_of_Government", "HoG"), ("Foreign_Minister", "FM"), ("Minister_of_Security", "MoS"), ("Armaments_Minister", "AM"), ("Head_of_Intelligence", "HoI"), ("Chief_of_Staff", "CoStaff"), ("Chief_of_Army", "CoArmy"), ("Chief_of_Navy", "CoNavy"), ("Chief_of_Airforce", "CoAir")])
ideologies = ["NS", "FA", "PA", "SC", "ML", "SL", "SD", "LWR", "LE", "ST"]
position_translation = dict([("Minister of Armament", "Armaments Minister"), ("Head of Military Intelligence", "Head of Intelligence"), ("Chief of Air Force", "Chief of Airforce")])
class minister:
def __init__(self, position, name, start_year, end_year, ideology, trait, country_tag):
if position in position_translation:
position = position_translation[position]
self.position = re.sub(" ", "_", position)
self.name = name
self.start_year = start_year
self.end_year = end_year
self.ideology = ideology
self.trait = string.capwords(trait)
self.parsed_name = re.sub(" ", "_", re.sub('[^A-Za-z0-9 ]+', '', unidecode(self.name)))
self.idea_tag = "%s_%s_%s" % (country_tag, positions[self.position], self.parsed_name)
def __repr__(self):
return "<minister position:%s name:%s start_year:%s end_year:%s ideology:%s trait:%s>" % (self.position, self.name, self.start_year, self.end_year, self.ideology, self.trait)
def __str__(self):
return "%s, %s, %s, %s, %s, %s" % (self.position, self.name, self.start_year, self.end_year, self.ideology, self.trait)
def convert(self, country_tag):
return str("\t# %s\n\t\t%s = {\n\t\t\tpicture = Generic_Portrait\n\t\t\tallowed = { tag = %s }\n\t\t\tavailable = {\n\t\t\t\tdate > %s\n\t\t\t\tdate < %s\n\t\t\t\t%s = yes\n\t\t\t\tNOT = { has_country_flag = %s }\n\t\t\t}\n\t\t\tcost = 150\n\t\t\tremoval_cost = 10\n\t\t\ttraits = { %s %s }\n\t\t}" % (self.name, self.idea_tag, country_tag, "%s.1.1" % self.start_year, "%s.1.1" % self.end_year, "%s_Minister_Allowed" % self.ideology, "%s_unavailable" % self.parsed_name, positions[self.position]+"_"+re.sub(" ", "_", self.trait), "ideology_"+self.ideology))
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def readDHfile(name):
print(("Reading file " + name + "..."))
with codecs.open(name, encoding='ISO-8859-15', mode="r") as f:
lines = f.read().splitlines()
ministers = list()
tag = lines[0].split(';')[0]
for line in lines:
split_line = line.split(';')
if not is_number(split_line[0]):
continue
if split_line[1] not in blocked_positions:
ministers.append(minister(split_line[1], split_line[2], split_line[3], split_line[4], split_line[6], split_line[7], tag))
return (sorted(ministers, key=lambda minister: (list(positions.keys()).index(minister.position), ideologies.index(minister.ideology), minister.start_year)), tag)
def createHOI4ideasfile(name, ministers, country_tag):
lines = list()
lines.append("ideas = {")
current_position = ""
append_brace = False
for minister in ministers:
if current_position != minister.position:
if append_brace:
lines.append("}")
lines.append("#################################################")
lines.append("### %s" % (re.sub("_", " ", minister.position)))
lines.append("#################################################")
lines.append("\t%s = {" % minister.position)
append_brace = True
current_position = minister.position
lines.extend(minister.convert(country_tag).splitlines())
append_brace = True
lines.append("\t}")
lines.append("}")
with codecs.open(name, encoding='utf-8-sig', mode="w") as f:
f.writelines(line + "\n" for line in lines)
def createHOI4localisationfile(name, ministers):
lines = ["l_english:"]
for minister in ministers:
lines.append(" %s:0 \"%s\"" % (minister.idea_tag, minister.name))
with codecs.open(name, encoding='utf-8-sig', mode="w") as f:
f.writelines(line + "\n" for line in lines)
###################################################################
parser = argparse.ArgumentParser(description='Given a HoI Darkest Hour .csv Minister file, create a HoI 4 ideas file with a given name with those ministers converted. Default format is for Darkest Hour mod by Algierian General. A localisation file with the names of ministers can also be created.')
parser.add_argument('input',
help='Darkest Hour .csv minister file')
parser.add_argument( 'output',
help='Name of HoI4 ideas file to write (overwrites)')
parser.add_argument('-l', '--localisation', required=False, default="",
help='Localisation file to write (overwrites - make sure the file name has "l_english" in it!)')
args = parser.parse_args()
parsed_file = readDHfile(args.input)
country_tag = parsed_file[1]
ministers = parsed_file[0]
print(("File %s read successfully, %s ministers found" % (args.input, len(ministers))))
createHOI4ideasfile(args.output, ministers, country_tag)
print(("Ideas file %s created successfully" % args.output))
if args.localisation:
createHOI4localisationfile(args.localisation, ministers)
print(("Localisation file %s created successfully" % args.localisation))
|
Rust
|
UTF-8
| 6,150
| 2.984375
| 3
|
[] |
no_license
|
/*!
The `Page` class deals with operations done on pages, like editing.
*/
#![deny(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
extern crate lazy_static;
use crate::api::Api;
use crate::title::Title;
use serde_json::Value;
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
/// Represents a page.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Page {
title: Title,
}
impl Page {
/// Creates a new `Page` from a `Title`.
pub fn new(title: Title) -> Self {
Page { title }
}
/// Accesses the `Title` of this `Page`.
pub fn title(&self) -> &Title {
&self.title
}
/// Fetches the current text of this `Page`. If there is one slot in
/// the current revision, it is fetched; if there are multiple slots,
/// the "main" slot is fetched, or an error is returned if there is
/// no "main" slot.
///
/// # Errors
/// May return a `PageError` or any error from [`Api::get_query_api_json`].
///
/// [`Api::get_query_api_json`]: ../api/struct.Api.html#method.get_query_api_json
pub fn text(&self, api: &Api) -> Result<String, PageError> {
let title = self.title.full_pretty(api)
.ok_or_else(|| PageError::BadTitle(self.title.clone()))?;
let params = [
("action", "query"),
("prop", "revisions"),
("titles", &title),
("rvslots", "*"),
("rvprop", "content"),
("formatversion", "2"),
]
.iter()
.map(|&(k, v)| (k.to_string(), v.to_string()))
.collect();
let result = api.get_query_api_json(¶ms)
.map_err(|e| PageError::RequestError(e))?;
let page = &result["query"]["pages"][0];
if page["missing"].as_bool() == Some(true) {
Err(PageError::Missing(self.title.clone()))
} else if let Some(slots) = page["revisions"][0]["slots"].as_object() {
if let Some(the_slot) = {
slots["main"].as_object().or_else(|| {
if slots.len() == 1 {
slots.values().next().unwrap().as_object() // unwrap OK, length is 1
} else {
None
}
})
} {
match the_slot["content"].as_str() {
Some(string) => Ok(string.to_string()),
None => Err(PageError::BadResponse(result)),
}
} else {
Err(PageError::BadResponse(result))
}
} else {
Err(PageError::BadResponse(result))
}
}
/// Edits this `Page` with the given parameters and edit summary.
///
/// # Errors
/// May return a `PageError` or any error from [`Api::post_query_api_json`].
///
/// [`Api::post_query_api_json`]: ../api/struct.Api.html#method.post_query_api_json
pub fn edit_text(
&self,
api: &mut Api,
text: impl Into<String>,
summary: impl Into<String>,
) -> Result<(), Box<dyn Error>> {
let title = self.title.full_pretty(api)
.ok_or_else(|| PageError::BadTitle(self.title.clone()))?;
let bot = if api.user().is_bot() { "true" } else { "false" };
let mut params: HashMap<String, String> = [
("action", "edit"),
("title", &title),
("text", &text.into()),
("summary", &summary.into()),
("bot", bot),
("formatversion", "2"),
("token", &api.get_edit_token()?),
]
.iter()
.map(|&(k, v)| (k.to_string(), v.to_string()))
.collect();
if !api.user().user_name().is_empty() {
params.insert("assert".to_string(), "user".to_string());
}
let result = api.post_query_api_json(¶ms)?;
match result["edit"].as_str() {
Some("Success") => Ok(()),
_ => Err(Box::new(PageError::EditError(result))),
}
}
}
/// Errors that can go wrong while performing operations on a `Page`.
#[derive(Debug)]
#[non_exhaustive]
pub enum PageError {
/// Couldn't obtain the title for this page for use in an API request.
BadTitle(Title),
/// Couldn't understand the API response (provided).
BadResponse(Value),
/// Missing page.
Missing(Title),
/// Edit failed; API response is provided.
EditError(Value),
/// Error while performing the API request.
RequestError(Box<dyn Error>),
}
impl fmt::Display for PageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PageError::BadTitle(title) => write!(f, "invalid title for this Page: {:?}", title),
PageError::BadResponse(response) =>
write!(f, "bad API response while fetching revision content: {:?}", response),
PageError::Missing(title) => write!(f, "page missing: {:?}", title),
PageError::EditError(response) => write!(f, "edit resulted in error: {:?}", response),
PageError::RequestError(error) => write!(f, "request error: {}", error),
}
}
}
impl Error for PageError {}
#[cfg(test)]
mod tests {
use super::*;
use crate::api::*;
fn wd_api() -> &'static Api {
lazy_static! {
static ref API: Api = Api::new("https://www.wikidata.org/w/api.php").unwrap();
}
&API
}
#[test]
fn page_text_main_page_nonempty() {
let page = Page::new(Title::new("Main Page", 4));
let text = page.text(wd_api()).unwrap();
assert!(!text.is_empty());
}
#[test]
fn page_text_nonexistent() {
let title = Title::new("This page does not exist", 0);
let page = Page::new(title.clone());
match page.text(wd_api()) {
Err(PageError::Missing(t)) => assert!(t == title),
x => panic!("expected missing error, found {:?}", x),
}
}
}
|
SQL
|
UTF-8
| 1,876
| 4.03125
| 4
|
[] |
no_license
|
{{ config(materialized='view') }}
-- Determines the percentage of time a property has been occupied since they've
-- been onboarded.
WITH property_master_list AS (SELECT * FROM {{ref('property_master_list')}}),
booking_occupancy AS (SELECT * FROM {{ref('nights_occupied_per_booking')}}),
jira_issues AS (SELECT * FROM {{ref('jira_issues')}}),
nights_occupied_per_booking AS (SELECT * FROM {{ref('nights_occupied_per_booking')}}),
days_onboard AS (SELECT * FROM {{ref('days_onboard')}}),
date_onboarded AS (SELECT * FROM {{ref('date_onboarded')}}),
date_offboarded AS (SELECT * FROM {{ref('date_offboarded')}}),
base AS (SELECT property_master_list.ba_id_code AS ba_id_code,
property_master_list.property_address AS property_address,
property_master_list.property_owner AS property_owner,
days_onboard.days_onboard AS days_onboard,
property_master_list.status AS status,
SUM(nights_occupied_per_booking.nights_occupied) AS nights_occupied
FROM property_master_list
LEFT JOIN days_onboard
ON property_master_list.ba_id_code = days_onboard.ba_id_code
LEFT JOIN nights_occupied_per_booking
ON property_master_list.ba_id_code = nights_occupied_per_booking.ba_id_code
GROUP BY 1,2,3,4,5)
SELECT b.*,
date_onboarded.date_onboarded AS date_onboarded,
date_offboarded.date_offboarded AS date_offboarded,
CASE WHEN b.nights_occupied IS NULL THEN 0
ELSE b.nights_occupied/b.days_onboard * 100 END AS percentage_occupied
FROM base b
LEFT JOIN date_onboarded
ON b.ba_id_code = date_onboarded.ba_id_code
LEFT JOIN date_offboarded
ON b.ba_id_code = date_offboarded.ba_id_code
WHERE status = 'Active'
|
C++
|
UTF-8
| 6,503
| 2.78125
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
#include <cstring>
#include <limits>
#include <fstream>
#include <sstream>
#include <atomic>
#include <time.h>
#include <pthread.h>
#include "ittnotify.h" // for VTune
#include "../include/graph.h"
#define MAX_THREADS 512
#define BUFF_SIZE 100000
#define INF std::numeric_limits<int>::max()
int num_threads = 0;
pthread_t handles[MAX_THREADS];
int short_names[MAX_THREADS];
// initialize the graph in main
graph g;
// NOTE: declare the global array with a buffer; if the argument graph has more nodes than the
// buffer size, reallocate the array with the argument number of nodes.
std::atomic<graph::edge_data_t>* distance = new std::atomic<graph::edge_data_t>[BUFF_SIZE];
void Usage(char *prog) {
std::cout << "usage: " << prog << " -f filename -s src_id [-p num_threads]" << std::endl;
}
void UpdateDistance(const graph::node_t& u, const graph::node_t& v, const graph::edge_data_t& w) {
bool done = false;
while (!done) {
auto dist_old = distance[v].load();
auto distu = distance[u].load();
auto dist_new = distu + w;
if (distu != INF && dist_new < dist_old) {
done = distance[v].compare_exchange_weak(dist_old, dist_new);
} else {
done = true;
}
}
}
void* Relax(void *thread_id_ptr) {
graph::node_t tid = *(graph::node_t*)thread_id_ptr;
for (graph::node_t u = tid; u < g.end(); u += num_threads) {
for (graph::edge_t e = g.edge_begin(u); e < g.edge_end(u); e++) {
graph::node_t v = g.get_edge_dst(e);
graph::edge_data_t w = g.get_edge_data(e);
// ---------------- critical section ----------------
UpdateDistance(u, v, w);
// --------------------------------------------------
}
}
}
int main(int argc, char* argv[]) {
__itt_pause();
std::string filename; // graph file name
graph::node_t src; // source node ID
bool parallel = false; // run in parallel if true
std::ofstream f; // result text file
std::ostringstream result_filename; // result text file name
uint64_t execTime; // time in nanoseconds
struct timespec tick, tock; // for measuring runtime
pthread_attr_t attr;
pthread_attr_init(&attr);
// parse program arguments
for (int i = 0; i < argc; ++i) {
if (!strcmp(argv[i], "-f")) {
// graph file name
filename = argv[++i];
} else if (!strcmp(argv[i], "-s")) {
src = (graph::node_t)std::stoi(argv[++i]);
} else if (!strcmp(argv[i], "-p")) {
parallel = true;
num_threads = std::stoi(argv[++i]);
}
}
if (filename.empty() || (parallel && num_threads == 0)) {
Usage(argv[0]);
return -1;
}
if (!g.construct_from_dimacs(filename)) {
return -1;
}
// initialize the graph
int num_nodes = (int)g.size_nodes();
if (num_nodes > BUFF_SIZE) {
delete [] distance;
distance = new std::atomic<graph::edge_data_t>[num_nodes];
}
for (int i = 0; i < num_nodes; ++i) {
distance[i] = INF;
}
distance[src - 1] = 0;
// repeat relaxation
if (parallel) {
std::cout << "solving SSSP from node " << (int)src << " via parallel Bellman-Ford algorithm..." << std::endl;
// main computation for SSSP; measure runtime here
clock_gettime(CLOCK_MONOTONIC_RAW, &tick);
// ---------------- experiment below ----------------
__itt_resume(); // for VTune
// this loop has to stay serial
for (int i = 0; i < num_threads; ++i) {
// create threads 0, 1, 2, ..., numThreads (round robin)
short_names[i] = i;
pthread_create(&handles[i], &attr, Relax, &short_names[i]);
}
// join with threads when they're done
for (int i = 0; i < num_threads; ++i) {
pthread_join(handles[i], NULL);
}
__itt_pause();
// --------------------------------------------------
clock_gettime(CLOCK_MONOTONIC_RAW, &tock);
execTime = 1000000000 * (tock.tv_sec - tick.tv_sec) + tock.tv_nsec - tick.tv_nsec;
std::cout << "elapsed process CPU time = " << (long long unsigned int)execTime << " nanoseconds\n";
result_filename << filename << "_parallel.txt";
// export result to a text file
f.open(result_filename.str());
for (int i = 0; i < num_nodes; ++i) {
std::string dist_str = std::to_string(distance[i]);
if (distance[i] == INF) dist_str = "INF";
f << i + 1 << " " << dist_str << std::endl;
}
f.close();
} else {
std::cout << "solving SSSP from node " << (int)src << " via serial Bellman-Ford algorithm..." << std::endl;
// main computation for SSSP; measure runtime here
clock_gettime(CLOCK_MONOTONIC_RAW, &tick);
// ---------------- experiment below ----------------
for (graph::node_t u = g.begin(); u < g.end(); u++) {
graph::edge_data_t dist = distance[u];
for (graph::edge_t e = g.edge_begin(u); e < g.edge_end(u); e++) {
graph::node_t v = g.get_edge_dst(e);
graph::edge_data_t w = g.get_edge_data(e);
// take care of cases with infinity
graph::edge_data_t updated = dist + w;
if (dist != INF && distance[v] > updated) {
distance[v] = updated;
}
}
}
// --------------------------------------------------
clock_gettime(CLOCK_MONOTONIC_RAW, &tock);
execTime = 1000000000 * (tock.tv_sec - tick.tv_sec) + tock.tv_nsec - tick.tv_nsec;
std::cout << "elapsed process CPU time = " << (long long unsigned int)execTime << " nanoseconds\n";
result_filename << filename << ".txt";
// export result to a text file
f.open(result_filename.str());
for (int i = 0; i < num_nodes; ++i) {
std::string dist_str = std::to_string(distance[i]);
if (distance[i] == INF) dist_str = "INF";
f << i + 1 << " " << dist_str << std::endl;
}
f.close();
}
// NOTE: normally, the algorithm checks for negative cycles, but for the sake of saving time,
// we'll just assume there aren't any, assuming all edges have positive weights.
return 0;
}
|
Markdown
|
UTF-8
| 686
| 2.6875
| 3
|
[] |
no_license
|
# TiP-updates
Weekly Theory in Practice updates
## Recent Progress
* I went through all of the proofs in section 2 of the prelims document.
* I've mostly set up an environment to work in, consisting of editors, Fedora 24, python, etc.
## Current tasks
### Big picure
* Learning Python
* Learning about Graphs
* Learning about matrices
### Specific tasks for the week
* Write up formalized proofs of exercises in section 2 of preliminaries document.
* Show M = UU^T is symmetric positive semi-definite (SPSD)
* Show that L = D - A is SPSD.
## Issues that could use group help?
* Things are going well! Thanks to people answering my large set of questions when I'm in the lab.
|
Java
|
UTF-8
| 5,012
| 1.953125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright © 2018 Marcus Thiesen (marcus@thiesen.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.netty.handler.ssl;
import io.netty.util.ReferenceCounted;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import java.nio.ByteBuffer;
public class ReferenceCountedOpenSslEngine extends SSLEngine implements ReferenceCounted, ApplicationProtocolAccessor {
@Override
public String getNegotiatedApplicationProtocol() {
// empty dummy implementation
return null;
}
@Override
public int refCnt() {
// empty dummy implementation
return 0;
}
@Override
public ReferenceCounted retain() {
// empty dummy implementation
return null;
}
@Override
public ReferenceCounted retain(int increment) {
// empty dummy implementation
return null;
}
@Override
public ReferenceCounted touch() {
// empty dummy implementation
return null;
}
@Override
public ReferenceCounted touch(Object hint) {
// empty dummy implementation
return null;
}
@Override
public boolean release() {
// empty dummy implementation
return false;
}
@Override
public boolean release(int decrement) {
// empty dummy implementation
return false;
}
@Override
public void beginHandshake() throws SSLException {
// empty dummy implementation
}
@Override
public void closeInbound() throws SSLException {
// empty dummy implementation
}
@Override
public void closeOutbound() {
// empty dummy implementation
}
@Override
public Runnable getDelegatedTask() {
// empty dummy implementation
return null;
}
@Override
public boolean getEnableSessionCreation() {
// empty dummy implementation
return false;
}
@Override
public String[] getEnabledCipherSuites() {
// empty dummy implementation
return new String[0];
}
@Override
public String[] getEnabledProtocols() {
// empty dummy implementation
return new String[0];
}
@Override
public HandshakeStatus getHandshakeStatus() {
// empty dummy implementation
return null;
}
@Override
public boolean getNeedClientAuth() {
// empty dummy implementation
return false;
}
@Override
public SSLSession getSession() {
// empty dummy implementation
return null;
}
@Override
public String[] getSupportedCipherSuites() {
// empty dummy implementation
return new String[0];
}
@Override
public String[] getSupportedProtocols() {
// empty dummy implementation
return new String[0];
}
@Override
public boolean getUseClientMode() {
// empty dummy implementation
return false;
}
@Override
public boolean getWantClientAuth() {
// empty dummy implementation
return false;
}
@Override
public boolean isInboundDone() {
// empty dummy implementation
return false;
}
@Override
public boolean isOutboundDone() {
// empty dummy implementation
return false;
}
@Override
public void setEnableSessionCreation(boolean arg0) {
// empty dummy implementation
}
@Override
public void setEnabledCipherSuites(String[] arg0) {
// empty dummy implementation
}
@Override
public void setEnabledProtocols(String[] arg0) {
// empty dummy implementation
}
@Override
public void setNeedClientAuth(boolean arg0) {
// empty dummy implementation
}
@Override
public void setUseClientMode(boolean arg0) {
// empty dummy implementation
}
@Override
public void setWantClientAuth(boolean arg0) {
// empty dummy implementation
}
@Override
public SSLEngineResult unwrap(ByteBuffer arg0, ByteBuffer[] arg1, int arg2, int arg3) throws SSLException {
// empty dummy implementation
return null;
}
@Override
public SSLEngineResult wrap(ByteBuffer[] arg0, int arg1, int arg2, ByteBuffer arg3) throws SSLException {
// empty dummy implementation
return null;
}
}
|
Markdown
|
UTF-8
| 875
| 4.125
| 4
|
[
"MIT"
] |
permissive
|
# Currying
Currying is where a function expects a certain amount of arguments and if provided with less,
it returns another function that is awaiting the remaining arguments. Only once it receives all
expected arguments does a result get returned. If provided with the expected amount of arguments
all at once it works as normal and returns a result.
```JavaScript
const curry = require('lodash/fp/curry');
const greet = curry((greeting, name) => `${greeting}, ${name}!`);
// Passing both arguments allows the function to work as normal
greet('Hello', 'Simon'); // Hello, Simon!
// Passing fewer however, returns another function
const sayBye = greet('See ya');
// And once it receives all its arguments, it returns a value
sayBye('John'); // See ya, John!;
```
References:
* https://simonsmith.io/dipping-a-toe-into-functional-js-with-lodash-fp/#a-delicious-curry
|
JavaScript
|
UTF-8
| 509
| 3.734375
| 4
|
[] |
no_license
|
//将类数组转换成数组
let array_like = {"0":"ter","1":"lal",length:2}
//类数组对象
console.log(array_like);
//从数组对象解构出slice方法
let {slice} =[];
//类似
//let array = Array.prototype.slice;
let array = slice.call(array_like,0);
console.log(array);
//第二种方法
console.log("类数组转换成数组2",Array.from(array_like));
let set = new Set([1,2,3,1,2,3,4,5,6,6,6]);
console.log("去重:",set);
console.log("再转换成数组",Array.from(set));
|
C#
|
UTF-8
| 1,142
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project.Model;
using Project.Repository;
using Project.RequestModel;
namespace Project.Service
{
public interface ICustomerService : IBaseService<Customer>
{
List<Customer> Search(SearchRequestModel model);
string GetLastCreatedCustomerCode();
}
public class CustomerService : BaseService<Customer>, ICustomerService
{
private readonly ICustomerRepository _repository;
public CustomerService(ICustomerRepository repository): base(repository)
{
_repository = repository;
}
public List<Customer> Search(SearchRequestModel model)
{
return _repository.Search(model).ToList();
}
public string GetLastCreatedCustomerCode()
{
var customers = _repository.GetLastCreatedCustomer().ToList();
if (customers.Count == 0) return "00100";
return customers.Count != 1 ? null : customers.Select(customer => customer.Code).FirstOrDefault();
}
}
}
|
PHP
|
UTF-8
| 6,292
| 3.09375
| 3
|
[] |
no_license
|
<?php
# ^ ==> "Commence par"
# $ ==> "fini par (ce qu'il y a juste avant le $)"
# [^] ==> "ne contient pas ce qui est dans les crochets" ex : [^abc] = ne contient ni a, ni b, ni c
# [a-z] ==> n'importe quel caractère entre a et z, en minuscule
# [A-Z] ==> n'importe quel caractère entre a et z, en majuscule
# [0-9] ==> n'importe quel chiffre entre 0 et 9
# [a-zA-Z0-9] ==> n'importe quel caractère alphanumérique (SAUF caractères accentués)
# [ahbk76/\?\.\-] ==> un de ces caractères là
# . (point) ==> n'importe quel caractère
# \ ==> permet d'échapper des caractères
# | (pipe) ==> "ou bien"
# () ==> parenthèses "capturantes" permet de cherche un ensemble de données, et ça permet de les réutiliser
# [] ==> intervales ; choix de caractères …
# ? ==> 0 ou 1 fois
# + ==> au moins 1 fois
# * ==> 0, 1 ou plusieurs fois
# ============
# = Exemples =
# ============
$chaine = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. LoUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
# Fonction pour remplacer des caractères
# preg_replace(motif en Regex, chaine de remplacement, la chaine à traiter);
# echo preg_replace('#^Lo#', 'toto', $chaine);
# echo preg_replace('#Lo#', 'toto', $chaine).'<br>';
# Recherche une chaine commençant par "Lo" ou "lo" (car insensible à la casse grace au 'i'), et la remplace par "toto" :
# echo preg_replace('#Lo#i', '<strong>toto</strong>', $chaine).'<br>';
# Remplace tous les "ae" ou "eu" par "O" :
# echo preg_replace('#ae|eu#', 'O', $chaine).'<br>';
# Remplace tous les "a" ou "e" par "O" :
# echo preg_replace('#a|e#', 'O', $chaine).'<br>';
# echo preg_replace('#[ae]#i', 'O', $chaine).'<br>';
# Repère tous les "a" ou "e" et remplace par eux-même, en rouge :
# echo preg_replace('#([ae])#i', '<span style="color:red">$1</span>', $chaine).'<br>'; // $1 = on remplace la parenthèse n°1
# echo preg_replace('#(ae)#i', '<span style="color:red">$1</span>', $chaine).'<br>';
# echo preg_replace('#[ae]#i', '<span style="color:red">$0</span>', $chaine).'<br>'; // $0 = on remplace TOUT le motif
$chaine2 = 'Dis moi gros gras grand grin d\'orge, quand te degrosgrasgrandgrin d\'orgeras-tu ? Je me degrosgrasgrandgrin d\'orgerai quand tous les gros gras grand grin d\'orge se seront degrosgrasgrandgrin d\'orge';
# Repèrer les chaines de caractères contenant "gr", suivi de "a","i" ou "o", suivi de "s" ou "n" et enfin éventuellement suivi d'un "d", et les mettre en italique.
# echo preg_replace('#gr[aio][sn]d?#i', '<em>$0</em>', $chaine2).'<br>';
# echo preg_replace('#(gr[aio][sn]d?)#', '<em>$1</em>', $chaine2).'<br />';
# Repèrer les chaines de caractères contenant "gr", suivi de "as" ou "in" ou "os", éventuellement suivi d'un "d", et les remplacer par "as" ou "in" ou "os" en italique.
# echo preg_replace('#gr(as|in|os|an)d?#i', '<em>$1</em>', $chaine2).'<br>';
# Repèrer les chaines de caractères contenant "gr", suivi d'une lettre entre "a" et "i", suivi peut-être de "s" ou "n" et enfin éventuellement suivi d'un "d", et les mettre en italique.
# echo preg_replace('#gr[a-i][sn]?d?#i', '<em>$0</em>', $chaine2).'<br>';
# Repèrer les chaines de caractères contenant "gr", suivi d'une lettre entre "a" et "i", suivi peut-être de "s" ou "n" et enfin éventuellement suivi d'un "d", et mettre en italique le tout, en gras les lettres entre a et i, en rouge le s ou n.
# echo preg_replace('#gr([a-i])([sn]?)(d?)#i', '<em>gr<b>$1</b><span style="color:red">$2</span>$3</em>', $chaine2).'<br>';
$chaine3 = 'Babarrrrrrrrrr';
# Repère "Baba" suivi de 3 "r"
# echo preg_replace('#Babar{3}#', '<span style="color:red">$0</span>', $chaine3).'<br /><br />';
$chaine4 = 'il fait pas beau à Paris';
# Repère 3 lettres à la suite (sans espace donc)
echo preg_replace('#[a-z]{3}#i', '<span style="color:red">$0</span>', $chaine4).'<br /><br />';
# Repère entre 3 et 4 lettres à la suite, suivies d'un espace
echo preg_replace('#[a-z]{3,4}\s#i', '<span style="color:red">$0</span>', $chaine4).'<br /><br />';
echo preg_replace('#[a-z]{3,}#i', '<span style="color:red">$0</span>', $chaine4).'<br /><br />'; // au moins 3 lettres
# Repère un espace, suivi de "f", puis de n'importe quels caractères, puis d'un "t" et enfin d'un espace
echo preg_replace('#\sf.*t\s#i', '<span style="color:red">$0</span>', $chaine4).'<br /><br />';
$texte = "j'aime bien les bananes et les concombres, mais pas les fraises";
$recherche = ['#bananes#', '#fraises#', '#concombres#'];
$remplace = ['fruits jaunes', 'fruits rouges', 'légumes verts'];
echo preg_replace($recherche, $remplace, $texte).'<br><br>';
$texte = "Espèce de batard d'enculé de sale fils de pute";
$recherche = ['#batard#','#enculé#','#pute#'];
# $remplace = '************';
$remplace = ['mélange', 'passif', 'plage'];
echo preg_replace($recherche, $remplace, $texte).'<br><br>';
$string = 'fraise,bananes;choux fleur,carottes';
# print_r(explode(',',$string));
print_r(preg_split('#[,; ]#',$string));
echo '<br><br>';
# Filtrer dans une chaine de caractère, un mail et le faire cliquable
$texte = 'Mon email est blagues.a-toto@toto-land.to';
$recherche = '#[a-z0-9]+([\.\_\-][a-z0-9]+)*@[a-z0-9]+([\.\-][a-z0-9]+)*\.[a-z]{2,}#i';
$remplace = '<a href="mailto:$0">$0</a>';
echo preg_replace($recherche, $remplace, $texte);
echo '<br><br>';
# preg_match()
# preg_match_all()
$texte = 'fraise,bananes;choux fleur,carottes';
# preg_match()
echo preg_match('#a#', $texte);
# preg_match_all()
$texte2 = 'Mon email est blagues.a-toto@toto-land.to. Mon email est toto@plop.com, celui de Ron est ron.winsley@hogwarts.co.uk';
$recherche = '#[a-z0-9]+([\.\_\-][a-z0-9]+)*@[a-z0-9]+([\.\-][a-z0-9]+)*\.[a-z]{2,}#i';
echo '<pre>';
print_r(preg_match_all($recherche, $texte2, $matches));
echo '</pre>';
echo '<pre>';
print_r($matches);
echo '</pre>';
echo $matches[0][1]; // accès direct au sous-tableau
// Version décomposée :
echo '<pre>';
print_r($matches[0]);
echo '</pre>';
$listeDesMails = $matches[0];
echo $listeDesMails[1];
|
Python
|
UTF-8
| 2,691
| 2.625
| 3
|
[] |
no_license
|
# -*- coding: UTF-8 -*-
import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data/', one_hot=True)
trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testimglabel = mnist.test.labels
learning_rate = 0.01
training_epochs = 20
batch_size = 256
display_step = 1
n_hidden_1 = 256
n_hidden_2 = 128
n_input = 784
examples_to_show = 10
X = tf.placeholder(tf.float32, [None, n_input])
weights = {
'encoder_h1':tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'encoder_h2':tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'decoder_h1':tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1])),
'decoder_h2':tf.Variable(tf.random_normal([n_hidden_1, n_input]))
}
biases = {
'encoder_b1':tf.Variable(tf.random_normal([n_hidden_1])),
'encoder_b2':tf.Variable(tf.random_normal([n_hidden_2])),
'decoder_h1':tf.Variable(tf.random_normal([n_hidden_1])),
'decoder_h2':tf.Variable(tf.random_normal([n_input]))
}
#定义压缩模型
def encoder(x):
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']), biases['encoder_b1']))
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']), biases['encoder_b2']))
return layer_2
def decoder(x):
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']), biases['decoder_h1']))
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']), biases['decoder_h2']))
return layer_2
encoder_op = encoder(X)
decoder_op = decoder(encoder_op)
y_pred = decoder_op
y_true = X
cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)
with tf.Session() as sess :
sess.run(tf.global_variables_initializer())
total_batch = int(mnist.train.num_examples/batch_size)
for epoch in range(training_epochs):
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={X:batch_x})
if epoch % display_step == 0:
print('Epoch:', '%04d'%(epoch+1),'cost=', '{:.9}'.format(c))
print('Optimizer Finished')
encode_decode = sess.run(y_pred, feed_dict={X:mnist.test.images[:examples_to_show]})
f, a = plt.subplots(2, 10, figsize=(10, 2))
for i in range(examples_to_show):
a[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))
a[1][i].imshow(np.reshape(encode_decode[i], (28, 28)))
f.show()
plt.draw()
plt.waitforbuttonpress()
|
Python
|
UTF-8
| 1,826
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
from flask import Flask, request, jsonify
from flask_cors import CORS
import base64
import numpy as np
import cv2
import angle
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path, model_wh
from sklearn.metrics import r2_score
from os.path import join
app = Flask(__name__)
CORS(app)
# 设置参数
model = 'cmu'
resize = '432x368'
upsample_size = 4.0
# 模型初始化
w, h = model_wh(resize)
e = TfPoseEstimator(get_graph_path(model), target_size=(w, h))
# 样本数据
stdAngle = np.loadtxt(join('features', 'demo.tsv'), delimiter='\t')
@app.route('/', methods=['POST'])
def compare():
data = request.form['snapData'] # 读取图片并去掉头部信息
data = data.split(',')[1] # 去掉头部信息
frame = int(float(request.form['frame']) * 30) # 当前帧时间
print(frame)
image = np.fromstring(base64.urlsafe_b64decode(data), np.uint8) # 解码
image = cv2.imdecode(image, cv2.IMREAD_ANYCOLOR)
if image is None:
return jsonify({'code': 0, 'msg': 'Image can not be read'})
humans = e.inference(image, resize_to_default=(w > 0 and h > 0), upsample_size=upsample_size)
# 检测到人
if len(humans) > 0:
realAngle = angle.CalAngle(humans[-1])
if np.isnan(realAngle).any():
return jsonify({'code': 2, 'msg': '识别部位缺失'})
i = np.abs(realAngle - stdAngle[frame]) < 0.15 # 设置允许误差
realAngle[i] = stdAngle[frame][i]
score = np.sqrt(r2_score(stdAngle[frame], realAngle))
# print(score)
return jsonify({'code': 3, 'msg': '识别成功', 'score': score})
return jsonify({'code': 1, 'msg': '无法检测到人'})
if __name__ == '__main__':
app.run(debug=True)
|
Java
|
UTF-8
| 1,111
| 2.203125
| 2
|
[] |
no_license
|
package com.forgus.rent.entity;
import javax.persistence.*;
import java.time.LocalDate;
/**
* 电表记录
* Created by cwb on 2016/3/8.
*/
@Entity
@Table(name = "elecRecord")
public class ElecRecord {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "createDate")
private LocalDate createDate;
@Column(name = "readings")
private int readings;
@ManyToOne
@JoinColumn(name = "ammeterId")
private Ammeter ammeter;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getCreateDate() {
return createDate;
}
public void setCreateDate(LocalDate createDate) {
this.createDate = createDate;
}
public int getReadings() {
return readings;
}
public void setReadings(int readings) {
this.readings = readings;
}
public Ammeter getAmmeter() {
return ammeter;
}
public void setAmmeter(Ammeter ammeter) {
this.ammeter = ammeter;
}
}
|
C++
|
UTF-8
| 1,931
| 2.75
| 3
|
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#include <vector>
#include <sstream>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "Image.h"
#include "Root.h"
#pragma pack(push, 1)
struct file_struct
{
char filename[8];
char ext[3];
u_int8_t attributes;
char reserved[10];
u_int16_t time_created;
u_int16_t modify_date;
u_int16_t starting_cluster;
u_int32_t file_size;
};
#pragma pack(pop)
using std::cout;
using std::endl;
using std::string;
string cool_func(char *source)
{
string s;
for (int i = 0; i < sizeof(source); ++i)
{
s += source[i];
}
return s;
}
int main(int argc, char *argv[])
{
std::string filename = "../hd0.img";
Image mainImage = Image(filename);
std::cout << "Bytes per sector: " << mainImage.getBootData().bytesPerSector << std::endl;
std::cout << "Sectors per claster: " << (int) mainImage.getBootData().sectorPerCluster << std::endl;
std::cout << "# of FATs: " << (int) mainImage.getBootData().numberOfFATS << std::endl;
std::cout << "FAT size: " << mainImage.getBootData().sectorsPerFAT << std::endl;
std::cout << "Root directory entires: " << mainImage.getBootData().rootEntries / 32 << ". Its size: "
<< mainImage.getBootData().rootEntries << std::endl;
std::cout << "Reserved Sectors: " << mainImage.getBootData().reservedSectors << std::endl;
std::cout << "Signature: " << (int) mainImage.getBootData().signature << std::endl;
std::cout << "----------------" << std::endl;
Root root = Root(mainImage);
std::string needed = argv[1];
auto res = root.find_file(needed);
if (res == -1)
{
std::cout << "File not found" << std::endl;
} else
{
std::cout << "File found" << std::endl;
}
auto file = root.getFile(res);
root.describe_file(file);
}
|
C++
|
UTF-8
| 804
| 3.109375
| 3
|
[] |
no_license
|
#include "Puntos.h"
Puntos::Puntos(string c, string n) {
fila = n;
columna = c;
}
Puntos::Puntos(ifstream& in) {
fila = SerializadorBinario::deserialize<string>(in);
columna = SerializadorBinario::deserialize<string>(in);
}
string Puntos::toString() const {
return fila + columna ;
}
void Puntos::serializar(ofstream& out) const {
SerializadorBinario::serialize<string>(out, fila);
SerializadorBinario::serialize<string>(out, columna);
}
void Puntos::setPuntos(string f, string c) {
fila = f;
columna = c;
}
void Puntos::setFila(string fil) {
fila = fil;
}
void Puntos::setColumna(string col) {
columna = col;
}
string Puntos::getFila() const {
return fila;
}
string Puntos::getColumna() const {
return columna;
}
|
Java
|
UTF-8
| 4,788
| 1.984375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.optaplanner.constraint.streams.bavet.common;
import java.util.Objects;
import java.util.Set;
import org.optaplanner.constraint.streams.bavet.BavetConstraint;
import org.optaplanner.constraint.streams.bavet.BavetConstraintFactory;
import org.optaplanner.constraint.streams.bavet.uni.BavetAbstractUniConstraintStream;
import org.optaplanner.constraint.streams.common.AbstractConstraintStream;
import org.optaplanner.constraint.streams.common.RetrievalSemantics;
import org.optaplanner.constraint.streams.common.ScoreImpactType;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.stream.Constraint;
import org.optaplanner.core.api.score.stream.ConstraintFactory;
import org.optaplanner.core.api.score.stream.uni.UniConstraintStream;
public abstract class BavetAbstractConstraintStream<Solution_> extends AbstractConstraintStream<Solution_> {
protected final BavetConstraintFactory<Solution_> constraintFactory;
public BavetAbstractConstraintStream(BavetConstraintFactory<Solution_> constraintFactory,
RetrievalSemantics retrievalSemantics) {
super(retrievalSemantics);
this.constraintFactory = constraintFactory;
}
// ************************************************************************
// Penalize/reward
// ************************************************************************
protected Constraint buildConstraint(String constraintPackage, String constraintName, Score<?> constraintWeight,
ScoreImpactType impactType, Object justificationFunction, Object indictedObjectsMapping,
BavetScoringConstraintStream<Solution_> stream) {
var resolvedConstraintPackage =
Objects.requireNonNullElseGet(constraintPackage, this.constraintFactory::getDefaultConstraintPackage);
var resolvedJustificationMapping =
Objects.requireNonNullElseGet(justificationFunction, this::getDefaultJustificationMapping);
var resolvedIndictedObjectsMapping =
Objects.requireNonNullElseGet(indictedObjectsMapping, this::getDefaultIndictedObjectsMapping);
var isConstraintWeightConfigurable = constraintWeight == null;
var constraintWeightExtractor = isConstraintWeightConfigurable
? buildConstraintWeightExtractor(resolvedConstraintPackage, constraintName)
: buildConstraintWeightExtractor(resolvedConstraintPackage, constraintName, constraintWeight);
var constraint =
new BavetConstraint<>(constraintFactory, resolvedConstraintPackage, constraintName, constraintWeightExtractor,
impactType, resolvedJustificationMapping, resolvedIndictedObjectsMapping,
isConstraintWeightConfigurable, stream);
stream.setConstraint(constraint);
return constraint;
}
// ************************************************************************
// Node creation
// ************************************************************************
public abstract void collectActiveConstraintStreams(Set<BavetAbstractConstraintStream<Solution_>> constraintStreamSet);
public BavetAbstractConstraintStream<Solution_> getTupleSource() {
return this;
}
public abstract <Score_ extends Score<Score_>> void buildNode(NodeBuildHelper<Score_> buildHelper);
// ************************************************************************
// Helper methods
// ************************************************************************
protected <A> BavetAbstractUniConstraintStream<Solution_, A> assertBavetUniConstraintStream(
UniConstraintStream<A> otherStream) {
if (!(otherStream instanceof BavetAbstractUniConstraintStream)) {
throw new IllegalStateException("The streams (" + this + ", " + otherStream
+ ") are not built from the same " + ConstraintFactory.class.getSimpleName() + ".");
}
BavetAbstractUniConstraintStream<Solution_, A> other = (BavetAbstractUniConstraintStream<Solution_, A>) otherStream;
if (constraintFactory != other.getConstraintFactory()) {
throw new IllegalStateException("The streams (" + this + ", " + other
+ ") are built from different constraintFactories (" + constraintFactory + ", "
+ other.getConstraintFactory()
+ ").");
}
return other;
}
// ************************************************************************
// Getters/setters
// ************************************************************************
@Override
public BavetConstraintFactory<Solution_> getConstraintFactory() {
return constraintFactory;
}
}
|
JavaScript
|
UTF-8
| 3,320
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
import React, { Component } from 'react'
import './../time.css';
import Switch from '@material-ui/core/Switch';
export default class TimeAPI extends Component {
constructor() {
super();
this.state = {
time: [],
date: [],
format: true,
interval_id: null,
city: null,
}
}
editFormat() {
if (this.state.format === true) {
clearInterval(this.state.interval_id);
this.setState({
interval_id: setInterval(() => this.formatAMPM(new Date()), 1000)
})
}
else {
clearInterval(this.state.interval_id);
this.setState({
interval_id: setInterval(() => this.setTime(), 1000)
})
}
}
formatAMPM() {
var cd = new Date();
var hours = cd.getHours();
var minutes = cd.getMinutes();
var week = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
this.setState({
time: [strTime],
date: [this.zeroPadding(cd.getFullYear(), 4) + '-' + this.zeroPadding(cd.getMonth() + 1, 2) + '-' + this.zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()]]
})
}
setTime() {
var cd = new Date();
var week = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
this.setState({
time: [this.zeroPadding(cd.getHours(), 2) + ':' + this.zeroPadding(cd.getMinutes(), 2) + ':' + this.zeroPadding(cd.getSeconds(), 2)],
date: [this.zeroPadding(cd.getFullYear(), 4) + '-' + this.zeroPadding(cd.getMonth() + 1, 2) + '-' + this.zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()]]
})
}
zeroPadding(num, digit) {
var zero = '';
for (var i = 0; i < digit; i++) {
zero += '0';
}
return (zero + num).slice(-digit);
}
componentDidMount() {
fetch("http://ip-api.com/json/?fields=61439")
.then(response => response.json())
.then(body => (this.setState({ city: body.city })
));
this.setTime();
this.setState({
interval_id: setInterval(() => this.setTime(), 1000)
})
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.checked });
this.editFormat();
};
render() {
return (
<div id="clock">
{this.state.date.map((el, index) => {
return (<p className="date" key={index}> {el} <Switch
checked={this.state.format}
onChange={this.handleChange}
name="format"
inputProps={{ 'aria-label': 'primary checkbox' }}
/></p>)
})}
{this.state.time.map((el, index) => {
return (<p className="time" key={index}> {el}</p>)
})}
<p className="text">TIME ZONE: {this.state.city}</p>
</div>
)
}
}
|
Java
|
UTF-8
| 5,254
| 1.882813
| 2
|
[
"Unlicense"
] |
permissive
|
package com.muskopf.tacotuesday.bl.proc;
import com.muskopf.tacotuesday.TacoTuesdayPersistenceInitializer;
import com.muskopf.tacotuesday.config.TacoTuesdayApiConfiguration;
import com.muskopf.tacotuesday.domain.Employee;
import com.muskopf.tacotuesday.domain.FullOrder;
import com.muskopf.tacotuesday.domain.IndividualOrder;
import com.muskopf.tacotuesday.domain.Taco;
import com.muskopf.tacotuesday.resource.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(classes = {TacoTuesdayApiConfiguration.class})
public class TacoTuesdayResourceMapperTests {
@MockBean
private TacoEmailer tacoEmailer;
@Autowired
private TacoTuesdayResourceMapper mapper;
@Autowired
private TacoTuesdayPersistenceInitializer testHelper;
/**
* Test mapping of Employee --> EmployeeResource --> Employee
*/
@Test
public void test_EmployeeMapping() {
Employee employee = testHelper.createEmployee();
EmployeeResource resource = mapper.mapEmployeeToEmployeeResource(employee);
Employee mappedBack = mapper.mapEmployeeResourceToEmployee(resource);
assertThat(mappedBack)
.usingRecursiveComparison()
.ignoringFields(
"orders"
).isEqualTo(employee);
}
/**
* Tests the mapping of Employee --> NewEmployeeResource --> Employee
*/
@Test
public void test_NewEmployeeResourceMapping() {
Employee employee = testHelper.createEmployee();
NewEmployeeResource resource = mapper.mapEmployeeToNewEmployeeResource(employee);
Employee mappedBack = mapper.mapNewEmployeeResourceToEmployee(resource);
assertThat(mappedBack)
.usingRecursiveComparison()
.ignoringFields(
"slackId"
).isEqualTo(employee);
}
/**
* Tests the mapping of Employee --> UpdateEmployeeResource --> Employee
*/
@Test
public void test_UpdateEmployeeResourceMapping() {
Employee employee = testHelper.createEmployee();
UpdateEmployeeResource resource = mapper.mapEmployeeToUpdateEmployeeResource(employee);
Employee mappedBack = mapper.mapUpdateEmployeeResourceToEmployee(resource);
assertThat(mappedBack)
.usingRecursiveComparison()
.ignoringFields(
"id",
"slackId"
).isEqualTo(employee);
}
/**
* Test mapping of Employee --> UpdateEmployeeBatchResource --> Employee
*/
@Test
public void test_UpdateEmployeeBatchResourceMapping() {
Employee employee = testHelper.createEmployee();
UpdateEmployeeBatchResource resource = mapper.mapEmployeeToUpdateEmployeeBatchResource(employee);
Employee mappedBack = mapper.mapUpdateEmployeeBatchResourceToEmployee(resource);
assertThat(mappedBack)
.usingRecursiveComparison()
.ignoringFields(
"id",
"slackId"
).isEqualTo(employee);
}
/**
* Test mapping of FullOrder --> FullOrderResource --> FullOrder
*/
@Test
public void test_FullOrderMapping() {
FullOrder fullOrder = testHelper.createFullOrder();
FullOrderResource resource = mapper.mapFullOrderToFullOrderResource(fullOrder);
FullOrder mappedBack = mapper.mapFullOrderResourceToFullOrder(resource);
assertThat(mappedBack)
.usingRecursiveComparison()
.ignoringActualNullFields()
.isEqualTo(fullOrder);
}
/**
* Tests the mapping of IndividualOrder --> IndividualOrderResource --> IndividualOrder
*/
@Test
public void test_IndividualOrderMapping() {
IndividualOrder individualOrder = testHelper.createIndividualOrder();
IndividualOrderResource resource = mapper.mapIndividualOrderToIndividualOrderResource(individualOrder);
IndividualOrder mappedBack = mapper.mapIndividualOrderResourceToIndividualOrder(resource);
assertThat(mappedBack)
.usingRecursiveComparison()
.ignoringActualNullFields()
.isEqualTo(individualOrder);
}
/**
* Tests the mapping of Taco --> TacoResource --> Taco
*/
@Test
public void test_TacoMapping() {
List<Taco> tacos = testHelper.loadObjects(Taco.class);
List<TacoResource> resources = mapper.mapTacosToTacoResources(tacos);
List<Taco> mappedBack = resources.stream().map(r -> mapper.mapTacoResourceToTaco(r)).collect(Collectors.toList());
assertThat(tacos).containsExactlyInAnyOrderElementsOf(mappedBack);
}
}
|
Python
|
UTF-8
| 2,087
| 3.78125
| 4
|
[] |
no_license
|
from sys import exit
class home(object):
def __init__(self):
print "Welcome home.."
print "Please come inside.."
raw_input()
def host(self):
l=living()
l.explain()
l.trick()
class living(object):
def __init__(self):
self.colour='pink'
self.door=2
self.window=3
def explain(self):
print "This is the Living room"
print "This is a ",self.colour," room with ",self.door," doors and ",self.window," windows."
print "There is a chair..\n.sit\n.open the door"
self.choice=(raw_input("> "))
def trick(self):
if self.choice=='sit':
print "The chair breaks.. u fall down..You lose"
exit(1)
elif self.choice=='open the door':
print "Good choice!.."
d=dining()
d.explain()
d.trick()
else:
print "bad choice!.."
self.explain()
self.trick()
class dining(object):
def __init__(self):
self.colour='blue'
self.door=3
self.window=4
def explain(self):
print "This is the Dining room"
print "This is a ",self.colour," room with ",self.door," doors and ",self.window," windows."
print "Please sit down and have some food..\n.eat\n.dont eat"
self.choice=raw_input("> ")
def trick(self):
if self.choice=='eat':
print "good choice.."
b=bedroom()
b.explain()
b.trick()
elif self.choice== 'dont eat':
print "A beast appears from nowhere n eats u up!!...you lose!"
exit(1)
else:
print "bad choice!.."
self.explain()
self.trick()
class bedroom(object):
def __init__(self):
self.colour='white'
self.door=1
self.window=2
def explain(self):
print "This is the Bedroom"
print "This is a ",self.colour," room with ",self.door," doors and ",self.window," windows."
print "Please lie down n take rest..\n.lie down\n.dont lie down"
self.choice=raw_input("> ")
def trick(self):
if self.choice== 'lie down':
print "You get lost in dreams forever!..you lose!"
exit(1)
elif self.choice=='dont lie down':
print "A magic door opens...u may escape..You win!Congrats!."
exit(1)
else:
print "bad choice!.."
self.explain()
self.trick()
h=home()
h.host()
|
Markdown
|
UTF-8
| 1,352
| 3.5
| 4
|
[] |
no_license
|
# Answers, week 12
## Part 1: Calling the procedure
We make a list of instances, each one corresponding to a tone. We add four values: the start point, the mid point, the end point, and the name of the tone in question. The procedure will be called **addTone**.
```
@addTone: 230, 230, 230, "ma1"
@addTone: 190, 210, 230, "ma2"
@addTone: 170, 150, 210, "ma3"
@addTone: 230, 190, 150, "ma4"
```
## Part 2: The procedure
Now we prepare the procedure. The first line defines it: we give it the name **addTone**. Then we name the variables, so that the first value in each one of the instances above corresponds to **.start**, the second one to **.mid**, etc.
```
procedure addTone: .start, .mid, .end, .tone$
```
The following lines are very similar to those seen in Week 9: we select the Sound object and create a Manipulation object. Then we create an empty PitchTier object, which we then fill in with the values stated in the procedure.
```
selectObject: "Sound ma"
man=To Manipulation: 0.1, 75, 600
Create PitchTier: ".$tone", 0, 0.5
Add point: 0, .start
Add point: 0.25, .mid
Add point: 0.5, .end
```
After that, we replace the PitchTier. Then we do the resynthesis, which will create a Sound object with the new pitch contour.
```
plusObject: man
Replace pitch tier
selectObject: man
Get resynthesis (overlap-add)
Rename: .tone$
endproc
```
|
Java
|
UTF-8
| 953
| 2.46875
| 2
|
[] |
no_license
|
package com.migie.smith;
import agent.auctionSolution.ontologies.GiveOntology;
import jade.content.onto.BeanOntologyException;
import jade.content.onto.Ontology;
/**
* Extends GiveOntology to allow for the encoding and
* decoding of MBCAccountant.
*
* @see GiveOntology
* @author Grant
*/
@SuppressWarnings("serial")
public class MBCGiveOntology extends GiveOntology{
// Name of the ontology
public static final String ONTOLOGY_NAME = "MBC-Give-Ontology";
// The singleton instance of this ontology
private static Ontology theInstance = new MBCGiveOntology();
/**
* @return The instance of the ontology
*/
public static Ontology getInstance() {
return theInstance;
}
/**
* Calls the parent class to initialise and then adds
* MBCAccountant to the ontology
*/
public MBCGiveOntology(){
super();
try {
add(MBCAccountant.class);
} catch (BeanOntologyException oe) {
oe.printStackTrace();
}
}
}
|
JavaScript
|
UTF-8
| 2,065
| 3
| 3
|
[] |
no_license
|
if (typeof Object.assign !== "function") {
Object.assign = function Object$assign () {
var it = {},
arg,
key;
while (arg = [].shift.call(arguments)) {
if (arg === null || typeof arg !== "object") {
throw new TypeError("Invalid argument");
}
for (key in arg) {
if (arg.hasOwnProperty(key)) {
it[key] = arg[key];
}
}
}
return it;
};
}
//////////////////////
/* get DOM elements */
//////////////////////
if (typeof document.getElementsByClassName !== "function") {
document.getElementsByClassName = function(class_name) {
var elementsArr = [],
elements = this.all || this.getElementsByTagName("*"),
pattern = new RegExp("(^|\\s)" + class_name + "(\\s|$)"),
len = elements.length,
i = 0;
for(; i < len; i++) {
if (pattern.test(elements[i].className)) {
elementsArr.push(elements[i]);
}
}
return elementsArr;
}
}
// get all form elements within an element or in the body (default)
var getFormFields = function (e) {
e = e || document.getElementsByTagName("body")[0];
var elementsArr = [],
tagsArray = ["input", "textarea", "select"],
elements=e.getElementsByTagName("*"),
len = elements.length,
i = 0;
for (; i < len; i++) {
if (tagsArray.indexOf(elements[i].tagName.toLowerCase()) !== -1) {
elementsArr.push(elements[i]);
}
}
return elementsArr;
}
// get element by partial ID by specific tag or by all (default)
var findByPartialID = function (string, tag_name) {
var arr = document.getElementsByTagName(tag_name),
len = arr.length,
i = 0;
tag_name = tag_name || "*";
for (; i < len; i++) {
if (arr[i].id) {
if (arr[i].id.indexOf(string) !== -1) {
return arr[i];
}
}
}
return null;
}
|
C#
|
UTF-8
| 1,360
| 2.71875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Algorithmsnetcore.Common.Map.Base;
namespace Algorithmsnetcore.Common.Map.DFS
{
class DFSTest
{
private DFS<int> _dfs;
public DFSTest()
{
AdjacencyList<int> adjacencyList = new AdjacencyList<int>();
ForDFSNode<int> firstHead = new ForDFSNode<int> { Data = 1 };
ForDFSNode<int> secondHead = new ForDFSNode<int> { Data = 2 };
ForDFSNode<int> thirdHead = new ForDFSNode<int> { Data = 3 };
ForDFSNode<int> forthHead = new ForDFSNode<int> { Data = 4 };
adjacencyList.Nodes.AddRange(new List<ForDFSNode<int>> { firstHead, secondHead, thirdHead, forthHead });
adjacencyList.NeighborsList.Add(firstHead, new List<Node<int>> { secondHead, forthHead });
adjacencyList.NeighborsList.Add(secondHead, new List<Node<int>> { firstHead, thirdHead, forthHead });
adjacencyList.NeighborsList.Add(thirdHead, new List<Node<int>> { secondHead, forthHead });
adjacencyList.NeighborsList.Add(forthHead, new List<Node<int>> { firstHead, secondHead, thirdHead });
_dfs = new DFS<int>(adjacencyList);
}
public void DoDFS()
{
_dfs.DoSearch();
}
}
}
|
C#
|
UTF-8
| 3,583
| 2.953125
| 3
|
[] |
no_license
|
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Translator
{
class YandexTranslator
{
public string Translate(string s, string lang)
{
if (s.Length > 0)
{
WebRequest request = WebRequest.Create("https://translate.yandex.net/api/v1.5/tr.json/translate?"
+ "key=trnsl.1.1.20170127T184343Z.c57386f5c18826ab.c3942baf91d3a5c948253592772906880173fc24"
+ "&text=" + s
+ "&lang=" + lang);
try
{
WebResponse response = request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string line;
if ((line = stream.ReadLine()) != null)
{
TranslationLang translation = JsonConvert.DeserializeObject<TranslationLang>(line);
s = "";
foreach (string str in translation.text)
s += str;
}
}
}
catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); }
return s;
}
else
return "";
}
public Dictionary<string, string> nnn = new Dictionary<string, string>();
public List<string> GetAlldirection()
// public Dictionary<string, string> GetAlldirection()
{
WebRequest request = WebRequest.Create("https://translate.yandex.net/api/v1.5/tr.json/getLangs?"
+ "key=trnsl.1.1.20170127T184343Z.c57386f5c18826ab.c3942baf91d3a5c948253592772906880173fc24"
+ "&ui=" + "ru");
List<string> spisok = new List<string>();
try
{
WebResponse response = request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string line;
if ((line = stream.ReadLine()) != null)
{
TranslationCode translation = JsonConvert.DeserializeObject<TranslationCode>(line);
List<string> st = new List<string>(translation.dirs);
Dictionary<string, string> dd = new Dictionary<string, string>(translation.langs);
foreach (var item in st)
{
string[] arr = item.Split('-');
string s1 = dd[arr[0]];
string s2 = dd[arr[1]];
spisok.Add(s1 + "-" + s2);
nnn.Add(item, (s1 + "-" + s2));
}
}
}
}
catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); }
return spisok;
}
}
class TranslationLang
{
public string code { get; set; }
public string lang { get; set; }
public string[] text { get; set; }
}
class TranslationCode
{
public string[] dirs { get; set; }
public Dictionary<string, string> langs { get; set; }
}
class Translation
{
public Translation()
{
lng = new Dictionary<string, string>();
}
public Dictionary<string, string> lng { get; set; }
public override string ToString()
{
return lng.Values.ToString();
}
}
}
|
C
|
UTF-8
| 7,765
| 3.3125
| 3
|
[] |
no_license
|
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#include <string.h>
#include "functions1.h"
/******************* Static Function Prototypes *******************/
static boardPosArray** createPosArr();// create pointer to arr of board positions function
// update single moves cell funcion
static void UpdateMoves(Move** move, unsigned int* size, char** board, unsigned int row, unsigned int col);
static Move* del_move(Move* move, unsigned int size, unsigned int new_size);// delete move function
static void fill_move_arr(movesArray*** move_arr);// fill example to move arr f
static void fill_board(char *** board);// fill example board f
static void UpdateMoveArr(char** board, movesArray*** moves_arr);// update move arr function
static Move* CreateMove(unsigned int size);// create moves f
static boardPos* build_positions(unsigned int size, Move* move, unsigned int row, unsigned int col);// build position function
/******************* Function Implementation *******************/
boardPosArray** validMoves(char** board, movesArray** moves_arr)// create valid moves board pos arr function
{
// decleration of variables
unsigned int row, col;
boardPosArray** valid_moves_arr;
valid_moves_arr = createPosArr();// create pos arr
UpdateMoveArr(board, &moves_arr);// updating move arr to only valid moves
for (row = 0; row < N; row++)// loop that fills each cell in arr pos
{
for (col = 0; col < M; col++)
{
valid_moves_arr[row][col].size = moves_arr[row][col].size;// calc size
// building postions according to the size
valid_moves_arr[row][col].positions = build_positions(valid_moves_arr[row][col].size, moves_arr[row][col].moves, row, col);
}
}
return valid_moves_arr;//output
}
static void UpdateMoveArr(char** board, movesArray*** moves_arr)// update move arr function
{
// decleration of variables
unsigned int row, col;
movesArray** temp;
temp = *moves_arr;
for (row = 0; row < N; row++)//loop that updates each cell in move arr
{
for (col = 0; col < M; col++)
{
UpdateMoves(&(temp[row][col].moves), &(temp[row][col].size), board, row, col);//updating cell
}
}
*moves_arr = temp;
}
// update single moves cell funcion
static void UpdateMoves(Move** move, unsigned int* size, char** board, unsigned int row, unsigned int col)
{
// decleration of variables
Move* temp;
unsigned int new_size, index, new_row, new_col;
new_size = *size;
temp = *move;
for (index = 0; index < *size; index++)// loop that checks each move validity
{
new_row = row + temp[index].rows;// calc of row
new_col = col + temp[index].cols;// calc of cell
if (!(check_cell_on_board(board, new_row, new_col)))// check cell on board
{
//if not valid
new_size--;// decreasing size
temp[index].rows = 0;
temp[index].cols = 0;
}
}
temp = del_move(temp, *size, new_size);// updating the move cell
*size = new_size;
*move = temp;
}
void allocation_check(void *ptr)//allocation check function
{
if (!ptr)
{
fprintf(stderr, "Allocation error\n");
exit(-1);
}
}
BOOL check_cell_on_board(char** board, unsigned int row, unsigned int col)// check cell on board function
{
// decleration of variables
BOOL res;
res = FALSE;
if ((row >= 0 && row < N) && (col >= 0 && col < M))// check if values arr in the board range
{
if (board[row][col] != CANT_MOVE)//check if the cell has '*';
res = TRUE;
}
return res;//output
}
static Move* del_move(Move* move, unsigned int size, unsigned int new_size)// delete move function
{
// decleration of variables
unsigned int index_old, index_new = 0, move_col, move_row;
Move* new_move = (Move*)malloc((new_size) * sizeof(Move));// memory alloc
allocation_check(new_move);// alloc check
for (index_old = 0; index_old < size; index_old++)// loop that updates moves
{
move_row = move[index_old].rows;
move_col = move[index_old].cols;
if (move_row != 0 || move_col != 0)// if move is empty = not valid
{
new_move[index_new] = move[index_old];// del
index_new++;
}
}
return new_move;//output
}
static boardPosArray** createPosArr()// create pointer to arr of board positions function
{
// decleration of variables
int index;
boardPosArray** new_arr;
new_arr = (boardPosArray**)malloc((N) * sizeof(boardPosArray*));//memory alloc rows
allocation_check(new_arr);//alloc check
for (index = 0; index < N; index++)// loop that alloc each row
{
new_arr[index] = (boardPosArray*)malloc((M) * sizeof(boardPosArray));// memory alloc col
allocation_check(new_arr[index]);//alloc check
}
return new_arr;//output
}
static boardPos* build_positions(unsigned int size, Move* move, unsigned int row, unsigned int col)// build position function
{
// decleration of variables
unsigned int index, calc_row, calc_col;
boardPos* cel = (boardPos*)malloc((size) * sizeof(boardPos));//memory allc
allocation_check(cel);// alloc cell
for (index = 0; index < size; index++)// build each pos loop
{
calc_row = move[index].rows + row;// calc row
calc_col = move[index].cols + col;// calc row
cel[index][0] = 'A' + calc_row;
printf("%c", cel[index][0]);
cel[index][1] = '1' + calc_col;
printf("%c ", cel[index][1]);
}
return cel;//output
}
movesArray** BuildMoveArrey()// build move arr
{
// decleration of variables
int index;
movesArray** move_arr;
move_arr = (movesArray**)malloc((N) * sizeof(movesArray*));// memory alloc
allocation_check(move_arr);//alloc check
for (index = 0; index < N; index++)// create cols for each row
{
move_arr[index] = (movesArray*)malloc((M) * sizeof(movesArray));
allocation_check(move_arr[index]);
}
fill_move_arr(&move_arr);// fill board
return move_arr;
}
static void fill_move_arr(movesArray*** move_arr)// fill moves arr exam f
{
// decleration of variables
unsigned int row, col, size = 5;
movesArray** temp = *move_arr;
for (row = 0; row < N; row++) {
for (col = 0; col < M; col++) {
temp[row][col].size = size;
temp[row][col].moves = CreateMove(temp[row][col].size);
}
}
*move_arr = temp;
}
static Move* CreateMove(unsigned int size) {// create moves for each cell in moves arr
// decleration of variables
Move* new_move;
new_move = (Move*)malloc((size) * sizeof(Move));
allocation_check(new_move);
new_move[0].rows = -1, new_move[0].cols = 1;
new_move[1].rows = 1, new_move[1].cols = -1;
new_move[2].rows = 2, new_move[2].cols = 0;
new_move[3].rows = 0, new_move[3].cols = 2;
new_move[4].rows = 0, new_move[3].cols = 1;
return new_move;//ouput
}
static void fill_board(char *** board)// fill board
{
// decleration of variables
unsigned int row, col;
char** temp;
temp = *board;
for (row = 0; row < N; row++)
{
for (col = 0; col < M; col++)
{
temp[row][col] = CAN_MOVE;
}
}
temp[0][0] = CANT_MOVE;
temp[1][0] = CANT_MOVE;
temp[2][2] = CANT_MOVE;
*board = temp;
}
char** BuildBoard()// build board f
{
// decleration of variables
unsigned int index;
char** board;
board = (char**)malloc((N) * sizeof(char*));// memo alloc
allocation_check(board);// alloc check
for (index = 0; index < N; index++)
{
board[index] = (char*)malloc((M) * sizeof(char));
allocation_check(board[index]);
}
fill_board(&board);
return board;//output
}
void free_board(char ** arr)
{
// decleration of variables
unsigned int index;
for (index = 0; index < N; index++)
{
free(arr[index]);
}
free(arr);
}
void free_pos_mat(boardPosArray** arr)
{
// decleration of variables
unsigned int index;
for (index = 0; index < N; index++)
{
free(arr[index]);
}
free(arr);
}
void free_moves_mat(movesArray** arr)
{
// decleration of variables
unsigned int index;
for (index = 0; index < N; index++)
{
free(arr[index]->moves);
free(arr[index]);
}
free(arr);
}
|
Java
|
UTF-8
| 662
| 2.40625
| 2
|
[] |
no_license
|
package com.lhx.chapter4.aop.aopaspectj;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class GreetingAspect {
@Around("execution(* com.lhx.chapter4.aop.GreetingImpl.*(..))")
public Object around(ProceedingJoinPoint point) throws Throwable {
before();
Object proceed = point.proceed();
after();
return proceed;
}
public void before() {
System.out.println("before");
}
public void after() {
System.out.println("after");
}
}
|
Java
|
UTF-8
| 1,800
| 2.03125
| 2
|
[] |
no_license
|
package com.we.sdk.memsap.service.impl;
import com.we.sdk.memsap.base.vo.Page;
import com.we.sdk.memsap.bean.AddressDic;
import com.we.sdk.memsap.dao.AddressDicDao;
import com.we.sdk.memsap.service.AddressDicService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
@RequiredArgsConstructor
public class AddressDicServiceImpl implements AddressDicService {
private final AddressDicDao addressDicDao;
@Override
public Integer save(AddressDic addressDic) {
return addressDicDao.save(addressDic);
}
@Override
public Integer delete(Integer id) {
return addressDicDao.delete(id);
}
@Override
public Integer update(AddressDic addressDic) {
return addressDicDao.update(addressDic);
}
@Override
public AddressDic getAddressDicById(Integer id) {
return addressDicDao.getAddressDicById(id);
}
@Override
public AddressDic getAddressDicByAddress(String address) {
return addressDicDao.getAddressDicByAddress(address);
}
@Override
public Page<AddressDic> getAddressDicListByCondition(String address, Page<AddressDic> page) {
Integer count = addressDicDao.getAddressDicListCount(address);
page.setTotalCount(count);
page.setData(addressDicDao.getAddressDicListByCondition(address, page));
return page;
}
@Override
public Integer getAddressDicListCount(String address) {
return addressDicDao.getAddressDicListCount(address);
}
@Override
public List<AddressDic> getAddressDicByParentId(Integer parentId) {
return addressDicDao.getAddressDicByParentId(parentId);
}
}
|
Java
|
UTF-8
| 1,606
| 2.453125
| 2
|
[
"MIT"
] |
permissive
|
package src.it.unibo.bd.db.controller;
import java.io.IOException;
import java.sql.SQLException;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
public abstract class ControllerMethods {
public void goToSelectedPage(final VIEW fxmlFileName, final MouseEvent event) throws IOException {
Platform.runLater(() -> {
Parent page = null;
try {
page = FXMLLoader.load(getClass().getResource(fxmlFileName.toString()));
} catch (IOException e) {
e.printStackTrace();
}
Scene scene = new Scene(page);
//This line gets the stage information
Stage window = (Stage) (((Node) event.getSource()).getScene().getWindow());
window.setScene(scene);
window.show();
});
}
public void selectPage(ComboBox<String> comboBox, MouseEvent event,
String selectedItemName, VIEW fxmlFileName) throws IOException {
if (comboBox.getSelectionModel().getSelectedItem().equals(selectedItemName)) {
this.goToSelectedPage(fxmlFileName, event);
}
}
public void displayErrorOnDialog() throws SQLException {
Alert alert = new Alert(AlertType.ERROR, "inserimento non andato a buon fine, controllare i paramentri", ButtonType.CLOSE);
alert.show();
}
}
|
JavaScript
|
UTF-8
| 677
| 3.46875
| 3
|
[] |
no_license
|
function send(){
number_1= document.getElementById("input_number_1").value;
number_2= document.getElementById("input_number_2").value;
actual_answer= parseInt(number_1) * parseInt(number_2);
question_number= "<h4>" + number_1 + " X " + number_2 + "</h4>";
input_box= "<br>Answer : <input type='text' id='input_check_box'>";
check_button= "<br><br><button class='btn btn-info' onclick='check()'>Check</button>"
row= question_number + input_box + check_button;
document.getElementById("div_output").innerHTML= row;
document.getElementById("input_number_1").value= "";
document.getElementById("input_number_2").value= "";
}
|
Java
|
UTF-8
| 1,066
| 2.078125
| 2
|
[] |
no_license
|
package com.starwars.client.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(
collection = "starship"
)
@JsonIgnoreProperties(
ignoreUnknown = true
)
public class Starship {
@Id
private String id;
private String name;
private String model;
private String starship_class;
private String manufacturer;
private String cost_in_credits;
private String length;
private String crew;
private String passengers;
private String max_atmosphering_speed;
private String hyperdrive_rating;
private String MGLT;
private String cargo_capacity;
private String consumables;
private String url;
public String customId(String url){
String[] paths = url.split("/");
return paths[paths.length-1];
}
}
|
JavaScript
|
UTF-8
| 760
| 2.859375
| 3
|
[] |
no_license
|
`use strict`
let html_daySelect, graph
//#region -------LISTENERS--------
const ListenToSelectDay = function(){
html_daySelect.addEventListener('change', function(){
let val = this.value;
getVisitorsByDay(val);
});
}
//#endregion
//#region -------GET FUNCTIONS-------
const getVisitorsByDay = async function(day){
console.log(day);
const response = await fetch(`https://iotcloud-nmct.azurewebsites.net/api/visitors/${day}`);
let data = response.json();
console.log(data);
}
//#endregion
const init = function(){
html_daySelect = document.querySelector('.js-select-day');
ListenToSelectDay();
}
document.addEventListener('DOMContentLoaded', function(){
console.log('Script Geladen!');
init();
});
|
Rust
|
UTF-8
| 3,228
| 3.015625
| 3
|
[] |
no_license
|
pub mod term;
pub mod syntax;
use term::*;
use std::string::*;
fn get_result<T>(name : Vec<u8>, result : Result<T, String>) -> T {
match result {
Ok(term) => term,
Err(err) => {
println!("[Error on `{}`]\n{}", String::from_utf8_lossy(&name), err);
std::process::exit(0);
}
}
}
fn main() {
let (val, defs) = get_result(b"main".to_vec(), syntax::term_from_string_slice("
data Empty : Type
data Unit : Type
| void : Unit
data Bool : Type
| true : Bool
| false : Bool
data Nat : Type
| succ : (n : Nat) -> Nat
| zero : Nat
data Eq : (A : Type, x : A, y : A) -> Type
| refl : (A : Type, x : A) -> Eq(A, x, x)
data Vect : (A : Type, n : Nat) -> Type
| cons : (A : Type, n : Nat, x : A, xs : Vect(A, n)) -> Vect(A, Nat.succ(n))
| nil : (A : Type) -> Vect(A, Nat.zero)
let the(P : Type, x : P) =>
x
let not(b : Bool) =>
case b
| true => Bool.false
| false => Bool.true
: Bool
let add(a : Nat, b : Nat) =>
case a
| succ(pred) => Nat.succ(add(pred, b))
| zero => b
: Nat
let pred(a : Nat) =>
case a
| succ(pred) => pred
| zero => Nat.zero
: Nat
let EFQ(P : Type, f : Empty) =>
case f : P
let induction
( P : (n : Nat) -> Type
, s : (n : Nat, p : P(n)) -> P(Nat.succ(n))
, z : P(Nat.zero)
, n : Nat) =>
case n
| succ(pred) => s(pred, induction(P, s, z, pred))
| zero => z
: P(self)
let tail(A : Type, n : Nat, vect : Vect(A, Nat.succ(n))) =>
case vect
| cons(A, n, x, xs) => xs
| nil(A) => Vect.nil(A)
: (A, n) => Vect(A, pred(n))
let head(A : Type, n : Nat, vect : Vect(A, Nat.succ(n))) =>
case vect
| cons(A, n, x, xs) => x
| nil(A) => Unit.void
: (A, n) => case n
| succ(m) => A
| zero => Unit
: Type
let two
Nat.succ(Nat.succ(Nat.zero))
let four
Nat.succ(Nat.succ(Nat.succ(Nat.succ(Nat.zero))))
let two_plus_two_is_four
the(Eq(Nat, add(two, two), four), Eq.refl(Nat, four))
two_plus_two_is_four
"));
println!("[Term]\n{}", syntax::term_to_string(&val, &mut Vec::new(), true));
println!("");
for (nam, def) in &defs {
get_result(nam.to_vec(), syntax::infer_with_string_error(&def, &defs, false, true));
}
let mut typ : Term = get_result(b"main".to_vec(), syntax::infer_with_string_error(&val, &defs, false, true));
reduce(&mut typ, &defs, true);
println!("[Type]\n{}", syntax::term_to_string(&typ, &mut Vec::new(), true));
println!("");
let mut nor : Term = val.clone();
reduce(&mut nor, &defs, true);
println!("[Norm]\n{}", syntax::term_to_string(&nor, &mut Vec::new(), true));
}
|
PHP
|
UTF-8
| 1,276
| 2.65625
| 3
|
[] |
no_license
|
<?php
namespace Anax\View;
/**
* Render content within an article.
*/
?>
<ul class="left-list">
<li><a href="<?= url("movie1/index") ?>">Visa alla filmer</a></li>
<li><a href="<?= url("movie1/search-title") ?>">Sök titel</a></li>
<li><a href="<?= url("movie1/search-year") ?>">Sök år</a></li>
<li><a href="<?= url("movie1/add") ?>">Add movie</a></li>
</ul>
<form method="get" class="movie-search">
<fieldset>
<legend>Search</legend>
<p>
<label>Title (use % as wildcard):
<input type="search" name="searchTitle" value="<?= htmlentities($searchTitle) ?>"/>
</label>
</p>
<p>
<input type="submit" name="doSearch" value="Search">
</p>
<p><a href="<?= url("movie1/search-title") ?>">Show all</a></p>
</fieldset>
</form>
<table class="movie-box">
<tr class="first">
<th>Rad</th>
<th>Id</th>
<th>Bild</th>
<th>Titel</th>
<th>År</th>
</tr>
<?php $id = -1; foreach ($res as $row) :
$id++; ?>
<tr>
<td><?= $id ?></td>
<td><?= $row->id ?></td>
<td><img class="thumb" src="<?= asset($row->image)?>"></td>
<td><?= $row->title ?></td>
<td><?= $row->year ?></td>
</tr>
<?php endforeach; ?>
</table>
|
Markdown
|
UTF-8
| 7,254
| 2.875
| 3
|
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
---
---
title: 52
---
彻夜无眠。
终于有了勇气,去思考这一辈子该怎么活的问题。
以前,很多工作是自己看不上的,哪怕在教育机构当了两年的老师,那也是一肚子的委屈。现在想起来,我,许晶晶,我凭什么对生活抱有那么高的期待?你有超人的才华吗?有良好的家庭背景吗?有魔鬼的身材和姣美的面容吗?如果都没有,生活凭什么给你更高的评价?生活不是慈善家,它的付出是需要交换的。也许,这些年来,我凭着一张重点大学的文凭,就对生活展开了太多想象。这些想象其实有点虚妄。我的期待,我的野心,超出了我的实力。“你是一个没有实力的人。”当我轻轻嚅动嘴唇,含糊地说出这句话,生怕自己听见,真的接受不了。然后,鼓起勇气,清晰地吐出来,让自己听见,就像有一双无形的手,在用力地挤压心脏,把它挤了出来。我再一次把这句话用更大的声音说出来,似乎要挑战自己的心理承受能力。
当我把这句话对自己说了无数遍,我逐渐地接受了这样一个事实,那就是,必须大幅度地降低对生活的期待,接受自己不愿接受的命运。不能再想那么多,想多了不是什么好事。有那么多女生在当营业员,当广告推销员,当发廊洗头妹,在卖小菜,在下粉,为什么她就不能是这个叫许晶晶的女生呢?我说自己有一张还过得去的文凭吧,可是在麓城,有这张文凭的人,实在是太多了啊!
我躺在床上不敢起身,似乎一起身,迎接我的,就是那样的命运。我在手机上把招聘启事一条条看过去,然后打电话。基本的状态,跟两年前是一样的,想去的地方人家不要,人家要的地方,自己又不想去。不会游泳的人,换个泳池,也还是会溺水。最后我失望了,在床上躺平,盯着天花板发呆。这让我觉得,这样的人生,也不是不可以接受的,反正最后的结局都是一样的,到了那天,就众生平等了。
电话响了。这个世界上还有人能记起我,我有点激动。拿起手机一看,是房东打来的,提醒我,下个季度的房租,已经晚交几天了。我马上看了看手机,里面只有一千多块钱了,不够。三张银行卡都找出来,记得上面已经没有什么钱了。几张银行卡就像被侦察兵反复搜寻过的森林,不会再有意外的潜伏。但我还是下楼去,在社区光大银行的柜员机上,把这些卡一张一张插入检查,希望自己的记忆有误。可是很不幸,记忆是准确的。离开银行,我给盈盈发了信息,说了情况,要她打一千块钱到我手机上,私心却希望她能够多打几百,这段时间我还需要一点生活费。回家的路上,我轻轻撇着嘴角嘲笑自己,嘿,还想躺在那里,过一种简单朴素的生活就算了,自己有这个资格吗?能那么躺着,那是回避残酷挑战的一种方式,可那得家里有几个钱啊!我连躺的资格都没有。嘿。我不能做一个愤青,在各种抱怨中躺下来,理直气壮,一天就过去了,一年就过去了。愤青是废青的前奏,那是一条绝路。嘿。
钱。钱钱。钱钱钱。形势比我想象得要严峻,严峻得多。回到家我马上坐到电脑前,在各种平台上找工作。已经没有从容选择的余地了,是个工作,我就得去。这让我想起上小学时看到邻居家的小男孩,坐在门槛上,呼啦呼啦地,一碗饭很快就吃完了。穷人家的孩子不挑食,穷有穷的好处。
那几天,我打了几十个电话,出门应聘了几次,都没有结果。有一家大超市,工资还行,给我的工作,就是处理顾客退货问题。我去现场看了一下,一个顾客正在那里大声嚷嚷拍桌子,说衬衣的包装本来就是坏的。这个工作实在是太不适合我了。我说回去考虑一下,就离开了。
这样过了几天,我心里更慌了,哪怕是个商场的售货员,自己也只能先接受了再说。我给秦芳打了个电话,说自己准备下几个台阶去找工作了。秦芳怔了一会儿,说:“不行啊,你一下台阶,女大学生这个身份就没有了。一旦贴上下面台阶的标签,再想反身向上,就很难了。”她讲得实在是太对了,我得承认,很对。我说:“可是,那又怎么办呢?”她说:“这实在是人类最大的难题。我实在是……你再缓一下,这几个月,半年,我先帮助你一下吧,每个月两千。”我感到了温暖,心中松弛了,说:“那怎么行?你还要养孩子呢。”她说:“小七是一只吸金兽,可是,这点钱,我还是可以拿出来的。”挂了电话,我手机上就进来了四千块钱。我没收,秦芳几次打电话来催我。我说:“等我山穷水尽再说吧。”其实我已经山穷水尽,手上只有一千多块钱。在麓城混了三年,混出这样一个局面。再这样混三年,基本上,这一辈子就玩完了。
晚上接到一个电话,问我是不是愿意去他们公司当银行卡的推销员。我了解了一下,每天一百块钱底薪,推销一张银行卡,还有一百元奖金。她说,公司上个月最高的拿到了两万多块。这真的是大大地刺激了我。我说:“这么好的工作,抢破头,你们为什么要找我呢?”她说:“我们公司对员工的素质要求是很高的,你没有好的口才,怎么能说服别人呢?”别的本领吧,我没有,要说口才,我还是可以的。我说:“你们怎么知道我在找工作?”她说:“我们是专门跟信息打交道的,有什么信息会不知道?”
最后我才知道,工作地点在海南。我有点犹豫了,说:“在海口吗?”她说:“应该算海口郊区。我们会给你订机票,会派车去机场接你。”我说:“还有飞机坐?”我没坐过飞机,这也给了我一点诱惑。我说:“试一试吧。”她说:“不满意你可以随时回来。”我安心了,说:“那就试一试吧。”
三天后,我到了海口美兰国际机场。果然有车在机场接我。开车的是一个小伙子。上了车我说:“还有别人吗?”他说:“这是专车,你是首长。”车出了机场,越开越偏僻。我说:“这是去哪里呢?”他说:“不是去海口郊区吗?海南岛就这么巴掌大,都算海口郊区。”我越来越不放心,就给秦芳打了个电话,把事情说了,把司机的电话都告诉了她。这样做有点不礼貌,但我有意让司机知道,这样我才有了安全感。司机说:“许小姐对我们还是有点不放心。”我说:“是朋友先问我呢。”司机说:“这个朋友是不是你男朋友?”我说:“是的,他什么都不放心我。”他说:“是我,我也难说放心。这世道,是吧?”又说:“我姓焦,小焦。”
车开了一个小时,穿过一个县城到了一个镇上。下了车,我心里凉了半截。
|
TypeScript
|
UTF-8
| 1,353
| 2.96875
| 3
|
[] |
no_license
|
import * as WebSocket from "ws";
export class WebSocketsService {
private websocketServer: WebSocket.Server;
/**
* Creates instance of this class.
* @param wss Instance of ws server
*/
constructor(wss: WebSocket.Server){
this.websocketServer = wss;
}
/**
* Notifies client that content in the specified folder has been changed.
* Called when one of the following events occurs in the specified folder: file or folder created, file or folder updated, file deleted.
* @param folderPath Content of this folder was modified.
*/
public notifyRefresh(folderPath: string) {
this.notify("refresh", folderPath);
}
/**
* Notifies client that folder was deleted.
* @param folderPath Content of this folder was deleted.
*/
public notifyDelete(folderPath: string) {
this.notify("delete", folderPath);
}
private notify(eventType: string, folderPath: string) {
folderPath = folderPath.replace(/^\/|\/$/g, '');
const notifyObject = {
FolderPath: folderPath,
EventType: eventType
};
this.websocketServer.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(notifyObject));
}
});
}
}
|
Java
|
UTF-8
| 4,883
| 2.5625
| 3
|
[] |
no_license
|
package alt.termos.core;
import alt.termos.util.Arguments;
import alt.termos.util.Unsafe;
import alt.termos.util.UnsafeMemoryMappedFile;
/**
*
* @author Albert Shift
*
*/
public class MetaPage {
public static final int MAGIC = 0x2E464D4D;
public static final long MAGIC_OFFSET = 0;
public static final long MAGIC_SIZE = 4;
public static final int DEFAULT_VERSION = 0x100;
public static final long VERSION_OFFSET = MAGIC_OFFSET + MAGIC_SIZE;
public static final long VERSION_SIZE = 4;
public static final int DEFAULT_DISK_PAGESIZE = 4096;
public static final long DISK_PAGESIZE_OFFSET = VERSION_OFFSET + VERSION_SIZE;
public static final long DISK_PAGESIZE_SIZE = 4;
public static final long REVERVED1_OFFSET = DISK_PAGESIZE_OFFSET + DISK_PAGESIZE_SIZE;
public static final long RESERVED1_SIZE = 4;
public static final long DEFAULT_NEXTNEW_PAGE = 1;
public static final long NEXTNEW_PAGE_OFFSET = REVERVED1_OFFSET + RESERVED1_SIZE;
public static final long NEXTNEW_PAGE_SIZE = 8;
/*
* Needs to be an array of linked lists. Hot, medium, cold and so on. Length of this array can be configurable.
* Not need to be a very big array. Tail of the hot linked list can have the same temperature as a head of cold linked list.
*
* TODO: implement this as a simple array, group of temperature/hit counter is an index
*/
public static final long DEFAULT_FREEHEAD_PAGE = 0;
public static final long FREEHEAD_PAGE_OFFSET = NEXTNEW_PAGE_OFFSET + NEXTNEW_PAGE_SIZE;
public static final long FREEHEAD_PAGE_SIZE = 8;
/*
* Needs to be an array of linked lists, each element has different k (distance from the root node)
*
* TODO: implement this as a simple array, k is an index
*/
public static final long DEFAULT_LEAFHEAD_PAGE = 0;
public static final long LEAFHEAD_PAGE_OFFSET = FREEHEAD_PAGE_OFFSET + FREEHEAD_PAGE_SIZE;
public static final long LEAFHEAD_PAGE_SIZE = 8;
public static final long LAST_OFFSET = LEAFHEAD_PAGE_OFFSET + LEAFHEAD_PAGE_SIZE;
private final long address;
private final long fileSize;
public MetaPage(UnsafeMemoryMappedFile mmf) {
Arguments.notNull(mmf);
Arguments.greater(mmf.getSize(), LAST_OFFSET);
this.address = mmf.getAddress();
this.fileSize = mmf.getSize();
}
public long getAddress() {
return address;
}
public long getFileSize() {
return fileSize;
}
public int getMagic() {
return Unsafe.UNSAFE.getInt(address + MAGIC_OFFSET);
}
public void setMagic(int magic) {
Unsafe.UNSAFE.putInt(address + MAGIC_OFFSET, magic);
}
public int getVersion() {
return Unsafe.UNSAFE.getInt(address + VERSION_OFFSET);
}
public void setVersion(int version) {
Unsafe.UNSAFE.putInt(address + VERSION_OFFSET, version);
}
public long getDiskPageSize() {
return (long) Unsafe.UNSAFE.getInt(address + DISK_PAGESIZE_OFFSET);
}
public void setDiskPageSize(long diskPageSize) {
Unsafe.UNSAFE.putInt(address + DISK_PAGESIZE_OFFSET, (int) diskPageSize);
}
public long getNextNewPage() {
return Unsafe.UNSAFE.getLong(address + NEXTNEW_PAGE_OFFSET);
}
public void setNextNewPage(long pageNum) {
Unsafe.UNSAFE.putLong(address + NEXTNEW_PAGE_OFFSET, pageNum);
}
public long getFreeHeadPage() {
return Unsafe.UNSAFE.getLong(address + FREEHEAD_PAGE_OFFSET);
}
public void setFreeHeadPage(long pageNum) {
Unsafe.UNSAFE.putLong(address + FREEHEAD_PAGE_OFFSET, pageNum);
}
public long getLeafHeadPage() {
return Unsafe.UNSAFE.getLong(address + LEAFHEAD_PAGE_OFFSET);
}
public void setLeafHeadPage(long pageNum) {
Unsafe.UNSAFE.putLong(address + LEAFHEAD_PAGE_OFFSET, pageNum);
}
public void formatNew(long diskPageSize) {
Arguments.greater(fileSize, diskPageSize);
Arguments.aligned(fileSize, diskPageSize);
setMagic(MAGIC);
setVersion(DEFAULT_VERSION);
setDiskPageSize(diskPageSize);
setNextNewPage(DEFAULT_NEXTNEW_PAGE);
setFreeHeadPage(DEFAULT_FREEHEAD_PAGE);
setLeafHeadPage(DEFAULT_LEAFHEAD_PAGE);
}
public boolean isNew() {
return getMagic() == 0;
}
public void validate() {
int magic = getMagic();
if (magic != MAGIC) {
throw new IllegalStateException("wrong magic " + Integer.toHexString(magic));
}
int version = getVersion();
if (version != DEFAULT_VERSION) {
throw new IllegalStateException("unsupported version " + version);
}
long diskPageSize = getDiskPageSize();
Arguments.positive(diskPageSize);
Arguments.pageAligned(diskPageSize);
Arguments.aligned(fileSize, diskPageSize);
long pageNum = getNextNewPage();
Arguments.positive(pageNum);
Arguments.greaterOrEquals(fileSize, pageNum * diskPageSize);
pageNum = getFreeHeadPage();
Arguments.positive(pageNum);
Arguments.greaterOrEquals(fileSize, pageNum * diskPageSize);
pageNum = getLeafHeadPage();
Arguments.positive(pageNum);
Arguments.greaterOrEquals(fileSize, pageNum * diskPageSize);
}
}
|
Java
|
UTF-8
| 1,680
| 2.328125
| 2
|
[] |
no_license
|
package com.liewmanchoi.processor;
import com.liewmanchoi.annotation.PigeonService;
import com.liewmanchoi.pigeon.rpc.common.enumeration.ErrorEnum;
import com.liewmanchoi.pigeon.rpc.common.exception.RPCException;
import com.liewmanchoi.pigeon.rpc.config.ProviderBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
/**
* @author wangsheng
* @date 2019/7/12
*/
@Slf4j
public class ProviderBeanPostProcessor extends AbstractBeanPostProcessor {
@Override
@SuppressWarnings("unchecked")
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> beanClass = bean.getClass();
if (!beanClass.isAnnotationPresent(PigeonService.class)) {
// 只处理被@PigeonService注解的Bean
return bean;
}
PigeonService pigeonService = beanClass.getAnnotation(PigeonService.class);
Class<?> interfaceClass = pigeonService.interfaceClass();
if (interfaceClass == void.class) {
Class<?>[] interfaceClasses = beanClass.getInterfaces();
if (interfaceClasses.length >= 1) {
interfaceClass = interfaceClasses[0];
} else {
log.error(">>> 服务[{}]没有实现接口 <<<", beanClass);
throw new RPCException(
ErrorEnum.SERVICE_DIDNT_IMPLEMENT_INTERFACE, "服务{}没有实现接口", beanClass);
}
}
ProviderBean providerBean = new ProviderBean();
initCommon(providerBean);
providerBean.setInterfaceClass(interfaceClass);
providerBean.setBean(bean);
// 暴露服务
providerBean.export();
log.info(">>> 暴露服务[{}] <<<", interfaceClass);
return bean;
}
}
|
Java
|
UTF-8
| 994
| 1.835938
| 2
|
[] |
no_license
|
package com.zsc.mnc.shop.service;
import com.zsc.mnc.shop.model.Category;
import com.zsc.mnc.shop.model.Product;
import com.zsc.mnc.shop.model.ProductDetails;
import com.zsc.mnc.shop.model.ProductImage;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
public interface ProductService {
int addProduct(Product product);
Product queryProductById(long id);
List<Product> getAllProduct();
int modifyProduct(Product product);
List<Product> fuzzyQuery(String name);
int deleteProduct(long id);
int addCategory(Category category);
List<Category> categoryList();
int insertProductImages(List<ProductImage> productImageList);
List<ProductDetails> ProductDetails(long id);
ProductDetails getProductDetailById(long id);
long queryOldStock(long id);
int updateStock(long id,long stock);
long queryOldSaleCount(long id);
int updateSaleCount(long id,long stock);
}
|
JavaScript
|
UTF-8
| 1,099
| 3.03125
| 3
|
[] |
no_license
|
const game = (() => {
let currentPlayer;
let otherPlayer;
const startGame = (players) => {
currentPlayer = players.player1;
otherPlayer = players.player2;
};
const getCurrentPlayer = () => currentPlayer;
const getOtherPlayer = () => otherPlayer;
const gameOver = (gameBoard) => {
const winConditions = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],
[1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
for (let i = 0; i < winConditions.length; i += 1) {
if (gameBoard.getBoard()[winConditions[i][0]] === gameBoard.getBoard()[winConditions[i][1]]
&& gameBoard.getBoard()[winConditions[i][0]] === gameBoard.getBoard()[winConditions[i][2]]
&& gameBoard.getBoard()[winConditions[i][0]] !== '') {
return `${currentPlayer.getName()} won the game!`;
}
}
if (gameBoard.getSuccessfulMoves() === 9) {
return 'The game is tied';
}
[currentPlayer, otherPlayer] = [otherPlayer, currentPlayer];
return false;
};
return {
startGame, getCurrentPlayer, getOtherPlayer, gameOver,
};
})();
export default game;
|
Python
|
UTF-8
| 5,809
| 3.65625
| 4
|
[] |
no_license
|
# File: Graph.py
# Description:Create a number of functions that will allow us to transverse a graph
# Student Name:Paul Vonder Haar
# Student UT EID:pmv347
# Partner UT EID:
# Course Name: CS 313E
# Unique Number:
# Date Created:
# Date Last Modified:
class Vertex(object):
def __init__(self,label):
self.label=label
self.visited=False
def wasVisited(self):
return self.visited
def getLabel(self):
return(self.label)
def __str(self):
return(str(self.label))
class Stack (object):
def __init__ (self):
self.stack = []
# add an item to the top of the stack
def push (self, item):
self.stack.append ( item )
# remove an item from the top of the stack
def pop (self):
return self.stack.pop()
# check what item is on top of the stack without removing it
def peek (self):
return self.stack[len(self.stack) - 1]
# check if a stack is empty
def isEmpty (self):
return (len(self.stack) == 0)
# return the number of elements in the stack
def size (self):
return (len(self.stack))
class Queue (object):
def __init__ (self):
self.queue = []
def enqueue (self, item):
self.queue.append (item)
def dequeue (self):
return (self.queue.pop(0))
def isEmpty (self):
return (len (self.queue) == 0)
def size (self):
return len (self.queue)
class Graph(object):
def __init__(self,):
self.Vertices=[]
self.adjMat=[]
#Checks if a particular vertex is in the graph
def hasVertex(self,label):
for i in range(len(self.Vertices)):
if(label==(self.Vertices[i]).label):
return(True)
return(False)
def addVertex(self,label):
if (not self.hasVertex(label)):
self.Vertices.append(Vertex(label))
for i in range(len(self.Vertices)-1):
self.adjMat[i].append(0)
newRow=[]
for i in range(len(self.Vertices)):
newRow.append(0)
self.adjMat.append(newRow)
def addDirectedEdge(self,start,finish,weight=1):
self.adjMat[start][finish]=weight
def getAdjUnivisitedVertex(self,v):
nVert=len(self.Vertices)
for i in range(nVert):
if((self.adjMat[v][i]>0) and(not(self.Vertices[i].wasVisited()))):
return i
return(-1)
def dfs(self,v):
theStack=Stack()
(self.Vertices[v]).visited=True
print(self.Vertices[v].label)
theStack.push(v)
while(not theStack.isEmpty()):
u=self.getAdjUnivisitedVertex(theStack.peek())
if(u==-1):
u=theStack.pop()
else:
(self.Vertices[u]).visited=True
print(self.Vertices[u].label)
theStack.push(u)
nVert=len(self.Vertices)
for i in range(nVert):
(self.Vertices[i]).visited=False
def getIndex(self,label):
nVert=len(self.Vertices)
for i in range(nVert):
if(self.Vertices[i].label==label):
return(i)
return(-1)
def bfs(self,v):
theQueue=Queue()
(self.Vertices[v]).visited=True
print(self.Vertices[v].label)
theQueue.enqueue(v)
while(not theQueue.isEmpty()):
v1=theQueue.dequeue()
v2=self.getAdjUnivisitedVertex(v1)
while(v2!=-1):
(self.Vertices[v2]).visited=True
print(self.Vertices[v2].label)
theQueue.enqueue(v2)
v2=self.getAdjUnivisitedVertex(v1)
def getEdgeWeight(self,fromVertexLabel,toVertexLabel):
fromVertIndex=self.getIndex(fromVertexLabel)
toVertIndex=self.getIndex(toVertexLabel)
if((self.adjMat[fromVertIndex][toVertIndex])==0):
return(-1)
else:
return((self.adjMat[fromVertIndex][toVertIndex]))
def getNeighbors(self,vertexLabel):
vertexIndex=self.getIndex(vertexLabel)
Indexanswer=[]
answer=[]
for i in range(len(self.adjMat[vertexIndex])):
if(self.adjMat[vertexIndex][i]!=0):
Indexanswer.append(i)
for j in range(len(Indexanswer)):
answer.append(self.Vertices[Indexanswer[j]].label)
return(answer)
def getVertices(self):
answer=[]
for i in range(len(self.Vertices)):
answer.append(self.Vertices[i].label)
return(answer)
def hasCycle(self):
for v in range(len (self.Vertices)):
theStack=Stack()
Answer=[]
theStack.push(v)
while(not theStack.isEmpty()):
u=self.getAdjUnivisitedVertex(theStack.peek())
if(u==v):
return(True)
if(u==-1):
u=theStack.pop()
else:
(self.Vertices[u]).visited=True
theStack.push(u)
nVert=len(self.Vertices)
for i in range(nVert):
(self.Vertices[i]).visited=False
return(False)
def edgeList(self):
weightList=[]
VertexList=[]
for i in range(len(self.adjMat)):
for j in range(len(self.adjMat[i])):
if(self.adjMat[i][j]!=0):
weightList.append(self.adjMat[i][j])
VertexList.append(self.Vertices[i].label+"--"+self.Vertices[j].label)
for i in range(len(weightList)):
minimum=i
for j in range(i,len(weightList)):
if(weightList[j]<weightList[minimum]):
minimum=j
temp=weightList[i]
tempStr=VertexList[i]
weightList[i]=weightList[minimum]
VertexList[i]=VertexList[minimum]
weightList[minimum]=temp
VertexList[minimum]=tempStr
for i in range(len(weightList)):
print(VertexList[i]+" "+str(weightList[i]))
def main():
MyGraph=Graph()
InData=open("graph.txt","r")
numVert=int(InData.readline())
for i in range(numVert):
CurrentCity=InData.readline()
CurrentCity=CurrentCity.strip()
MyGraph.addVertex(CurrentCity)
numEdges=int(InData.readline())
for j in range(numEdges):
temp=InData.readline()
EdgeData=temp.split()
MyGraph.addDirectedEdge(int(EdgeData[0]),int(EdgeData[1]),int(EdgeData[2]))
city=InData.readline()
cityIndex=MyGraph.getIndex(city)
print("DFS from "+city+":")
MyGraph.dfs(cityIndex)
print()
print("BFS from "+city+":")
MyGraph.bfs(cityIndex)
print()
print("Topological Sort:")
MyVertices=MyGraph.getVertices()
for i in range(len(MyVertices)):
print(MyVertices[i])
print()
print("Ascending Edges:")
MyGraph.edgeList()
main()
|
C++
|
UTF-8
| 2,709
| 2.671875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#include <vector>
#include <eventpp/udp/sync_udp_client.hpp>
#include <eventpp/udp/udp_server.hpp>
#include "test.h"
static int g_count = 0;
static bool g_exit = false;
static uint64_t g_timeout_ms = 1000;
static void OnMessage(eventpp::udp::Server * udpsrv, eventpp::EventLoop * loop, const eventpp::udp::MessagePtr msg)
{
g_count++;
eventpp::udp::SendMessage(msg);
usleep(100);
if (memcmp(msg->data(), "stop", msg->size()) == 0)
{
g_exit = true;
}
}
static void Init()
{
g_count = 0;
g_exit = false;
}
TEST_CASE("testUDPServer")
{
// LOG_TRACE << __func__;
Init();
std::vector<int> ports(2, 0);
ports[0] = 15368;
ports[1] = 15369;
eventpp::udp::Server * udpsrv = new eventpp::udp::Server;
udpsrv->SetMessageHandler(std::bind(&OnMessage, udpsrv, std::placeholders::_1, std::placeholders::_2));
REQUIRE(udpsrv->Init(ports));
REQUIRE(udpsrv->Start());
usleep(100); //wait udpsrv started
// LOG_TRACE << "udpserver started.";
int loop = 10;
for (int i = 0; i < loop; ++i)
{
std::string req = "data xxx";
std::string resp = eventpp::udp::sync::Client::DoRequest("127.0.0.1", ports[0], req, g_timeout_ms);
REQUIRE(req == resp);
resp = eventpp::udp::sync::Client::DoRequest("127.0.0.1", ports[1], req, g_timeout_ms);
REQUIRE(req == resp);
}
REQUIRE(g_count == 2 * loop);
eventpp::udp::sync::Client::DoRequest("127.0.0.1", ports[0], "stop", g_timeout_ms);
REQUIRE(g_count == 2 * loop + 1);
eventpp::udp::sync::Client::DoRequest("127.0.0.1", ports[1], "stop", g_timeout_ms);
REQUIRE(g_count == 2 * loop + 2);
while (!g_exit)
{
usleep(1);
}
REQUIRE(g_exit);
udpsrv->Stop(true);
REQUIRE(udpsrv->IsStopped());
delete udpsrv;
}
TEST_CASE("testUDPServerGraceStop")
{
Init();
int port = 53669;
eventpp::udp::Server * udpsrv = new eventpp::udp::Server;
udpsrv->SetMessageHandler(std::bind(&OnMessage, udpsrv, std::placeholders::_1, std::placeholders::_2));
REQUIRE(udpsrv->Init(port));
REQUIRE(udpsrv->Start());
usleep(100); //wait udpsrv started
int loop = 10;
for (int i = 0; i < loop; ++i)
{
std::string req = "data xxx";
std::string resp = eventpp::udp::sync::Client::DoRequest("127.0.0.1", port, req, g_timeout_ms);
REQUIRE(req == resp);
}
REQUIRE(g_count == loop);
eventpp::udp::sync::Client::DoRequest("127.0.0.1", port, "stop", g_timeout_ms);
REQUIRE(g_count == loop + 1);
while (!g_exit)
{
usleep(1);
}
REQUIRE(g_exit);
udpsrv->Stop(true);
REQUIRE(udpsrv->IsStopped());
delete udpsrv;
}
|
JavaScript
|
UTF-8
| 3,877
| 2.703125
| 3
|
[] |
no_license
|
export function compare(a, b) {
if (a.priority < b.priority) return -1;
if (a.priority > b.priority) return 1;
return 0;
}
var Resource = require("./Resource").Resource;
var State = require("./State").State;
var RESOURSECOLOR = require("./constants").RESOURSECOLOR;
var COLOR = require("./constants").COLOR;
export class ICPP{
constructor(tasks, res=[]) {
this.tasks = tasks;
console.log(tasks)
this.inUsedRes = [];
this.instant = 0;
}
getResources(tasks, str = false) {
let resList = []; // array<Resource>
let addedRes = []; // array<string>
for (let i = 0; i < tasks.length; i++) {
const task = tasks[i];
for (let j = 0; j < task.seq.length; j++) {
const pres = task.seq[j];
let iOfnex = addedRes.indexOf(pres);
if (iOfnex == -1) {
resList.push(new Resource(pres, task.priority));
addedRes.push(pres);
} else {
resList[iOfnex].setPriority(task.priority);
// addedRes[iOfnex]
}
}
resList.sort(compare);
if (str) return addedRes;
return resList;
}
}
ICPPScheduler(tasks) {
let newtasks = [];
let qlq = false;
let inExTask = null;
tasks.sort(compare);
let resources = this.getResources(tasks);
let resourcesStr = this.getResources(tasks, true);
for (let index = tasks.length - 1; index >= 0; index--) {
const task = tasks[index];
if (task.release <= this.instant && !task.hasFinish()) {
let nextMove = task.getNextAction();
let iOfnex = this.inUsedRes.indexOf(nextMove);
let presIndex = resourcesStr.indexOf(nextMove);
if (this.inUsedRes.length == 1 && !task.byMe()) {
// if (iOfnex != -1 && !task.byMe()) {
if (inExTask && task.priority0 < inExTask.priority0)
task.addState(new State(0, 0, COLOR.BLANCHE), true);
else
task.addState(new State(0, 0, COLOR.ROUGE, "B"), true);
} else {
if (!qlq) {
qlq = true;
task.addState(new State(0, 0, RESOURSECOLOR[nextMove])); //COLOR.VERT))
if (nextMove != "E") {
if (iOfnex == -1) {
// resourese index to raise task priority
let presIndex = resourcesStr.indexOf(nextMove);
if (presIndex != -1)
task.raisePriority(resources[presIndex].priority);
this.inUsedRes.push(nextMove);
inExTask = task;
}
if (task.hasFinish()) {
iOfnex = this.inUsedRes.indexOf(nextMove);
this.inUsedRes.splice(iOfnex, 1);
inExTask = null;
} else {
let newNext = task.getNextAction();
if (nextMove != newNext) {
// have to remove res
iOfnex = this.inUsedRes.indexOf(nextMove);
// resourese index to normal task priority
// let presIndex = resourcesStr.indexOf(nextMove)
task.defaultPriority();
this.inUsedRes.splice(iOfnex, 1);
inExTask = null;
}
}
}
inExTask = task;
} else {
task.addState(new State(0, 0, COLOR.BLANCHE), true);
}
}
}
newtasks.push(task);
}
if (this.instant < 50) this.instant++;
return newtasks;
}
}
|
Java
|
UTF-8
| 420
| 2.953125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package models.decorator;
public abstract class ComponentDecorator extends Component{
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
@Override
public void operation() {
System.out.println("Operation in " + this.getClass().getName());
if (component!= null){
component.operation();
}
}
}
|
Java
|
UTF-8
| 156
| 2.515625
| 3
|
[] |
no_license
|
package com.ghs.aop;
public class Human implements Sleepable {
@Override
public void sleep() {
System.out.println("正在睡觉!");
}
}
|
C#
|
UTF-8
| 2,016
| 2.84375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace ModeD
{
class Program
{
static void Main(string[] args)
{
string ConnexString;
ConnexString = "Data Source=.;Initial Catalog=Client;Integrated Security=True";
SqlConnection Connex = new SqlConnection(ConnexString);
SqlCommand CommanSelect = Connex.CreateCommand();
CommanSelect.CommandText = "Select * from [dbo].[tblClient]";
SqlDataAdapter sqlDadapter = new SqlDataAdapter();
sqlDadapter.SelectCommand = CommanSelect;
DataSet Datseet = new DataSet();
sqlDadapter.Fill(Datseet);
SqlCommandBuilder ccmdb = new SqlCommandBuilder(sqlDadapter);
////Ajouter un Client
//DataRow Dr1 = Datseet.Tables[0].NewRow();
//Dr1["Cin"] = "kb12333";
//Dr1["Id"] = 3;
//Dr1["Fname"] = "JOhn";
//Dr1["Lname"] = "wick";
//Dr1["Nb_Phone"] = 500;
//Dr1["Email"] = "jjjj@john";
//Datseet.Tables[0].Rows.Add(Dr1);
//sqlDadapter.Update(Datseet);
//////Modifier un Client
//DataRow Client4 = Datseet.Tables[0].Rows[0];
//Client4["Fname"] = "WICKK";
//sqlDadapter.Update(Datseet);
//////Supprimer premier Client
DataRow Pro = Datseet.Tables[0].Rows[0];
Pro.Delete();
sqlDadapter.Update(Datseet);
////Afficher Client
//foreach (DataRow ligne in Datseet.Tables[0].Rows)
//{
// Console.WriteLine("Cin = {0} | Id = {1} | Fname = {2} | Lname = {3} | Nb_Phone = {4} | Email = {5}", ligne[0],ligne[1],ligne[2], ligne[3], ligne[4], ligne[5]);
// Console.WriteLine("\n");
//}
Console.ReadLine();
}
}
}
|
Python
|
UTF-8
| 4,654
| 3.375
| 3
|
[] |
no_license
|
# -*- coding: UTF-8 -*-
import turtle
import math
import random
# Tela do Jogo
tela = turtle.Screen()
tela.bgcolor('black')
tela.title('Space Invaders')
tela.bgpic('space_invaders_background.gif')
turtle.register_shape('invader.gif')
turtle.register_shape('player.gif')
# Bordas do Jogo
bordas = turtle.Turtle()
bordas.speed(0)
bordas.color('white')
bordas.penup() #Levantando a 'caneta' para mudar a posição da turtle sem 'riscar'
bordas.setposition(-300,-300)
bordas.pendown() #Descendo a 'caneta'
bordas.pensize(3) #Grossura da ponta da 'caneta'
for side in range(4): #Um retangulo
bordas.fd(600) #Foward
bordas.rt(90) #Feft
bordas.hideturtle()
# Pontuação durante o jogo
pontos = 0
# Mostrar a pontuação
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color('white')
score_pen.penup()
score_pen.setposition(-290,280)
scorestring = 'Pontuação: %s' %pontos
score_pen.write(scorestring, False, align='left', font=("Arial", 14, "normal"))
score_pen.hideturtle()
# Nave do jogador
player = turtle.Turtle()
player.color('blue')
player.shape('player.gif')
player.penup()
player.speed(0)
#player.turtlesize(.5,.5,.5)
#player.setundobuffer
player.setposition(0, -250)
player.setheading(90)
playerspeed = 25
# Quantidade de enemigos no jogo
number_of_enemies = 10
enemies = []
enemyspeed = 5
#lista de inimgos
for i in range(number_of_enemies):
# Criando os enimigos
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.color(random.choice(['red', 'green', 'yellow']))
enemy.shape('invader.gif')
enemy.penup()
enemy.speed(0)
#enemy.turtlesize(.5,.5,.5)
x = random.randint(-200, 200)
y = random.randint(100, 150)
enemy.setposition(x, y)
# Criar a bala da Nave do jogador
bullet = turtle.Turtle()
bullet.color('yellow')
bullet.shape('triangle')
bullet.penup()
bullet.speed(0)
bullet.setheading(90)
bullet.shapesize(0.5,0.5)
bullet.hideturtle()
bulletspeed = 50
# Definir o estado da bala
# Ready
# Firing
bulletstate = 'ready'
# Movimentar o jogador
def move_left():
x = player.xcor()
x = x - playerspeed
if (x < -315):x = -315
player.setx(x)
def move_right():
x = player.xcor()
x = x + playerspeed
if (x > 315): x = 315
player.setx(x)
def fire_bullet():
global bulletstate
if bulletstate == 'ready':
bulletstate = 'firing'
# Movimentar a bola
x = player.xcor()
y = player.ycor() + 10
bullet.setposition(x,y)
bullet.showturtle()
def isColision(t1,t2):
distance = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2))
if distance < 25:
return True
else:
return False
'''
# Receber os comandos do jogador teclado
turtle.listen()
turtle.onkey(move_left, 'Left')
turtle.onkey(move_right, 'Right')
turtle.onkey(fire_bullet, 'space')
'''
moving = 'left'
closiest_e = 1000
# Main game loop
while True:
# Movimentar os Inimigos
for enemy in enemies:
x = enemy.xcor()
x = x + enemyspeed
enemy.setx(x)
e_dist = enemy.ycor()
if (e_dist < closiest_e):
closiest_e = e_dist
right_e = enemy
# Mover todos os inimigos para baixo quando acertar as bordas
if (enemy.xcor() > 280 or enemy.xcor() < -280):
for e in enemies:
y = e.ycor()
y = y - 20
e.sety(y)
enemyspeed *= -1
# Checar se há colisão
if isColision(bullet, enemy):
# Resetar a bullet
bullet.hideturtle()
bulletstate = 'ready'
bullet.setposition(0, -400) # Evitar colisões futuras
x = random.randint(-200, 200)
y = random.randint(100, 250)
enemy.setposition(x, y)
# Atualizar a Pontuação
pontos = pontos + 100
scorestring = "Pontuação: %s" %pontos
score_pen.clear()
score_pen.write(scorestring, False, align='left', font=("Arial", 14, "normal"))
if isColision(player, enemy):
player.hideturtle()
enemy.hideturtle()
print ("Game Over")
break
# Movimentar a nave
if (right_e.xcor() > player.xcor()):
move_right()
else:
move_left()
fire_bullet()
# Movimentar a bala
if bulletstate == 'firing':
y = bullet.ycor()
y = y + bulletspeed
bullet.sety(y)
# Checar se a bala já chegou no limite da tela
if bullet.ycor() > 275:
bullet.hideturtle()
bulletstate = 'ready'
|
PHP
|
UTF-8
| 632
| 2.625
| 3
|
[] |
no_license
|
<?php
namespace App\Traits;
use App\Exceptions\NoSlugParamsException;
trait SluggableTrait
{
public static function boot()
{
parent::boot();
static::created(function ($entity) {
if ( !$entity->sluggable) {
throw new NoSlugParamsException(get_class($entity) . ' use SluggableTrait but has no sluggable param');
}
$stringToSlug = $entity->{$entity->sluggable['build_from']};
$entity->{$entity->sluggable['save_to']} = str_slug($stringToSlug) . '-' . $entity->id;
$entity->update();
});
}
}
|
Java
|
UTF-8
| 3,238
| 2.203125
| 2
|
[] |
no_license
|
package com.socialcoding.models;
/**
* Created by cloverhearts on 2016-12-06.
*/
public class CctvLocationDetail {
final transient String PUBLIC_CCTV_TYPE = "PUBLIC";
final transient String PRIVATE_CCTV_TYPE = "PRIVATE";
private long cctvId;
private String purpose;
private String source;
private String address;
private String borough;
private String dong;
private String range;
private String department;
private String pixel;
private String form;
private String installedAt;
public CctvLocationDetail(long cctvId,
String purpose,
boolean isPublic,
String address,
String borough,
String dong,
String range,
String department,
String pixel,
String form,
String installedAt) {
this.cctvId = cctvId;
this.purpose = purpose;
this.address = address;
this.borough = borough;
this.dong = dong;
this.range = range;
this.department = department;
this.pixel = pixel;
this.form = form;
this.installedAt = installedAt;
if (isPublic == true) {
this.source = PUBLIC_CCTV_TYPE;
} else {
this.source = PRIVATE_CCTV_TYPE;
}
}
public boolean isPublic() {
return this.source.equals(PUBLIC_CCTV_TYPE);
}
public String getPUBLIC_CCTV_TYPE() {
return PUBLIC_CCTV_TYPE;
}
public String getPRIVATE_CCTV_TYPE() {
return PRIVATE_CCTV_TYPE;
}
public long getCctvId() {
return cctvId;
}
public void setCctvId(long cctvId) {
this.cctvId = cctvId;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBorough() {
return borough;
}
public void setBorough(String borough) {
this.borough = borough;
}
public String getDong() {
return dong;
}
public void setDong(String dong) {
this.dong = dong;
}
public String getRange() {
return range;
}
public void setRange(String range) {
this.range = range;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getPixel() {
return pixel;
}
public void setPixel(String pixel) {
this.pixel = pixel;
}
public String getForm() {
return form;
}
public void setForm(String form) {
this.form = form;
}
public String getInstalledAt() {
return installedAt;
}
public void setInstalledAt(String installedAt) {
this.installedAt = installedAt;
}
}
|
Python
|
UTF-8
| 419
| 4.25
| 4
|
[] |
no_license
|
#!/usr/bin/python3
# Description: Demander deux nombres à l’utilisateur et afficher le résultat
# Author: Thomas HATUEL
# Date: 23/10/2018
print("choisi un nombre")
value1 = input()
try:
value1 = int(value1)
except ValueError:
pass
print("choisi un autre nombre")
value2 = input()
try:
value2 = int(value2)
except ValueError:
pass
print("leurs somme est �gale a ")
print(value1 + value2)
|
TypeScript
|
UTF-8
| 2,051
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
import PropertyChangeSupport from './PropertyChangeSupport';
import Data from './Data';
export class PropertyBinder implements PropertyChangeSupport {
private propertyClass1: string;
private propertyClass2: string;
private data1: Data;
private data2: Data;
// works like a lock
private applyingChange: boolean = false;
constructor(data1: Data, data2: Data, propertyClass1: string, propertyClass2: string) {
this.data1 = data1;
this.data2 = data2;
this.propertyClass1 = propertyClass1;
this.propertyClass2 = propertyClass2;
}
static bind(data1: Data, data2: Data, property1: string, property2: string) {
if (!data1 || !data2 || !property1) {
console.error('NullValue!!');
return null;
}
const propertyBinder = new PropertyBinder(data1, data2, property1, property2);
propertyBinder.bind();
return propertyBinder;
}
propertyChange(entity: Data, property: string, oldValue: any, newValue: any): void {
if (!this.applyingChange) {
this.applyingChange = true;
if (entity === this.data1) {
// fire to data2
this.data2.setValue(this.propertyClass2, newValue);
} else if (entity === this.data2) {
// fire to data1
this.data1.setValue(this.propertyClass1, newValue);
}
this.applyingChange = false;
}
}
protected bind() {
// public addListener(control: Control, property?: string)
// todo: set value immediately
this.data1.setValue(this.propertyClass1, this.data2.getValue(this.propertyClass2));
this.data1.addListener(this, this.propertyClass1);
this.data2.addListener(this, this.propertyClass2);
}
protected unbind() {
// public addListener(control: Control, property?: string)
this.data1.removeListener(this, this.propertyClass2);
this.data1.removeListener(this, this.propertyClass2);
}
}
|
Java
|
UTF-8
| 1,118
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.android.zd112.ui.view.player.media;
/**
* Created by etongdai on 2018/3/20.
*/
public class VideoPlayerManager {
public static VideoPlayer FIRST_FLOOR_JZVD;
public static VideoPlayer SECOND_FLOOR_JZVD;
public static VideoPlayer getFirstFloor() {
return FIRST_FLOOR_JZVD;
}
public static void setFirstFloor(VideoPlayer videoPlayer) {
FIRST_FLOOR_JZVD = videoPlayer;
}
public static VideoPlayer getSecondFloor() {
return SECOND_FLOOR_JZVD;
}
public static void setSecondFloor(VideoPlayer videoPlayer) {
SECOND_FLOOR_JZVD = videoPlayer;
}
public static VideoPlayer getCurrentJzvd() {
if (getSecondFloor() != null) {
return getSecondFloor();
}
return getFirstFloor();
}
public static void completeAll() {
if (SECOND_FLOOR_JZVD != null) {
SECOND_FLOOR_JZVD.onCompletion();
SECOND_FLOOR_JZVD = null;
}
if (FIRST_FLOOR_JZVD != null) {
FIRST_FLOOR_JZVD.onCompletion();
FIRST_FLOOR_JZVD = null;
}
}
}
|
Markdown
|
UTF-8
| 6,699
| 3.015625
| 3
|
[] |
no_license
|
# linkbuilder
[](https://travis-ci.org/osvaldopina/linkbuilder)
[](https://gitter.im/osvaldopina/linkbuilder?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
# Changes from 0.3.0
Before 0.4.0-SNAPSHOT the annotation @LinkDestination was named @GenerateUriTemplateFor
# How to use it.
## Include the dependency
Add the following dependency to your project:
```xml
<dependency>
<groupId>com.github.osvaldopina</groupId>
<artifactId>linkbuilder</artifactId>
<version>0.3.0</version>
</dependency>
```
Or the following dependency for the version under development:
```xml
<dependency>
<groupId>com.github.osvaldopina</groupId>
<artifactId>linkbuilder</artifactId>
<version>0.4.0-SNAPSHOT</version>
</dependency>
```
### Purpose
The framework was created to generate links and links templates for Spring Hateoas web
applications. In this new version, besides the builder, you can create the links using only annotations.
In the [complete documentation](https://github.com/osvaldopina/linkbuilder/wiki/Documentation)
you will find instructions for
[creating links via builder](https://github.com/osvaldopina/linkbuilder/wiki/Documentation#2-classic-link-builder),
via annotations made on the
[controller](https://github.com/osvaldopina/linkbuilder/wiki/Documentation#31-controller-links) and / or
[resources](https://github.com/osvaldopina/linkbuilder/wiki/Documentation#32-resource-links).
Below is a summary of link building via builder and resource annotation
### Creating links with a classic builder
* Indicate the methods that will be destiny of the links with ``@LinkDestination`` (or ``@GanerateUriTemplateFor`` in 0.3.0 and before)
```java
@RestController
public class ResourcesRestController {
@RequestMapping("/resource1/{path_param}")
@LinkDestination
public ResourceSupport oneResource(
@PathVariable("path_param") String pathParam,@RequestParam("query_param") String queryParam) {
return null;
}
@RequestMapping("/resource2/{path_param}")
@LinkDestination
public ResourceSupport otherResource(
@PathVariable("path_param") String pathParam,@RequestParam("query_param") String queryParam) {
return null;
}
}
```
* Inject the `LinksBuilderFactory`
```java
@Autowired
private LinksBuilderFactory linksBuilderFactory;
```
* Create the `LinksBuilder` which is a builder for a set of links.
```java
LinksBuilder linksBuilder = linksBuilderFactory.create(resource);
```
* For each link call `link()` on `LinksBulder` to create a builder for a link.
```java
ResourceSupport resource = new ResourceSupport();
LinksBuilder linksBuilder = linksBuilderFactory.create(resource);
linksBuilder.link()
.withRel("first-rel")
.fromControllerCall(ResourcesRestController.class)
.oneResource("path", "query")
linksBuilder.link()
.withRel("second-rel")
.fromControllerCall(ResourcesRestController.class)
.otherResource("path", "query");
linksBuilder.buildAndSetAll();
```
* Then when you call `buildAndSetAll()` in the `LinksBuilder` all links will be created and
added to `Resouce` instance.
```java
linksBuilder.buildAndSetAll();
```
The following json will be generated:
```json
{
"_links":{
"first-rel":{
"href":"http://localhost/resource1/path?query_param=query"
},
"second-rel":{
"href":"http://localhost/resource2/path?query_param=query"
}
}
}
```
### Use annotations to generate links
* Leave the controller methods you want to point in the same way:
```java
@RequestMapping("/direct-link/{path}")
@LinkDestination(rel = "direct-link")
public void directLink(@RequestParam(value = "query", required = false) String query,
@PathVariable("path") String path) {
}
@RequestMapping("/direct-link/templated")
@LinkDestination(rel = "direct-link-templated")
public void directLinkTemplated(
@RequestParam(value = "non_templated", required = false) String nonTemplated,
@RequestParam(value = "templated", required = false) String templated) {
}
```
* Annotate the controller method with `@LinkDestination` (or ``@GanerateUriTemplateFor`` in 0.3.0 and before):
```java
@RequestMapping("/")
@LinkDestination(rel = "root")
public Resource root() {
Resource resource = new Resource();
resource.setQueryValue("anyQueryValue");
resource.setPathValue("anyPathValue");
return resource;
}
```
* And annotate the resource:
```java
@Links({
@Link(controller = RootRestController.class, rel = "root", overridedRel = "self"),
@Link(controller = RootRestController.class, rel = "direct-link",
variables = {
@Variable(name = "query", value = "#resource.queryValue"),
@Variable(name = "path", value = "#resource.pathValue")
}),
@Link(controller = RootRestController.class, rel = "direct-link", overridedRel = "direct-link-overrided",
variables = {
@Variable(name = "query", value = "#resource.queryValue"),
@Variable(name = "path", value = "#resource.pathValue")
}),
@Link(controller = RootRestController.class, rel = "direct-link-templated",
templated = true,
variables = {
@Variable(name = "templated", value = "'templated-value'")
})
})
public class Resource extends ResourceSupport {
private String queryValue;
private String pathValue;
public String getQueryValue() {
return queryValue;
}
public void setQueryValue(String queryValue) {
this.queryValue = queryValue;
}
public String getPathValue() {
return pathValue;
}
public void setPathValue(String pathValue) {
this.pathValue = pathValue;
}
}
```
The following json will be generated:
```json
{
"queryValue":"anyQueryValue",
"pathValue":"anyPathValue",
"_links":{
"direct-link":{
"href":"http://localhost/direct-link/anyPathValue?query=anyQueryValue"
},
"direct-link-overrided":{
"href":"http://localhost/direct-link/anyPathValue?query=anyQueryValue"
},
"direct-link-templated":{
"href":"http://localhost/direct-link/templated?templated=templated-value{&non_templated}",
"templated":true
},
"self":{
"href":"http://localhost/"
}
}
}
```
|
Java
|
UTF-8
| 504
| 2.078125
| 2
|
[] |
no_license
|
package com.gresstenan.wisnu.repository;
import com.gresstenan.wisnu.models.Tutorial;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface TutorialRepository extends MongoRepository<Tutorial, String> {
Page<Tutorial> findByPublished(boolean published, Pageable pageable);
Page<Tutorial> findByTitleContaining(String title, Pageable pageable);
}
|
Python
|
UTF-8
| 242
| 2.5625
| 3
|
[] |
no_license
|
#! /usr/bin/env python3
from enum import Enum
"""
牌的颜色枚举类
"""
class CardColorEnum(Enum):
# 黑桃
SPADE = '黑桃'
# 红桃
HEART = '红桃'
# 梅花
CLUB = '梅花'
# 方片
DIAMOND = '方片'
|
Java
|
UTF-8
| 9,478
| 1.742188
| 2
|
[] |
no_license
|
package com.fanwe;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.fanwe.application.App;
import com.fanwe.application.SysConfig;
import com.fanwe.businessclient.R;
import com.fanwe.config.AppConfig;
import com.fanwe.constant.Constant;
import com.fanwe.http.InterfaceServer;
import com.fanwe.http.listener.SDRequestCallBack;
import com.fanwe.library.customview.ClearEditText;
import com.fanwe.library.dialog.SDDialogManager;
import com.fanwe.library.utils.SDViewBinder;
import com.fanwe.model.AccountInfoModel;
import com.fanwe.model.ApplyInfoModel;
import com.fanwe.model.ApplyResultModel;
import com.fanwe.model.BizUserCtlDoLoginActModel;
import com.fanwe.model.LocalUserModel;
import com.fanwe.model.RequestModel;
import com.fanwe.service.AppUpgradeService;
import com.fanwe.umeng.UmengPushManager;
import com.fanwe.utils.SDDialogUtil;
import com.fanwe.utils.SDInterfaceUtil;
import com.fanwe.utils.SDToast;
/**
* 登入
*/
public class LoginActivity extends TitleBaseActivity implements OnClickListener {
private ClearEditText mEt_username;
private ClearEditText mEt_password;
private Button mBtn_login;
private String mBiz_email;
private String mBiz_pwd;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.act_login);
init();
}
private void init() {
register();
initTitle();
startUpgradeService();
SysConfig.getInstance().setCheckUpdate(true);
}
private void register() {
mEt_username = (ClearEditText) findViewById(R.id.act_login_et_username);
mEt_password = (ClearEditText) findViewById(R.id.act_login_et_password);
mBtn_login = (Button) findViewById(R.id.act_login_btn_login);
mBtn_login.setOnClickListener(this);
// 再次登入显示保存账号
mEt_username.setText(AppConfig.getUserName());
}
private void initTitle() {
SDViewBinder.setTextView(mTitle, "登录");
}
private void startUpgradeService() {
Intent updateIntent = new Intent(this, AppUpgradeService.class);
startService(updateIntent);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.act_login_btn_login:
loginclick();
break;
}
}
public void onRegister(View view) {
startActivity(new Intent(mActivity, RegisterActivity.class));
}
private void loginclick() {
if (verifyReqeustParams()) {
requestLoginInterface();
}
}
private boolean verifyReqeustParams() {
mBiz_email = mEt_username.getText().toString();
mBiz_pwd = mEt_password.getText().toString();
if (TextUtils.isEmpty(mBiz_email) || TextUtils.isEmpty(mBiz_pwd)) {
SDToast.showToast("账号或密码不能为空");
return false;
}
return true;
}
private void requestLoginInterface() {
RequestModel model = new RequestModel();
model.putCtlAct("biz_user", "dologin");
model.put("account_name", mBiz_email);
model.put("account_password", mBiz_pwd);
model.put("device_token", UmengPushManager.getPushAgent().getRegistrationId());
InterfaceServer.getInstance().requestInterface(model, new SDRequestCallBack<BizUserCtlDoLoginActModel>() {
private Dialog nDialog;
@Override
public void onFinish() {
if (nDialog != null) {
nDialog.dismiss();
}
}
@Override
public void onSuccess(BizUserCtlDoLoginActModel actModel) {
if (!SDInterfaceUtil.dealactModel(actModel, null)) {
switch (actModel.getStatus()) {
case 0:
if (actModel.getCheck_info() != null) {
ApplyResultModel applyResultModel = actModel.getCheck_info();
if(applyResultModel.getIs_pay() == 0) {
//未支付入住费用,再次编辑
requestInfo(applyResultModel);
} else {
Intent intent = new Intent(mActivity, ApplyResultActivity.class);
intent.putExtra(Constant.ExtraConstant.EXTRA_MODEL, applyResultModel);
startActivity(intent);
}
}
break;
case 1:
if(actModel.getAccount_info() != null) {
dealLoginSuccess(actModel.getAccount_info());
}
break;
}
}
}
@Override
public void onStart() {
nDialog = SDDialogUtil.showLoading("登录中...");
}
});
}
private void dealLoginSuccess(AccountInfoModel accountInfoModel) {
LocalUserModel user = new LocalUserModel();
user.setUser_id(accountInfoModel.getAccount_id());
user.setSubmit_id(accountInfoModel.getSubmit_id());
user.setSupplier_id(accountInfoModel.getSupplier_id());
user.setAccount_name(accountInfoModel.getAccount_name());
user.setAccount_password(accountInfoModel.getAccount_password());
user.setAccount_type(accountInfoModel.getAccount_type());
user.setQr_code(accountInfoModel.getQr_code());
user.setIs_new(accountInfoModel.getIs_new());
App.getApp().setmLocalUser(user);
// 保存账号
AppConfig.setUserName(accountInfoModel.getAccount_name());
if (accountInfoModel.getIs_new() == 0) {
//登录成功进入主页之前,需要判断是否已经申请加盟
startActivity(new Intent(mActivity, MainActivity.class));
finish();
} else {
//申请类别选择
startActivity(new Intent(mActivity, ApplyTypeActivity.class));
finish();
}
}
//没有支付的账户,需要再次编辑,获取数据
private void requestInfo(final ApplyResultModel resultModel) {
RequestModel model = new RequestModel();
model.putCtlAct("biz_member", "get_supplier_info");
model.put("supplier_id", resultModel.getSubmit_id());//商户的id
InterfaceServer.getInstance().requestInterface(model, new SDRequestCallBack<ApplyInfoModel>() {
@Override
public void onFinish() {
SDDialogManager.dismissProgressDialog();
}
@Override
public void onSuccess(ApplyInfoModel actModel) {
SDDialogManager.dismissProgressDialog();
actModel.setSubmit_id(resultModel.getSubmit_id());
if (!SDInterfaceUtil.dealactModel(actModel, null) && actModel.getStatus() == 1) {
//0 普通 ,1 会员店 ,2 商户合伙人,3个人合伙人
Intent intent;
switch (resultModel.getType()) {
case 1:
intent = new Intent(mActivity, ApplyHYDActivity.class);
intent.putExtra(Constant.ExtraConstant.EXTRA_OTHER_MODEL, actModel);
intent.putExtra(Constant.ExtraConstant.EXTRA_TYPE, Constant.Apply.EDIT_HYD);
startActivity(intent);
break;
case 2:
intent = new Intent(mActivity, ApplyHHRActivity.class);
intent.putExtra(Constant.ExtraConstant.EXTRA_OTHER_MODEL, actModel);
intent.putExtra(Constant.ExtraConstant.EXTRA_TYPE, Constant.Apply.EDIT_COMPANY_HHR);
startActivity(intent);
break;
case 3:
intent = new Intent(mActivity, ApplyHHRActivity.class);
intent.putExtra(Constant.ExtraConstant.EXTRA_OTHER_MODEL, actModel);
intent.putExtra(Constant.ExtraConstant.EXTRA_TYPE, Constant.Apply.EDIT_PERSON_HHR);
startActivity(intent);
break;
}
}
}
@Override
public void onStart() {
SDDialogManager.showProgressDialog("正在获取数据,请稍候...");
}
});
}
/*TODO
* 彩蛋,删除账户
* */
public void deleteAccount(View view) {
RequestModel model = new RequestModel();
model.putCtlAct("biz_member", "delete_supplier");
model.put("account_name", "15982034811");
InterfaceServer.getInstance().requestInterface(model, new SDRequestCallBack<String>() {
@Override
public void onFinish() {
}
@Override
public void onSuccess(String actModel) {
}
@Override
public void onStart() {
}
});
}
}
|
Java
|
UTF-8
| 2,764
| 2.015625
| 2
|
[] |
no_license
|
/**
*
*/
package win.caicaikan.controller;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import win.caicaikan.constant.SsqConstant;
import win.caicaikan.repository.mongodb.entity.ssq.SsqResultEntity;
import win.caicaikan.service.internal.DaoService;
import win.caicaikan.service.internal.DaoService.Condition;
import win.caicaikan.service.rule.RuleService;
import win.caicaikan.service.rule.RuleTemplate.Result;
import win.caicaikan.service.rule.ssq.RuleDisplayTimes;
/**
* @Desc
* @author wewenge.yan
* @Date 2016年12月16日
* @ClassName HistoryController
*/
@Controller
@RequestMapping(value = { "history" })
public class HistoryController {
@Autowired
private DaoService daoService;
@Autowired
private RuleService ruleService;
@Autowired
private RuleDisplayTimes displayTimes;
@RequestMapping(value = { "" })
public String index(HttpServletRequest request, ModelMap map) {
return "history/index";
}
@RequestMapping(value = { "ssq" })
public String queryHistoryOfSsq(HttpServletRequest request, ModelMap map) {
Condition condition = new Condition();
condition.setOrderBy(daoService.getIdColName(SsqResultEntity.class));
condition.setLimit(100);
List<SsqResultEntity> ssqs = daoService.query(condition, SsqResultEntity.class);
if (!CollectionUtils.isEmpty(ssqs)) {
SsqResultEntity ssq = ssqs.get(0);
try {
String nextTermNoOfSsq = ruleService.getNextTermNoOfSsq(ssq);
map.put("nextTermNoOfSsq", nextTermNoOfSsq);
String nextTermOpenDateOfSsq = ruleService.getNextTermOpenDateOfSsq(ssq.getOpenTime());
map.put("nextTermOpenDateOfSsq", nextTermOpenDateOfSsq);
} catch (RuntimeException e) {
e.printStackTrace();
}
map.put("ssq", ssq);
map.put("redBalls", Arrays.asList(ssq.getRedNumbers().split(",")));
map.put("blueBalls", Arrays.asList(ssq.getBlueNumbers().split(",")));
}
Result countResult = displayTimes.countDisplayTimes(ssqs, 100);
map.put("redBallLabels", SsqConstant.RED_NUMBERS);
map.put("blueBallLabels", SsqConstant.BLUE_NUMBERS);
map.put("countRedBalls", countResult.getRedMap().values());
map.put("countBlueBalls", countResult.getBlueMap().values());
return "history/ssq";
}
@RequestMapping(value = { "dlt" })
public String queryHistoryOfDlt(HttpServletRequest request, ModelMap map) {
map.put("words", "<p>Hello,World!</p>");
return "history/dlt";
}
}
|
Java
|
UTF-8
| 208
| 1.84375
| 2
|
[] |
no_license
|
package com.yunqin.bearmall.inter;
/**
* Created by chenchen on 2018/8/12.
*/
public interface OnPartSnatchListener {
void onBuySuccess(int postition,int count);
void onBuyFailer(String msg);
}
|
Java
|
UTF-8
| 2,089
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
package core;
import generator.PuzzleGenerator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import utils.Utils;
/**
* Main class of the project. Opens a data set and solves all instances
* in the set using a certain heuristic algorithm. Certain metrics that are
* recorded during the solving process are accumulated. Once the data set is
* completely solved the final results, statistics, and summary are displayed.
*
* @author Martin Sieniawski msien009@uottawa.ca
*
*/
public class Runner {
/**
* Main method.
*
* @param args
*/
public static void main (String[] args) {
// Run an algorithm on the data-set, record metrics, and display results.
Loader loader = new Loader();
if (!loader.load("data/" + args[0]))
{
PuzzleGenerator.main(null);
loader.load("data/dataset.txt");
}
int s = 0;
try
{
s = Integer.parseInt(args[1]);
} catch (Exception e) {}
Solver solver = s == 0 ? new BruteForceSolver() : s == 1 ? new BacktrackingSolver() : new GeneticSolver();
Result result;
List<Long> elapsedTimes = new ArrayList<Long>();
List<Integer> operationCounts = new ArrayList<Integer>();
while (loader.hasNext()) {
result = solver.solve(loader.getNext());
elapsedTimes.add(result.getTimeElapsed());
operationCounts.add(result.getOperationCount());
}
System.out.println("Min time: " + Collections.min(elapsedTimes));
System.out.println("Max time: " + Collections.max(elapsedTimes));
System.out.println("Average time: " + Utils.computeLongAverage(elapsedTimes));
System.out.println();
System.out.println("Min operations: " + Collections.min(operationCounts));
System.out.println("Max operations: " + Collections.max(operationCounts));
System.out.println("Average operations: " + Utils.computeIntAverage(operationCounts));
}
}
|
C++
|
UTF-8
| 1,318
| 2.875
| 3
|
[] |
no_license
|
#pragma once
#include "tf_base.h"
namespace tensorflow_c_api
{
class tensor : private not_copyable
{
public:
tensor(data d, const std::int64_t* dims, std::int32_t num_dims, size_t len)
{
m_value = TF_AllocateTensor(static_cast<TF_DataType>(d), dims, num_dims, len);
}
tensor(TF_Tensor* b)
{
m_value = b;
}
~tensor()
{
TF_DeleteTensor(m_value);
}
tensor(tensor&& o)
{
m_value = o.m_value;
o.m_value = nullptr;
}
tensor& operator=(tensor&& o)
{
if (&o != this)
{
m_value = o.m_value;
o.m_value = nullptr;
}
}
operator TF_Tensor *() const
{
return m_value;
}
data type() const
{
return static_cast<data>(TF_TensorType(m_value));
}
std::int32_t num_dims() const
{
return TF_NumDims(m_value);
}
size_t byte_size() const
{
return TF_TensorByteSize(m_value);
}
void* bytes() const
{
return TF_TensorData(m_value);
}
private:
TF_Tensor * m_value;
};
}
|
Java
|
UTF-8
| 1,810
| 3.5625
| 4
|
[] |
no_license
|
package com.bridgelabz.employeewagecomputation;
public class EmployeeWage {
//constants
public static final int IS_FULL_TIME = 1;
public static final int IS_PART_TIME = 2;
//instance variables
public int empWagePerHour;
public int maxWokringDays;
public int maxWorkingHrs;
public String companyName;
//constructor
public EmployeeWage(String companyName,int empWagePerHour,int maxWorkingDays,int maxWorkingHrs)
{
this.companyName = companyName;
this.empWagePerHour = empWagePerHour;
this.maxWokringDays = maxWorkingDays;
this.maxWorkingHrs = maxWorkingHrs;
}
public void calculateEmployeeWage()
{
//variables
int monthlyEmpWage=0;
int totalWorkingDays=0;
int totalEmpHrs=0;
System.out.println("Welcome to Employee Computation Program");
while (totalWorkingDays<maxWokringDays && totalEmpHrs<maxWorkingHrs)
{
int empHrs=0;
int dailyEmpWage=0;
totalWorkingDays++;
double empCheck = Math.floor(Math.random() * 10) % 3;
switch ((int)empCheck) {
case IS_FULL_TIME:
System.out.println("Employee is full time present");
empHrs=8;
break;
case IS_PART_TIME:
System.out.println("Employee is part time present");
empHrs=4;
default:
System.out.println("Employee is absent");
}
dailyEmpWage = empWagePerHour *empHrs;
totalEmpHrs += empHrs;
monthlyEmpWage += dailyEmpWage;
}
System.out.println("Employee Wage for a month in "+companyName+ " is "+monthlyEmpWage);
}
public static void main(String args[]) {
EmployeeWage bridgelabz = new EmployeeWage("Bridgelabz",20,20,100);
bridgelabz.calculateEmployeeWage();
EmployeeWage dmart = new EmployeeWage("Dmart",15,25,150);
dmart.calculateEmployeeWage();
EmployeeWage reliance= new EmployeeWage("Reliance",20,30,200);
reliance.calculateEmployeeWage();
}
}
|
Python
|
UTF-8
| 1,672
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.face.models import FaceAttributeType
KEY = "1837b9d29e0b4a22843d103a7ca8b3c9"
ENDPOINT = "https://westus2.api.cognitive.microsoft.com/"
class NoFaceFoundException(Exception):
def __init__(self, filepath):
self.message = "File: {}".format(filepath)
def get_face_emotion(filepath):
"""Gets emtion information about faces in provided image.
Args:
filepath (str): Full path to input file. Must be one of: .png, .jpg, .gif. File size from 1KB to 6MB.
Returns:
emotion_data (OrderedDict): Returns data on each emotion each face is showing. Largest face is first.
"""
face_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY))
with open(filepath, "rb") as face_fd:
detected_faces = face_client.face.detect_with_stream(face_fd, return_face_attributes=FaceAttributeType.emotion)
if not detected_faces:
raise NoFaceFoundException(filepath)
emotion_data = {}
emotion_data["face"] = []
for face in detected_faces:
emotion_data["face"].append({
"anger": face.face_attributes.emotion.anger,
"contempt": face.face_attributes.emotion.contempt,
"disgust": face.face_attributes.emotion.fear,
"happiness": face.face_attributes.emotion.happiness,
"neutral": face.face_attributes.emotion.neutral,
"sadness": face.face_attributes.emotion.sadness,
"surprise": face.face_attributes.emotion.surprise
})
return emotion_data
|
Java
|
UTF-8
| 2,635
| 2.3125
| 2
|
[] |
no_license
|
package com.example.wordbook.domain.word.service.word_userwordbook;
import com.example.wordbook.domain.study.entity.Study;
import com.example.wordbook.domain.word.dto.request.UpdateWordDTO;
import com.example.wordbook.domain.word.dto.response.WordDetailDTO;
import com.example.wordbook.domain.word.entity.Word;
import com.example.wordbook.domain.word.repository.WordRepository;
import com.example.wordbook.domain.word.service.userwordbook.GetWordOfUserWordBookService;
import com.example.wordbook.domain.word.service.userwordbook.UpdateWordOfUserWordBookService;
import com.example.wordbook.domain.wordbook.entity.UserWordBook;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.BDDMockito.given;
public class UpdateWordOfUserWordBookServiceTest extends WordOfUserWordBookServiceTest {
@Mock
private WordRepository wordRepository;
@Mock
private GetWordOfUserWordBookService getWordOfUserWordBookService;
@Test
@DisplayName("정상적으로 개인 단어장에 단어를 수정하는 테스트")
public void updateWordAtUserWordBook() {
//given
UpdateWordOfUserWordBookService updateWordOfUserWordBookService = new UpdateWordOfUserWordBookService(
wordRepository,
wordOfUserWordBookToWordDetailDtoMapper,
getWordOfUserWordBookService
);
UserWordBook userWordBook = domainFactory.getUserWordBook();
UpdateWordDTO updateWordDTO = UpdateWordDTO.builder()
.voca("apple")
.meaning("사과")
.build();
Word word = userWordBook.getWords().get(0);
given(wordRepository.save(any(Word.class))).willReturn(word);
given(getWordOfUserWordBookService.getEntityByUserIdAndWordBookIdAndWordId(anyLong(), anyLong(), anyLong()))
.willReturn(word);
//when
Long user = userWordBook.getUser().getId();
Long wordBookId = userWordBook.getId();
Long wordId = word.getId();
WordDetailDTO wordDetailDTO = updateWordOfUserWordBookService.update(user, wordBookId, wordId, updateWordDTO);
//then
assertThat(wordDetailDTO).isNotNull();
assertThat(wordDetailDTO.getId()).isEqualTo(word.getId());
assertThat(wordDetailDTO.getVoca()).isEqualTo(word.getVoca());
assertThat(wordDetailDTO.getMeaning()).isEqualTo(word.getMeaning());
}
}
|
Java
|
UTF-8
| 2,975
| 3.921875
| 4
|
[] |
no_license
|
import java.io.*;
import java.util.*;
import java.math.*;
//I created my own HashSet class for the 100% solution
public class MyHashSet<K extends Comparable<K>> implements Set<K>{
//private Node class. Pretty much the same node that we would use in a normal linked list
private class Node{
K key;
Node next;
public Node(K key){
this.key = key;
next = null;
}
}
//The main arraylist where everything is kept
private ArrayList<Node> daArray;
//keep track of the max capacity of the array (for load capacity)
private int maxCap;
//how many elements are currently loaded in the data structure
private int size;
public MyHashSet(){
daArray = new ArrayList<Node>(10);
maxCap = 10;
size = 0;
//initialize each of the indexes with null
for(int i = 0; i < maxCap; i++)
daArray.add(null);
}
//return how many elements in the structure
public int size(){
return size;
}
//Use's java's hash method to return the index where we will store the key
private int getKeyIndex(K key){
int hashInt = key.hashCode();
int arrayindex = Math.abs(hashInt % maxCap);
return arrayindex;
}
//Add method
public void add(K key){
//get the index where we are going to add the key
int index = getKeyIndex(key);
Node n = daArray.get(index);
//checks to see if there is a duplicate
while(n != null){
if(n.key.equals(key))
return;
n = n.next;
}
//increment size
size++;
n = daArray.get(index);
Node newOne = new Node(key);
newOne.next = n;
//add the new node to the end of the linked list at the index
daArray.set(index, newOne);
//check the load factor, making sure its below .65
if((double)(size/maxCap) >= 0.65){
//if the load factor is larger, then double the array size
ArrayList<Node> temp = daArray;
daArray = new ArrayList<Node>();
maxCap = 2 * maxCap;
size = 0;
//re add everything into the new array
for(int i = 0; i < maxCap; i++)
daArray.add(null);
for(Node xNode : temp){
while(xNode != null){
add(xNode.key);
xNode = xNode.next;
}
}
}
}
//Check to see if the data structure contains the key
public boolean contains(K key){
//find out where the key should go
int index = getKeyIndex(key);
Node n = daArray.get(index);
//check to see if the key is there
while(n != null){
if(n.key.equals(key))
//if it is here then return true
return true;
n = n.next;
}
//otherwise return false
return false;
}
//puts all the elements into an ArrayList and returns the list
public List<K> toList(){
ArrayList<K> tempList = new ArrayList<K>(size);
for(Node tempNode : daArray){
while(tempNode != null){
tempList.add(tempNode.key);
tempNode = tempNode.next;
}
}
return tempList;
}
}
|
Java
|
UTF-8
| 978
| 2.640625
| 3
|
[] |
no_license
|
package com.dmma.dashboard.gwt.core.client.types;
import com.dmma.dashboard.gwt.core.client.i18n.DashboardMessages;
public enum TipDirectionType {
isMtoB( 1, DashboardMessages.MSG.tipDirectionBrokerToBanker()),
isBtoM( 2, DashboardMessages.MSG.tipDirectionBankerToBroker());
private Integer id;
private String title;
public static TipDirectionType getById(Integer id){
for(TipDirectionType type: TipDirectionType.values()){
if(type.getId()==id)
return type;
}
return null;
}
public static String getTitleById(Integer id){
TipDirectionType type = getById(id);
if(type!=null) return type.getTitle();
return "null";
}
private TipDirectionType(Integer id , String title){
this.setId(id);
this.setTitle(title);
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
|
PHP
|
UTF-8
| 1,281
| 2.671875
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: jacky
* Date: 2019/11/3
* Time: 下午 02:10
*/
namespace common\sso;
use common\sso\vendor\facebook\FacebookLoginHelper;
use common\sso\vendor\google\GoogleLoginHelper;
use Exception;
use Facebook\Exceptions\FacebookSDKException;
class Sso
{
public function login($vendor)
{
switch ($vendor) {
case Vendor::FACEBOOK:
$url = FacebookLoginHelper::handlePreLogin();
header("Location:" . $url);
break;
case Vendor::GOOGLE:
$url = GoogleLoginHelper::handlePreLogin();
header("Location:" . $url);
break;
default:
exit();
}
}
public function facebookLoginResponse()
{
try {
$userInformation = FacebookLoginHelper::getUserInformationFromCallback();
return $userInformation;
} catch (FacebookSDKException $e) {
var_dump($e);
}
}
public function GoogleLoginResponse()
{
try {
$userInformation = GoogleLoginHelper::getUserInformationFromCallback();
return $userInformation;
} catch (Exception $e) {
var_dump($e);
}
}
}
|
Java
|
UTF-8
| 1,447
| 2.859375
| 3
|
[] |
no_license
|
public class Seats_Page {
private int num;
private String type;
private String window;
private boolean table;
private String direction;
private boolean access;
private String email = "";
public Seats_Page(int num, String type, String window, String direction,
boolean table, boolean access) {
this.num = num;
this.type = type;
this.window = window;
this.table = table;
this.direction = direction;
this.access = access;
this.email = "";
}
public int getNum() {
return num;
}
public boolean match(String classtype, String window, String direction,
boolean table, boolean access) {
return this.type.equals(classtype) && this.window.equals(window)
&& this.direction.equals(direction) && this.table == table
&& this.access == access;
}
public void print() {
System.out.print("Number: " + num);
System.out.print(" Class: " + type);
System.out.print(" Window: " + window);
System.out.print(" Table: " + table);
System.out.print(" Direction: " + direction);
System.out.print(" Access: " + access);
System.out.print(" Email: " + email);
System.out.println();
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return this.email;
}
public void cancel() {
email = "";
}
public boolean isReserved() {
if (email.length() == 0)
return false;
else
return true;
}
}
|
JavaScript
|
UTF-8
| 634
| 3.46875
| 3
|
[
"MIT"
] |
permissive
|
function printValues(arr) {
let searchedKey = arr.pop();
let isSearchedKeyFound = false;
for (let element of arr) {
let elementTokens = element.split(' ');
let key = elementTokens[0];
if (key === searchedKey) {
let value = elementTokens[1];
console.log(value);
isSearchedKeyFound = true;
}
}
if (!isSearchedKeyFound) {
console.log('None');
}
}
//printValues(['key value', 'key eulav', 'test tset', 'key']);
//printValues(['3 test', '3 test1', '4 test2', '4 test3', '4 test5', '4']);
//printValues(['3 bla', '3 alb', '2']);
|
C++
|
GB18030
| 10,875
| 2.609375
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<malloc.h>
#include"start.h"
#include"process.h"
void doyouwork()
{
if(now->next_node == NULL) //ǰڷ
{
if(PHead->next_node != NULL) //вΪt
{
pn = (SERVELISTNODE*)malloc(sizeof(ServeListNode));
pn->user_call = PHead->next_node->user_call; //ָӴӦָȡ뵽ݵķָ
pn->serve_state = 'P';
pn->next_node = NULL;
ServeListAdd(rn, pn);
ResponseCut(&Head->head, &Head->tail); //ӴӦָȥ
pn2 = &now->next_node;
if((*pn2)->user_call->user_floor == d.current_floor) //û¥ = ¥
{
(*pn2)->serve_state = 'E'; // Ϊ
}
else // !=
{
(*pn2)->serve_state = 'P'; // Ϊ ǰ
}
Process1_ride(); // 1
}
else
return ;
}
else if(now->next_node != NULL) //ڷ
{
Process1_ride(); // 1
}
Process2_judge(); // 2
}
void Process1_ride()
{
if(d.run_state == 'U') //
{
RESPONSELISTNODE *Pl3 = PHead->next_node; //
for( ; Pl3 != NULL; )
{
if(Pl3->user_call->user_floor > d.current_floor && Pl3->user_call->user_target > Pl3->user_call->user_floor)
{
pn = (SERVELISTNODE*)malloc(sizeof(ServeListNode));
pn->user_call = Pl3->user_call;
pn->serve_state = 'P';
pn->next_node = NULL;
ServeListAdd(rn, pn);
ResponseCut2(&Pl3);
}
if(Pl3 != NULL)
{
Pl3 = Pl3->next_node;
}
else if(Pl3 == NULL)
{
break;
}
}
return ;
}
else if(d.run_state == 'D') //
{
RESPONSELISTNODE *Pl3 = PHead->next_node; //
for( ; Pl3 != NULL; )
{
if(Pl3->user_call->user_floor < d.current_floor && Pl3->user_call->user_target < Pl3->user_call->user_floor)
{
pn = (SERVELISTNODE*)malloc(sizeof(ServeListNode));
pn->user_call = Pl3->user_call;
pn->serve_state = 'P';
pn->next_node = NULL;
ServeListAdd(rn, pn);
ResponseCut2(&Pl3);
}
if(Pl3 != NULL)
{
Pl3 = Pl3->next_node;
}
else if(Pl3 == NULL)
{
break;
}
}
return ;
}
else if(d.run_state == 'S') //ͣ
{
if(((*pn2)->serve_state == 'P' && (*pn2)->user_call->user_floor > d.current_floor) || ((*pn2)->serve_state == 'E' && (*pn2)->user_call->user_target > d.current_floor))
{
RESPONSELISTNODE *Pl3 = PHead->next_node; //
for( ; Pl3 != NULL; )
{
if(Pl3->user_call->user_floor >= d.current_floor && Pl3->user_call->user_target > Pl3->user_call->user_floor)
{
pn = (SERVELISTNODE*)malloc(sizeof(ServeListNode));
pn->user_call = Pl3->user_call;
pn->next_node = NULL;
if(Pl3->user_call->user_floor == d.current_floor)
pn->serve_state = 'E';
else if(Pl3->user_call->user_floor != d.current_floor)
pn->serve_state = 'P';
ServeListAdd(rn, pn);
ResponseCut2(&Pl3);
}
if(Pl3 != NULL)
{
Pl3 = Pl3->next_node;
}
else if(Pl3 == NULL)
{
break;
}
}
}
else if(((*pn2)->serve_state == 'P' && (*pn2)->user_call->user_floor < d.current_floor) || ((*pn2)->serve_state == 'E' && (*pn2)->user_call->user_target < d.current_floor))
{
RESPONSELISTNODE *Pl3 = PHead->next_node; //
for( ; Pl3 != NULL; )
{
if(Pl3->user_call->user_floor <= d.current_floor && Pl3->user_call->user_target < Pl3->user_call->user_floor)
{
pn = (SERVELISTNODE*)malloc(sizeof(ServeListNode));
pn->user_call = Pl3->user_call;
pn->next_node = NULL;
if(Pl3->user_call->user_floor == d.current_floor)
pn->serve_state = 'E';
else if(Pl3->user_call->user_floor != d.current_floor)
pn->serve_state = 'P';
ServeListAdd(rn, pn);
ResponseCut2(&Pl3);
}
if(Pl3 != NULL)
{
Pl3 = Pl3->next_node;
}
else if(Pl3 == NULL)
{
break;
}
}
}
return ;
}
}
void Process2_judge()
{
if(d.run_state == 'U')
{
SERVELISTNODE *Pn3 = now->next_node; //
for( ; Pn3 != NULL; )
{
if(Pn3->serve_state == 'P') //ǰ
{
if(Pn3->user_call->user_floor == d.current_floor + 1) //û¥ ڣm+1)
{
d.run_state = 'S';
ChangeToE(&Pn3); // Ϊ
}
if(Pn3 != NULL)
{
Pn3 = Pn3->next_node;
}
else if(Pn3 == NULL)
{
break;
}
}
else if(Pn3->serve_state == 'E') //
{
if(Pn3->user_call->user_target == d.current_floor + 1) //ûĿ¥ ڣm+1)
{
d.run_state = 'S';
ServeListCut(&Pn3);
}
else
{
if(Pn3 != NULL)
{
Pn3 = Pn3->next_node;
}
else if(Pn3 == NULL)
{
break;
}
}
}
}
d.current_floor++; //¥ +1
s.Road++;
}
else if(d.run_state == 'D')
{
SERVELISTNODE *Pn3 = now->next_node; //
for( ; Pn3 != NULL; )
{
if(Pn3->serve_state == 'P') //ǰ
{
if(Pn3->user_call->user_floor == d.current_floor - 1) //û¥ ڣm-1)
{
d.run_state = 'S';
ChangeToE(&Pn3); // Ϊ
}
if(Pn3 != NULL)
{
Pn3 = Pn3->next_node;
}
else if(Pn3 == NULL)
{
break;
}
}
else if(Pn3->serve_state == 'E') //
{
if(Pn3->user_call->user_target == d.current_floor - 1) //û¥ ڣm-1)
{
d.run_state = 'S';
ServeListCut(&Pn3);
}
else
{
if(Pn3 != NULL)
{
Pn3 = Pn3->next_node;
}
else if(Pn3 == NULL)
{
break;
}
}
}
}
d.current_floor--; //¥ -1
s.Road++;
}
else if(d.run_state == 'S')
{
if((*pn2)->serve_state == 'P') //ǰ
{
if((*pn2)->user_call->user_floor > d.current_floor) //û¥ > m
{
d.run_state = 'U';
}
else
{
d.run_state = 'D';
}
}
else if((*pn2)->serve_state == 'E') //
{
if((*pn2)->user_call->user_target > d.current_floor) //ûĿ¥ > m
{
d.run_state = 'U';
}
else
{
d.run_state = 'D';
}
}
}
}
void ServeListAdd(SERVELISTNODE **p, SERVELISTNODE *pn) //ӵǰָ
{
SERVELISTNODE *pp = *p;
while(pp->next_node != NULL)
{
pp = pp->next_node;
}
SERVELISTNODE **ppp = &pp;
(*ppp)->next_node = pn;
}
void ResponseAdd(RESPONSELISTNODE **ph, RESPONSELISTNODE *pl) //ӵӦָ
{
RESPONSELISTNODE *pp = *ph;
while(pp->next_node != NULL)
{
pp = pp->next_node;
}
RESPONSELISTNODE **ppp = &pp;
(*ppp)->next_node = pl;
Head->tail = pl;
Head->list_num++;
s.All++;
if(pl->user_call->call_type == 'U')
s.Up++;
else if(pl->user_call->call_type == 'D')
s.Down++;
}
void ResponseCut(RESPONSELISTNODE **ph, RESPONSELISTNODE **pt)
{
if((*ph)->next_node->next_node != NULL)
{
RESPONSELISTNODE *temp_next = (*ph)->next_node->next_node; //ȡһ
(*ph)->next_node->user_call = temp_next->user_call;
(*ph)->next_node->next_node = temp_next->next_node;
}
else if((*ph)->next_node->next_node == NULL)
{
(*pt) = NULL;
(*ph)->next_node = *pt;
}
Head->list_num--;
}
void ResponseCut2(RESPONSELISTNODE **p)
{
if((*p)->next_node != NULL)
{
RESPONSELISTNODE *temp_next = (*p)->next_node; //ȡ
(*p)->user_call = temp_next->user_call;
(*p)->next_node = temp_next->next_node;
}
else if((*p)->next_node == NULL)
{
RESPONSELISTNODE *pp = PHead;
while(pp->next_node->next_node != NULL)
{
pp = pp->next_node;
}
RESPONSELISTNODE **ppp = &pp;
(*ppp)->next_node = NULL;
Head->tail = pp;
}
Head->list_num--;
}
void ServeListCut(SERVELISTNODE **p)
{
if((*p)->next_node != NULL)
{
SERVELISTNODE *temp_next = (*p)->next_node; //ɾǰڵ
(*p)->serve_state = temp_next->serve_state;
(*p)->user_call = temp_next->user_call;
(*p)->next_node = temp_next->next_node;
}
else if((*p)->next_node == NULL)
{
SERVELISTNODE *pp = now;
while(pp->next_node->next_node != NULL)
{
pp = pp->next_node;
}
SERVELISTNODE **ppp = &pp;
(*ppp)->next_node = NULL;
*p = (*p)->next_node;
}
}
void ChangeToE(SERVELISTNODE **p)
{
(*p)->serve_state = 'E'; // Ϊ
}
|
Markdown
|
UTF-8
| 6
| 3.734375
| 4
|
[] |
no_license
|
UGBKQ872CN-eyJsaWNlbnNlSWQiOiJVR0JLUTg3MkNOIiwibGljZW5zZWVOYW1lIjoi5rC45LmF5r+A5rS7IHd3d8K3YWppaHVvwrdjb20iLCJhc3NpZ25lZU5hbWUiOiIiLCJhc3NpZ25lZUVtYWlsIjoiIiwibGljZW5zZVJlc3RyaWN0aW9uIjoiIiwiY2hlY2tDb25jdXJyZW50VXNlIjpmYWxzZSwicHJvZHVjdHMiOlt7ImNvZGUiOiJEUE4iLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6ZmFsc2V9LHsiY29kZSI6IkRCIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOmZhbHNlfSx7ImNvZGUiOiJQUyIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjpmYWxzZX0seyJjb2RlIjoiSUkiLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6ZmFsc2V9LHsiY29kZSI6IlJTQyIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjp0cnVlfSx7ImNvZGUiOiJHTyIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjpmYWxzZX0seyJjb2RlIjoiRE0iLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6ZmFsc2V9LHsiY29kZSI6IlJTRiIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjp0cnVlfSx7ImNvZGUiOiJEUyIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjpmYWxzZX0seyJjb2RlIjoiUEMiLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6ZmFsc2V9LHsiY29kZSI6IlJDIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOmZhbHNlfSx7ImNvZGUiOiJDTCIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjpmYWxzZX0seyJjb2RlIjoiV1MiLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6ZmFsc2V9LHsiY29kZSI6IlJEIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOmZhbHNlfSx7ImNvZGUiOiJSUzAiLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6ZmFsc2V9LHsiY29kZSI6IlJNIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOmZhbHNlfSx7ImNvZGUiOiJBQyIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjpmYWxzZX0seyJjb2RlIjoiUlNWIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOnRydWV9LHsiY29kZSI6IkRDIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOmZhbHNlfSx7ImNvZGUiOiJSU1UiLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6ZmFsc2V9LHsiY29kZSI6IkRQIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOnRydWV9LHsiY29kZSI6IlBEQiIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjp0cnVlfSx7ImNvZGUiOiJQV1MiLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6dHJ1ZX0seyJjb2RlIjoiUFNJIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOnRydWV9LHsiY29kZSI6IlBQUyIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjp0cnVlfSx7ImNvZGUiOiJQQ1dNUCIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjp0cnVlfSx7ImNvZGUiOiJQR08iLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6dHJ1ZX0seyJjb2RlIjoiUFBDIiwicGFpZFVwVG8iOiIyMDIyLTA1LTIzIiwiZXh0ZW5kZWQiOnRydWV9LHsiY29kZSI6IlBSQiIsInBhaWRVcFRvIjoiMjAyMi0wNS0yMyIsImV4dGVuZGVkIjp0cnVlfSx7ImNvZGUiOiJQU1ciLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6dHJ1ZX0seyJjb2RlIjoiUlMiLCJwYWlkVXBUbyI6IjIwMjItMDUtMjMiLCJleHRlbmRlZCI6dHJ1ZX1dLCJtZXRhZGF0YSI6IjAxMjAyMjA0MjRQUEFNMDAwMDA1IiwiaGFzaCI6IjMzNDIyNDg4LzA6LTE0NzMxNzM5ODIiLCJncmFjZVBlcmlvZERheXMiOjcsImF1dG9Qcm9sb25nYXRlZCI6ZmFsc2UsImlzQXV0b1Byb2xvbmdhdGVkIjpmYWxzZX0=-WFvUJCsu9PiJTj6lG9YPrZ+IDpCPgJKw11u+u9BTUBb9tsFwN+av/i3vHpnNJBgZzp7jonzXsvNR3B5OcIj8J0+9VxJLctguBKY9u+1/kdXhI8xRxFqP9sJ8Hq46Y7MDSsyUhOU1siwH8kcHDkFvr6IH1+MyvOhtXE7ocTkkp8Cj8PyXLiJyYxs0YKUD1L5BqGn7U0tDwzH9YYQq7+T1N7NJ9spNyVA1zTyivTcj5RrrbrAjC1Q7tt+cC73h4C4xC7kp6JVlwjfsNm4anbMepCvlT7SKA7uODH4KJ3M+oVen9P3j6acQkiuCxGLPYscCq4DfmmNPGW1PrW9uke86Dg==-MIIETDCCAjSgAwIBAgIBDTANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1KZXRQcm9maWxlIENBMB4XDTIwMTAxOTA5MDU1M1oXDTIyMTAyMTA5MDU1M1owHzEdMBsGA1UEAwwUcHJvZDJ5LWZyb20tMjAyMDEwMTkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDCP4uk4SlVdA5nuA3DQC+NsEnZS9npFnO0zrmMWcz1++q2UWJNuGTh0rwi+3fUJIArfvVh7gNtIp93rxjtrQAuf4/Fa6sySp4c32MeFACfC0q+oUoWebhOIaYTYUxm4LAZ355vzt8YeDPmvWKxA81udqEk4gU9NNAOz1Um5/8LyR8SGsSc4EDBRSjcMWMwMkYSauGqGcEUK8WhfplsyF61lKSOFA6VmfUmeDK15rUWWLbOMKgn2cxFA98A+s74T9Oo96CU7rp/umDXvhnyhAXSukw/qCGOVhwKR8B6aeDtoBWQgjnvMtPgOUPRTPkPGbwPwwDkvAHYiuKJ7Bd2wH7rAgMBAAGjgZkwgZYwCQYDVR0TBAIwADAdBgNVHQ4EFgQUJNoRIpb1hUHAk0foMSNM9MCEAv8wSAYDVR0jBEEwP4AUo562SGdCEjZBvW3gubSgUouX8bOhHKQaMBgxFjAUBgNVBAMMDUpldFByb2ZpbGUgQ0GCCQDSbLGDsoN54TATBgNVHSUEDDAKBggrBgEFBQcDATALBgNVHQ8EBAMCBaAwDQYJKoZIhvcNAQELBQADggIBAB2J1ysRudbkqmkUFK8xqhiZaYPd30TlmCmSAaGJ0eBpvkVeqA2jGYhAQRqFiAlFC63JKvWvRZO1iRuWCEfUMkdqQ9VQPXziE/BlsOIgrL6RlJfuFcEZ8TK3syIfIGQZNCxYhLLUuet2HE6LJYPQ5c0jH4kDooRpcVZ4rBxNwddpctUO2te9UU5/FjhioZQsPvd92qOTsV+8Cyl2fvNhNKD1Uu9ff5AkVIQn4JU23ozdB/R5oUlebwaTE6WZNBs+TA/qPj+5/wi9NH71WRB0hqUoLI2AKKyiPw++FtN4Su1vsdDlrAzDj9ILjpjJKA1ImuVcG329/WTYIKysZ1CWK3zATg9BeCUPAV1pQy8ToXOq+RSYen6winZ2OO93eyHv2Iw5kbn1dqfBw1BuTE29V2FJKicJSu8iEOpfoafwJISXmz1wnnWL3V/0NxTulfWsXugOoLfv0ZIBP1xH9kmf22jjQ2JiHhQZP7ZDsreRrOeIQ/c4yR8IQvMLfC0WKQqrHu5ZzXTH4NO3CwGWSlTY74kE91zXB5mwWAx1jig+UXYc2w4RkVhy0//lOmVya/PEepuuTTI4+UJwC7qbVlh5zfhj8oTNUXgN0AOc+Q0/WFPl1aw5VV/VrO8FCoB15lFVlpKaQ1Yh+DVU8ke+rt9Th0BCHXe0uZOEmH0nOnH/0onD
|
Java
|
UTF-8
| 392
| 1.820313
| 2
|
[] |
no_license
|
package com.gaments.gaments.service;
import com.gaments.gaments.models.UserProfile;
public interface UserProfileService {
public UserProfile createUserProfile(String username, UserProfile newUserProfile);
public UserProfile getLoggedUserProfile(String username);
public UserProfile getUserProfile();
public UserProfile updateUserProfile(UserProfile updatedUserProfile);
}
|
Java
|
UTF-8
| 6,415
| 1.695313
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teiid.adminapi.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.teiid.adminapi.PropertyDefinition;
public class PropertyDefinitionMetadata extends AdminObjectImpl implements PropertyDefinition {
private static final long serialVersionUID = 6612838530524627205L;
private Collection allowedValues = new ArrayList();
private Object defaultValue = null;
private String description = null;
private String displayName = null;
private String propertyTypeClassName = String.class.getName();
private RestartType requiresRestart = RestartType.NONE;
private boolean advanced = false;
private boolean masked = false;
private boolean modifiable = true;
private boolean required = false;
private String category;
/**
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer result = new StringBuffer();
result.append("Display Name:").append(getDisplayName()); //$NON-NLS-1$
result.append(" Name:").append(getName()); //$NON-NLS-1$
result.append(" Description:").append(getDescription()); //$NON-NLS-1$
result.append(" Property Type Classname:").append(getPropertyTypeClassName()); //$NON-NLS-1$
result.append(" Default Value:").append(getDefaultValue()); //$NON-NLS-1$
result.append(" Constrained To Allow Values:").append(isConstrainedToAllowedValues()); //$NON-NLS-1$
result.append(" Allowed Values:").append(getAllowedValues()); //$NON-NLS-1$
result.append(" Required:").append(isRequired()); //$NON-NLS-1$
result.append(" Expert:").append(isAdvanced()); //$NON-NLS-1$
result.append(" Masked:").append(isMasked()); //$NON-NLS-1$
result.append(" Category:").append(getCategory()); //$NON-NLS-1$
result.append(" Modifiable:").append(isModifiable()); //$NON-NLS-1$
result.append(" RequiresRestart:").append(getRequiresRestart()); //$NON-NLS-1$
return result.toString();
}
/**
* @see org.teiid.adminapi.PropertyDefinition#getAllowedValues()
*/
public Collection getAllowedValues() {
return allowedValues;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#getDefaultValue()
*/
public Object getDefaultValue() {
return defaultValue;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#getDescription()
*/
public String getDescription() {
return description;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#getDisplayName()
*/
public String getDisplayName() {
return displayName;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#getPropertyTypeClassName()
*/
public String getPropertyTypeClassName() {
return propertyTypeClassName;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#getRequiresRestart()
*/
public RestartType getRequiresRestart() {
return requiresRestart;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#isAdvanced()
* @since 4.3
*/
public boolean isAdvanced() {
return advanced;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#isMasked()
*/
public boolean isMasked() {
return masked;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#isModifiable()
*/
public boolean isModifiable() {
return modifiable;
}
/**
* @see org.teiid.adminapi.PropertyDefinition#isRequired()
*/
public boolean isRequired() {
return required;
}
/**
* @param allowedValues The allowedValues to set.
*/
public void setAllowedValues(Collection allowedValues) {
this.allowedValues = allowedValues;
}
/**
* @param defaultValue The defaultValue to set.
*/
public void setDefaultValue(Serializable defaultValue) {
this.defaultValue = defaultValue;
}
/**
* @param description The description to set.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @param displayName The displayName to set.
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* @param expert The value of expert to set.
*/
public void setAdvanced(boolean expert) {
this.advanced = expert;
}
/**
* @param masked The value of masked to set.
*/
public void setMasked(boolean masked) {
this.masked = masked;
}
/**
* @param modifiable The value of modifiable to set.
*/
public void setModifiable(boolean modifiable) {
this.modifiable = modifiable;
}
/**
* @param propertyTypeClassName The propertyTypeName to set.
*/
public void setPropertyTypeClassName(String propertyTypeClassName) {
this.propertyTypeClassName = propertyTypeClassName;
}
/**
* @param required The value of required to set.
*/
public void setRequired(boolean required) {
this.required = required;
}
/**
* @param requiresRestart The value of requiresRestart to set.
*/
public void setRequiresRestart(RestartType requiresRestart) {
this.requiresRestart = requiresRestart;
}
@Override
public boolean isConstrainedToAllowedValues() {
return allowedValues != null && !allowedValues.isEmpty();
}
@Override
public String getCategory() {
return this.category;
}
public void setCategory(String category) {
this.category = category;
}
}
|
SQL
|
UTF-8
| 5,505
| 3.25
| 3
|
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Creato il: Ago 11, 2021 alle 16:48
-- Versione del server: 10.4.11-MariaDB
-- Versione PHP: 7.4.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `db_raccolta_differenziata`
--
-- --------------------------------------------------------
--
-- Struttura della tabella `failed_jobs`
--
CREATE TABLE `failed_jobs` (
`id` bigint(20) UNSIGNED NOT NULL,
`uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`connection` text COLLATE utf8mb4_unicode_ci NOT NULL,
`queue` text COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`failed_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Struttura della tabella `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dump dei dati per la tabella `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2019_08_19_000000_create_failed_jobs_table', 1),
(4, '2021_07_23_132456_create_schedule', 1);
-- --------------------------------------------------------
--
-- Struttura della tabella `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Struttura della tabella `schedules`
--
CREATE TABLE `schedules` (
`id` bigint(20) UNSIGNED NOT NULL,
`type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`date_start` date NOT NULL,
`time_start` time NOT NULL,
`date_end` date NOT NULL,
`time_end` time NOT NULL,
`completed` tinyint(1) NOT NULL DEFAULT 0,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dump dei dati per la tabella `schedules`
--
INSERT INTO `schedules` (`id`, `type`, `date_start`, `time_start`, `date_end`, `time_end`, `completed`, `created_at`, `updated_at`) VALUES
(1, 'Carta', '2021-08-14', '10:30:00', '2021-08-16', '10:30:00', 1, '2021-08-10 12:34:38', '2021-08-10 14:25:13'),
(2, 'Vetro', '2021-08-13', '20:30:00', '2021-08-14', '21:30:00', 0, '2021-08-10 12:35:19', '2021-08-10 12:35:19'),
(3, 'Indifferenziata', '2021-08-31', '19:00:00', '2021-09-02', '19:00:00', 0, '2021-08-10 12:58:21', '2021-08-10 12:58:21'),
(4, 'Carta', '2021-10-19', '12:30:00', '2021-10-21', '12:30:00', 0, '2021-08-10 14:06:28', '2021-08-10 14:25:38');
-- --------------------------------------------------------
--
-- Struttura della tabella `users`
--
CREATE TABLE `users` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indici per le tabelle scaricate
--
--
-- Indici per le tabelle `failed_jobs`
--
ALTER TABLE `failed_jobs`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`);
--
-- Indici per le tabelle `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indici per le tabelle `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Indici per le tabelle `schedules`
--
ALTER TABLE `schedules`
ADD PRIMARY KEY (`id`);
--
-- Indici per le tabelle `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT per le tabelle scaricate
--
--
-- AUTO_INCREMENT per la tabella `failed_jobs`
--
ALTER TABLE `failed_jobs`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT per la tabella `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT per la tabella `schedules`
--
ALTER TABLE `schedules`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT per la tabella `users`
--
ALTER TABLE `users`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java
|
UTF-8
| 5,413
| 2.1875
| 2
|
[] |
no_license
|
package com.out.link.server.http.controller;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.out.link.server.http.log.LoggerFactory;
import com.out.link.server.http.service.BingTranslateService;
import com.out.link.server.http.service.BingTranslateTokenService;
import com.out.link.server.http.service.UserService;
import com.out.link.server.http.service.model.TranslateRequest;
import com.out.link.server.http.service.model.TranslateToken;
@Controller
public class BingTranslateController {
public Logger loggerError = LoggerFactory.getServerErrorLogger(BingTranslateController.class);
@Resource
private BingTranslateService bingTranslateService;
@Resource
private BingTranslateTokenService bingTranslateTokenService;
@Resource
private UserService userService;
Gson gson = new Gson();
@RequestMapping(value = "action/translate/translateText", method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String translateText(
@RequestBody String body
) {
String targetText = null;
try {
TranslateRequest request = gson.fromJson(body, TranslateRequest.class);
if(request != null
&& StringUtils.isNotBlank(request.getText())
&& StringUtils.isNotBlank(request.getTo())
&& StringUtils.isNotBlank(request.getUid())) {
int subPoint = countText(request.getText());
long rePoint = userService.subUserMaxPoint(request.getUid(), subPoint);
if(rePoint == 0) {
targetText = bingTranslateService.translateText(request.getText(), request.getTo());
} else {
return "{ \"ret\" : 1, \"err\" : \"The rest of the points is not enough!\"}";
}
} else {
return "{ \"ret\" : 1, \"err\" : \"uid or text or to is null!\"}";
}
} catch (Exception e) {
loggerError.error("translate text exception", e);
return "{ \"ret\" : 1, \"err\" : \"" + e.getMessage() + "\"}";
}
return "{ \"ret\" : 0,\"target_text\":\""+targetText+"\"}";
}
@RequestMapping(value = "action/translate/getTranslateNames", method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String getTranslateNames(
) {
try {
Map<String,String> map = bingTranslateService.getLangTranslateAndName();
return gson.toJson(map, new TypeToken<Map<String,String>>(){}.getType());
} catch (Exception e) {
loggerError.error("getTranslateNames exception", e);
return "{ \"ret\" : 1, \"err\" : \"" + e.getMessage() + "\"}";
}
}
@RequestMapping(value = "action/translate/getTranslateNamesByLocale", method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String getTranslateNamesByLocale(
@RequestParam(value="locale",required = true) String locale
) {
try {
Map<String,String> map = bingTranslateService.getLangTranslateAndNameByLocale(locale);
return gson.toJson(map, new TypeToken<Map<String,String>>(){}.getType());
} catch (Exception e) {
loggerError.error("getTranslateNamesByLocale exception", e);
return "{ \"ret\" : 1, \"err\" : \"" + e.getMessage() + "\"}";
}
}
@RequestMapping(value = "action/translate/checkSpeak", method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String checkSpeakLang(
@RequestParam(value="lang",required = true) String lang
) {
try {
boolean exits = bingTranslateService.checkSpeakLang(lang);
return "{ \"ret\" : 0,\"exits\":\""+String.valueOf(exits)+"\"}";
} catch (Exception e) {
loggerError.error("checkSpeakLang exception", e);
return "{ \"ret\" : 1, \"err\" : \"" + e.getMessage() + "\"}";
}
}
//https://msdn.microsoft.com/en-us/library/ff512420.aspx 获取语音
@RequestMapping(value = "action/translate/getAccessToken", method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String getAccessToken() {
try {
TranslateToken token = bingTranslateTokenService.getAccessToken();
return "{ \"ret\" : 0,\"token\":\""+gson.toJson(token)+"\"}";
} catch (Exception e) {
loggerError.error("getAccessToken exception", e);
return "{ \"ret\" : 1, \"err\" : \"" + e.getMessage() + "\"}";
}
}
@ExceptionHandler(Exception.class)
@ResponseBody
public String handleIOException(Exception ex) {
return "{ \"ret\" : 1, \"err\" : \"" + ex.getMessage() + "\"}" ;
}
@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseBody
public String handleMissParaException(Exception ex) {
return "{ \"ret\" : 1, \"err\" : \"" + ex.getMessage() + "\"}" ;
}
//计算字符的个数,去掉空格数
private int countText(String text) {
int count = 0;
for(char s : text.toCharArray()) {
if(s != ' ')
count = count + 1;
}
return count;
}
}
|
JavaScript
|
UTF-8
| 845
| 4.125
| 4
|
[] |
no_license
|
class hashMap {
constructor(cap) {
this.capacity = cap;
this.table = [];
}
add(key, val) {
// Add, but handle collisions
// Create an add(key, val) method on hashMap to add a new key and value to the map. This entails hashing key, mod’ing it into the size of your array, and placing the value there.
}
}
// Use the below to hash a string:
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash &= hash; //Convert to 32b int
}
return hash;
}
let myString = "today";
let myHashCode = myString.hashCode();
console.log('myHashCode', myHashCode);
const myHash = new hashMap(10);
myHash.add("today", "Monday");
|
Python
|
UTF-8
| 1,856
| 2.671875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
# Doc: https://pythonhosted.org/PyPDF2/PdfFileWriter.html
# https://stackoverflow.com/questions/2252726/how-to-create-pdf-files-in-python
# https://pypi.org/project/pdfkit/ html -> pdf
# reportLab
import PyPDF2
#import pdfkit
from reportlab.pdfgen import canvas
import os
class Pdfhandler(object):
def __init__(self,
filename):
self.filename = filename
self.absoluteFilePath = self.__absoluteFilePath()
def __absoluteFilePath(self):
script_dir = os.path.dirname(__file__) # absolute dir the script is in
# ".." moves one folder back
# absoluteFilePath = os.path.join(script_dir, "..", "textfiles", "textfiles", self.filename)
absoluteFilePath = os.path.join(script_dir, "..", "tmpfiles", "textfiles", self.filename)
return absoluteFilePath
def deleteFile(self):
os.remove(self.absoluteFilePath)
def pdfToText(self):
text = ''
pdf = open(self.absoluteFilePath, 'rb')
fileReader = PyPDF2.PdfFileReader(pdf)
for page in fileReader.pages:
text = text + page.extractText().replace('\n', '')
pdf.close()
return text
@staticmethod
def createPdfReport():
script_dir = os.path.dirname(__file__)
absoluteFilePath = os.path.join(script_dir, "..", "tmpfiles", "reports", "Report.pdf")
c = canvas.Canvas(absoluteFilePath)
# c = canvas.Canvas("/tmpfiles/reports/Report.pdf")
c.drawString(100,100,"PDFanalyzer Report")
c.showPage()
c.save()
"""
def htmlReportToPdf(self):
pdfkit.from_url('http://google.com', 'out.pdf')
from django.test import Client
c = Client()
response = c.get('/mymodel/1')
content = response.content
"""
|
Java
|
UTF-8
| 1,625
| 2.40625
| 2
|
[] |
no_license
|
package simplytextile.policytracker.companyresponse;
public class PolicyType
{
private Integer id;
private String name;
private String description;
private String parent_id;
private Integer is_renewable;
private Integer renewal_notice_days;
public PolicyType(Integer id, String name, String description, String parent_id, Integer is_renewable, Integer renewal_notice_days) {
this.id = id;
this.name = name;
this.description = description;
this.parent_id = parent_id;
this.is_renewable = is_renewable;
this.renewal_notice_days = renewal_notice_days;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 String getParent_id() {
return parent_id;
}
public void setParent_id(String parent_id) {
this.parent_id = parent_id;
}
public Integer getIs_renewable() {
return is_renewable;
}
public void setIs_renewable(Integer is_renewable) {
this.is_renewable = is_renewable;
}
public Integer getRenewal_notice_days() {
return renewal_notice_days;
}
public void setRenewal_notice_days(Integer renewal_notice_days) {
this.renewal_notice_days = renewal_notice_days;
}
}
|
Markdown
|
UTF-8
| 1,938
| 2.5625
| 3
|
[] |
no_license
|
# -000000
#000000 Digital Dark Age - HSD FB D/IRAA Summer 2017
One can feel it behind the eyes like the fog before a migraine sets in. The buzz words humming like fluorescent lights, tumbling from the mouths of talking heads like water from the puckered lips of a stone cherub. Disruptive innovation, exit strategies, the New Normal, Post-fact politics, Fake News, Alternative Facts.
In the wake of the referendum on Brexit and the election of US President Donald J. Trump set against the backdrop of a European Union visibly in the grips of a sweeping wave of Nationalism, truth seems to be in thumbs of the Tweeter. In light of an apparent and culturally pervasive lack of regard for facts, my research will focus on reworking the notion of the Digital Dark Ages, a hypothetical future condition where history and knowledge become lost in an amnesia of techno-obsolescence.
## Contents:
This is a growing collection of course work and collaborative research expanding the notion of the Digital Dark Age not as some hypothetical future state, but rather as our present historical moment.
* [Lecture Resources](https://github.com/phillipdavidstearns/-000000/tree/master/lectureResources) - contains materials, images, keynotes presentations, and other material presented during the seminar.
* [Reading Material](https://github.com/phillipdavidstearns/-000000/tree/master/readingMaterial) - a collection of PDF and other research materials, both a mixture of required and additional reading on topics introduced in class.
* [Student Projects](https://github.com/phillipdavidstearns/-000000/tree/master/StudentProjects) - a raw collection of research materials gathered by students.
## Wiki:
A course wiki page will serve as the primary interface between the class and the public. Additional class materials can found there along with documentation of student projects.
* [Course Wiki](https://github.com/phillipdavidstearns/-000000/wiki)
|
JavaScript
|
UTF-8
| 16,342
| 2.515625
| 3
|
[] |
no_license
|
// Settings for JS
$(document).ready(function(){
var xurl = 'index.php?id=19';
$('label.insured').click(function(){
if($(this).hasClass('active')){
$(this).removeClass('btn-success').addClass('btn-warning');
$('span.insured-lable').text("Insured?");
$('input#insured').attr('checked', false);
} else {
$(this).removeClass('btn-warning').addClass('btn-success');
$('span.insured-lable').text("We are insured!");
$('input#insured').attr('checked', true);
}
});
$('.btn-group label.btn').bind('click', function(){
var childinput = $(this).children('input');
if($(this).hasClass('active')){
lablecheckbox(this,false,childinput);
if($(this).hasClass('category')){
$(this).remove();
}
} else {
lablecheckbox(this,true,childinput);
}
});
function lablecheckbox(lable,state,b){
if(state !== true){
console.log('ne active');
$(lable).removeClass('btn-success').addClass('btn-default');
b.attr('checked', false);
} else {
console.log('active');
$(lable).removeClass('btn-default').addClass('btn-success');
b.attr('checked', true);
}
}
function responseHandler(data){
var trHTML = '';
$.each(data, function (i, item) {
trHTML +=
'<tr class="item'+ item.id +'"><td>' + item.checkbox +
'</td><td>' + item.title +
'</td><td>' + item.address +
'</td><td>' + item.type +
'</td><td>' + item.status +
'</td><td>' + item.estVal +
'</td><td>' + DropDownMenu(item.links) +
'</td></tr>';
});
return trHTML;
}
function TableUpdate(){
//console.log('Prisutsvuet tablita');
var data = $('.ajax-table').data();
var target = $('.ajax-table').data('target');
//console.log('Prisutsvuet tablitas vivodom v ' + target);
$.ajax({
type:"POST",
url: xurl,
data: data,
dataType: 'json',
success:function(data){
// Success message
if(typeof data['status'] != 'undefined'){
$('#success').html("<div class='alert alert-success alert-dismissible fade in'>");
$('#success > .alert-success').append(data.status);
$('#success > .alert-success').append('</div>');
} else if(typeof data['error'] != 'undefined'){
$('#error').html("<div class='alert alert-danger alert-dismissible fade in'>");
$('#error > .alert-danger').append('<h3>Error</h3>: ');
$('#error > .alert-danger').append(data.error);
$('#error > .alert-danger').append('</div>');
}
$('.ajax-table tbody').html('');
$('.ajax-table tbody').append(responseHandler(data.data));
setTimeout(function() {
$('.alert').fadeOut('slow');
$('#success').html('');
$('#error').html('');
}, 1000);
},
error: function(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#error').html("<div class='alert alert-warning alert-dismissible fade in'>");
$('#error > .alert-warning').append('Important message: ');
$('#error > .alert-warning').append(msg);
$('#error > .alert-warning').append('</div>');
setTimeout(function() {
$('.alert').fadeOut('slow');
$('#error').html('');
}, 1000);
}
});
}
function DropDownMenu(array){
var initial = '<div class="btn-group"><button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action <span class="caret"></span></button><ul class="dropdown-menu">';
var list = '';
$.each(array, function (i, item) {
if (item.name == 'Edit'){
list += '<li class="link"><a href="'+item.url+'&obj='+item.obj+'">' + item.name + '</a></li>';
} else {
list += '<li class="link"><a href="#" class="xlink" data-action="' + item.type + '" data-' + item.action + '="' + item.obj + '" data-obj="' + item.obj + '">' + item.name + '</a></li>';
}
});
initial += list + '</ul></div>';
return initial;
}
function AjaxLink(data){
$('#success').html('');
$('#error').html('');
$.ajax({
type:"POST",
url: xurl,
data: data,
dataType: 'json',
success:function(response){
// Success message
$('#success').html("<div class='alert alert-success alert-dismissible fade in'>");
$('#success > .alert-success').append(response.status);
$('#success > .alert-success').append('</div>');
if(response.status == 'Removed'){
$('.ajax-table tr.item'+data['obj']).addClass('hidden');
console.log('tr.item'+data['obj']+' Removed from table');
} else if(response.status == 'Updated'){
TableUpdate();
}
setTimeout(function() {
$('.alert').fadeOut('slow');
}, 1000);
},
error: function(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#error').html("<div class='alert alert-warning alert-dismissible fade in'>");
$('#error > .alert-warning').append('Important message: ');
$('#error > .alert-warning').append(msg);
$('#error > .alert-warning').append('</div>');
setTimeout(function() {
$('.alert').fadeOut('slow');
$('#error').html('');
}, 1000);
}
});
}
if (localStorage['menustg'] === 'closed') {
$('.sidenav .nav').removeClass('open').addClass('closed');
$('button.navbar-button span.glyphicon').removeClass('glyphicon-chevron-left').addClass('glyphicon-chevron-right');
$('#wrapper').attr('style', 'padding-left:50px;');
$(this).addClass('closed');
}
$('#home').tab('show');
$('.table').on('click','input#checkall', function () {
var table = $(this).parent('.table');
if ($(this).is(':checked')) {
table.find('input.checkthis').each(function () {
console.log('Find checkbox');
$(this).prop("checked", true);
});
} else {
table.find('input.checkthis').each(function () {
console.log('Find checkbox');
$(this).prop("checked", false);
});
}
});
//datetime modal
$('#datetime').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
//var linkfrom = button.data('from') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
//var modal = $(this);
var datenow = new Date();
//modal.find('#callbackForm #linkfrom').val(linkfrom);
$('#time').datetimepicker({
controlType: 'select',
timeFormat: 'hh:mm tt',
stepMinute: 30,
altField: '#selected',
altFieldTimeOnly: false,
});
$('#show').click(function(){
$('#time').datetimepicker("show");
});
});
$("[data-toggle=tooltip]").tooltip();
//Формы
$('form.ajax').on('submit', function(e) {
e.preventDefault();
$('#success').html('');
$('#error').html('');
var data = $(this).serialize();
$.ajax({
type:"POST",
url: xurl,
data: data,
dataType: 'json',
success:function(data){
// Success message
if(typeof data['status'] != 'undefined'){
$('#success').html("<div class='alert alert-success alert-dismissible fade in'>");
$('#success > .alert-success').append(data.status);
$('#success > .alert-success').append('</div>');
} else if(typeof data['error'] != 'undefined'){
$('#error').html("<div class='alert alert-danger alert-dismissible fade in'>");
$('#error > .alert-danger').append('<h3>Error</h3>: ');
$('#error > .alert-danger').append(data.error);
$('#error > .alert-danger').append('</div>');
}
setTimeout(function() {
$('.alert').fadeOut('slow');
$('#success').html('');
$('#error').html('');
}, 1000);
},
error: function(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#error').html("<div class='alert alert-danger alert-dismissible fade in'>");
$('#error > .alert-danger').append('Important message: ');
$('#error > .alert-danger').append(msg);
$('#error > .alert-danger').append('</div>');
setTimeout(function() {
$('.alert').fadeOut('slow');
$('#error').html('');
}, 1000);
}});
return false;
});
/*Charts*/
$(function () {
$('.graf-container').highcharts({
chart: {
type: 'area'
},
title: {
text: 'Historic and Estimated Worldwide Population Growth by Region'
},
subtitle: {
text: 'Source: Wikipedia.org'
},
xAxis: {
categories: ['1750', '1800', '1850', '1900', '1950', '1999', '2050'],
tickmarkPlacement: 'on',
title: {
enabled: false
}
},
yAxis: {
title: {
text: 'Billions'
},
labels: {
formatter: function () {
return this.value / 1000;
}
}
},
tooltip: {
shared: true,
valueSuffix: ' millions'
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
}
},
series: [{
name: 'Asia',
data: [502, 635, 809, 947, 1402, 3634, 5268]
}, {
name: 'Africa',
data: [106, 107, 111, 133, 221, 767, 1766]
}, {
name: 'Europe',
data: [163, 203, 276, 408, 547, 729, 628]
}, {
name: 'America',
data: [18, 31, 54, 156, 339, 818, 1201]
}, {
name: 'Oceania',
data: [2, 2, 2, 6, 13, 30, 46]
}]
});
});
/*End chart*/
$(function () {
$('.work-done-graf-container').highcharts({
chart: {
type: 'areaspline'
},
title: {
text: 'Average fruit consumption during one week'
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 150,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
xAxis: {
categories: [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
],
plotBands: [{ // visualize the weekend
from: 4.5,
to: 6.5,
color: 'rgba(68, 170, 213, .2)'
}]
},
yAxis: {
title: {
text: 'Fruit units'
}
},
tooltip: {
shared: true,
valueSuffix: ' units'
},
credits: {
enabled: false
},
plotOptions: {
areaspline: {
fillOpacity: 0.5
}
},
series: [{
name: 'John',
data: [3, 4, 3, 5, 4, 10, 12]
}, {
name: 'Jane',
data: [1, 3, 4, 3, 3, 5, 4]
}]
});
});
/*Ajax*/
$('.ajax-table').on('click','.xlink', function(e) {
e.preventDefault();
console.log('Ajax link submited');
AjaxLink($(this).data());
return false;
});
$( document ).ready(function() {
if($('.ajax-table').length){
TableUpdate();
}
});
$('#modal-dialog').on('hide.bs.modal', function(e){
if($('.ajax-table').length){
TableUpdate();
}
});
});
|
PHP
|
UTF-8
| 1,049
| 3.03125
| 3
|
[] |
no_license
|
<?php
class Image extends Database {
private $file;
/*
* upload the file method and get the uploaded file URL
*/
public function uploadFile($file) {
$this->file = $file;
$extension = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
$imgURL = "upload/" . time() . ".{$extension}";
$tmpLocation = $file['tmp_name'];
move_uploaded_file($tmpLocation, '../'.$imgURL);
return $imgURL;
}
/*
* insert the uploaded file URL in DB by product id
*/
public function insertFile($id, $file) {
$imgURL = $this->uploadFile($file);
$query = "INSERT INTO images (product_id, image_url) VALUES (?, ?)";
$stmt = $this->dbConnect()->prepare($query);
$stmt->execute([$id, $imgURL]);
}
/*
* update product image
*/
public function updateFile($id, $file){
$imgURL = $this->uploadFile($file);
$query = 'UPDATE images SET image_url=? WHERE product_id=?';
$stmt = $this->dbConnect()->prepare($query);
$stmt->execute([$imgURL, $id]);
return $stmt->rowCount();
}
}
|
SQL
|
UTF-8
| 756
| 3.9375
| 4
|
[] |
no_license
|
WITH qualified_act as (
SELECT athlete_hub_seq
,CONCAT(firstname," ", lastname) as athlete
, FORMAT_TIMESTAMP("%b %Y", start_date) as event_month
, count(activity_hub_seq) act_count
FROM `strava-int.strava_information_vault.fact_activity`
where moving_time_s > 1500
GROUP BY athlete_hub_seq
,CONCAT(firstname," ", lastname)
, FORMAT_TIMESTAMP("%b %Y", start_date)
)
select athlete_hub_seq
, athlete
, event_month
, act_count
, RANK()
OVER (PARTITION BY event_month order by act_count desc) as month_rank
, CASE WHEN (RANK()
OVER (PARTITION BY event_month order by act_count desc)) = 1 THEN 2 ELSE 0 END as most_activities_points
, CASE WHEN act_count >= 20 THEN 2 ELSE 0 END as twenty_activities_points
from qualified_act
|
Ruby
|
UTF-8
| 3,477
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
require "pigpio"
require "rmagick"
class SharpMemoryDisplay
attr_reader :width, :height, :buf
CMD_BIT_WRITECMD = 0x80
CMD_BIT_VCOM = 0x40
CMD_BIT_CLEAR = 0x20
DUMMY_DATA = 0x00
BitRverseChar = 256.times.map do |v|
8.times.inject(0) { |ret, i| ret |= (v & 0x01 << i) != 0 ? 0x80 >> i : 0 }
end
def initialize(spi, com, cs, width, height)
@width = width
@height = height
@spi = spi
@com = com
@cs = cs
@buf = Array.new((@width / 8) * height, 0)
@com.mode = PI_OUTPUT
@com.pud = PI_PUD_OFF
@com.write 0
@cs.mode = PI_OUTPUT
@cs.pud = PI_PUD_OFF
@cs.write 0
@wave = generate_com @com
end
def stop
@wave.tx_stop if @wave
@wave.clear if @wave
@com.write 0
end
def display(num = 0)
com(*@buf)
end
def clear
com(CMD_BIT_CLEAR, DUMMY_DATA)
end
def com(*data)
@cs.write 1
@spi.write data.pack("c*")
@cs.write 0
end
def generate_com pin
mark = 0x01 << pin.gpio
wave = Pigpio::Wave.new(pin.pi)
wave.add_new
wave.add_generic([
wave.pulse(mark, 0x00, 3),
wave.pulse(0x00, mark, 1000000 - 10000)
])
wid = wave.create
wave.chain([255, 0, wid, 255, 3])
wave
end
def image2buf(image)
@buf = [CMD_BIT_WRITECMD]
th = 65536 / 2
@height.times do |y|
@buf.push BitRverseChar[y + 1]
(@width / 8).times do |col|
ret = 8.times.inject(0) do |c, x|
px = image.pixel_color(x + col * 8, y)
c << 1 | (px.red < th ? 0 : 1)
end
@buf.push ret
end
@buf.push DUMMY_DATA
end
@buf.push DUMMY_DATA
end
end
class LS013B4DN04 < SharpMemoryDisplay
def initialize(spi, com, cs, width = 96, height = 96)
super
end
end
class LS013B7DH05 < SharpMemoryDisplay
def initialize(spi, com, cs, width = 144, height = 168)
super
end
end
class LS027B4DH01 < SharpMemoryDisplay
def initialize(spi, com, cs, width = 400, height = 240)
super
end
end
def word_wrap(draw, str, width)
str.each_line.map do |v|
v.chomp.size.times.with_object([0]) do |i, ins|
ins.unshift(i) if draw.get_type_metrics(v[ins.first..i]).width > width
end[0..-2].each { |i| v.insert(i, "\n") }
v
end.join("")
end
include Pigpio::Constant
pi = Pigpio.new
unless pi.connect
p "error" + pi.pi.to_s
exit(-1)
end
com = pi.gpio(17)
cs = pi.gpio(22)
spi = pi.spi(0)
if spi.handle < 0
p "spi error" + spi.handle.to_s
pi.stop
exit(-2)
end
begin
d = LS013B7DH05.new(spi, com, cs)
image = Magick::Image.new(d.width, d.height) {
self.background_color = "white"
}
draw = Magick::Draw.new
draw.font = "./example/font/misaki_gothic.ttf" # Little Limit (http://littlelimit.net/)
draw.pointsize = 8
draw.fill = "black"
draw.gravity = Magick::NorthWestGravity
str = word_wrap(draw, DATA.read, d.width)
draw.annotate(image, 0, 0, 0, 0, str)
d.image2buf(image)
d.clear
d.display
rescue => e
puts e.full_message
ensure
d.stop if d
spi.close
pi.stop
end
__END__
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
|
Python
|
UTF-8
| 5,261
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
import math
from printing_tools import *
def circle_array(radius, n, p0):
""""Simple circle, or rather regular polygon with n vertices"""""
array = []
for phi in np.linspace(0, 2 * np.pi, n):
p = list(p0)
p[0] += np.sin(phi) * radius
p[1] += (1 + np.cos(phi)) * radius
array.append(list(p))
return array
def color_array(wavelength, axis_name, layers=100, harm=0, n0=1.45, z_limit=100):
if axis_name == "z":
dz = (2 * harm + 1) * wavelength / (2 * n0)
z_steps = int(math.floor(z_limit / dz))
positions = np.linspace(0, 100, layers)
return positions, z_steps, dz
if axis_name == "x":
dx = (2 * harm + 1) * wavelength / (2 * n0)
positions = np.arange(0, 100, dx)
dz = z_limit/(layers-1)
return positions, layers, dz
print("you can choose only x and z axis :/")
def cross_array(max_shift, z_range=100, x_range=100, y_range=100,
p0=np.array([50, 50, 0])):
array = [np.copy(p0)]
p = np.array([0, 0, 0])
for z in np.arange(0, z_range, max_shift):
for x in np.arange(0, 0.5 * x_range, max_shift):
array.append(p0 + p)
p[0] = x
for x in np.arange(0.5 * x_range, -0.5 * x_range, -max_shift):
array.append(p0 + p)
p[0] = x
for x in np.arange(-0.5 * x_range, 0, max_shift):
array.append(p0 + p)
p[0] = x
for y in np.arange(0, 0.5 * y_range, max_shift):
array.append(p0 + p)
p[1] = y
for y in np.arange(0.5 * y_range, -0.5 * y_range, -max_shift):
array.append(p0 + p)
p[1] = y
for y in np.arange(-0.5 * y_range, 0, max_shift):
array.append(p0 + p)
p[1] = y
p[2] = z
return array
def height_test_array(rate, line_len, z_steps,
speed_limit=10.0, p0=np.array([0.0, 0.0, 100.0]), z_range=100.0, x_range=100.0, margin=5.0):
"""This is a specific pattern to print in order to check if the height
is correct"""
p = [0, 0, 0]
array = [np.copy(p0)]
ds = speed_limit * rate
delta_z = z_range / z_steps
line_dist_x = (x_range - line_len) / z_steps
for z in range(z_steps):
y0 = p[1]
x0 = p[0]
p, tmp_arr = move_slow(p0, p, y0 + line_len, ds, 1, margin)
array += list(tmp_arr)
p, tmp_arr = wait(p0, p, 2)
array += list(tmp_arr)
p, tmp_arr = move_slow(p0, p, y0 + line_len * z / z_steps, ds, 1, margin)
array += list(tmp_arr)
p[1] = y0 + line_len * z / z_steps
p, tmp_arr = move_slow(p0, p, x0 + line_len, ds, 0, margin)
array += list(tmp_arr)
p, tmp_arr = wait(p0, p, 2)
array += list(tmp_arr)
p, tmp_arr = move_slow(p0, p, x0, ds, 0, margin)
array += list(tmp_arr)
p[0] = x0
p, tmp_arr = move_slow(p0, p, y0, ds, 1, margin)
array += list(tmp_arr)
p[1] = y0
if z < z_steps - 1:
p, tmp_arr = wait(p0, p, 2)
array += list(tmp_arr)
p, tmp_arr = move(p0, p, x0 + line_dist_x, ds, 0)
array += list(tmp_arr)
p[0] = x0 + line_dist_x
p, tmp_arr = move(p0, p, -(z + 1) * delta_z, ds, 2)
array += list(tmp_arr)
p[2] = -(z + 1) * delta_z
return array
def square_wave_array(p0, dx, nx, stepsx, dy, ny):
""""Simple square wave in x and y directions
which whe didn't managed to print """""
assert (nx * ny < 3333)
assert (dx * nx * stepsx < 100.0e3)
assert (dy * ny < 100.0e3)
array = []
p = list(p0)
for idx in range(nx):
for _ in range(stepsx):
p[0] += dx
array.append(list(p))
if idx % 2 == 0:
for y in range(ny):
p[1] += dy
array.append(list(p))
else:
for y in range(ny):
p[1] -= dy
array.append((list(p)))
return array
if __name__ == '__main__':
# general parameters
plot_stuff = True
speed = 2
rate = 1
# color pattern parameters
wlen = 0.521
layers_ = 20
axis = "x"
# height pattern parameters
line_length = 20
arr = height_test_array(
rate=rate,
line_len=line_length,
z_steps=layers_,
speed_limit=speed)
plot_arr = arr
# positions, z_steps, delta_z = color_array(plot_stuff, wlen, speed, axis=axis, layers=layers)
# plot_arr, arr = pattern2array3d_pair(
# p0=np.array([0, 0, 100]),
# rate=rate,
# pattern=positions,
# speed=np.ones_like(positions) * speed,
# z_steps=z_steps,
# delta_z=delta_z)
if plot_stuff:
plot_arr = np.array(plot_arr)
arr = np.array(arr)
print("full length:", len(arr))
if plot_stuff:
print("without markers", len(plot_arr))
check_array(plot_arr, rate=rate, max_speed=speed+0.01,
max_points=3333 * 1000, max_speed_change=speed+0.01)
# array2file(rate, arr, "color_"+ axis +"_" + str(wlen) + "_wlen_" + str(speed) + "_speed.lipp")
print("file created")
if plot_stuff:
plot_pattern(plot_arr)
|
Python
|
UTF-8
| 686
| 3.296875
| 3
|
[] |
no_license
|
# Uses python3
import sys
def inversions(nums):
n = len(nums)
if (n == 1):
return 0, nums
x, a = inversions(nums[0 : n // 2])
y, b = inversions(nums[n // 2 : n])
z, c = merge_sort(a, b)
return x + y + z, c
def merge_sort(a, b):
i, j, z = 0, 0, 0
la, lb = len(a), len(b)
c = []
for _ in range(0, la + lb):
if (j >= lb or i < la and a[i] <= b[j]):
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
z += la - i
return z, c
if __name__ == '__main__':
input = sys.stdin.read()
_, *a = list(map(int, input.split()))
o=inversions(a)
print (o[0])
|
C++
|
UTF-8
| 4,545
| 3.484375
| 3
|
[] |
no_license
|
#define CATCH_CONFIG_FAST_COMPILE
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <set>
struct ListNode {
int val;
ListNode *next{nullptr};
ListNode(int x) : val(x) {}
};
// this solution creates a new list
//class Solution {
//public:
// ListNode* mergeTwoLists(const ListNode* L1, const ListNode* L2) {
// if (L1 == nullptr && L2 == nullptr) return nullptr;
// if (L1 == nullptr) return cloneList(L2);
// if (L2 == nullptr) return cloneList(L1);
//
// if (L1->val > L2->val)
// {
// std::swap(L1, L2);
// }
// ListNode* head = new ListNode(L1->val);
// ListNode* tail = head;
// L1 = L1->next;
//
// while (L1 && L2)
// {
// if (L1->val < L2->val)
// {
// tail->next = new ListNode(L1->val);
// L1 = L1->next;
// }
// else
// {
// tail->next = new ListNode(L2->val);
// L2 = L2->next;
// }
// tail = tail->next;
// }
// if (L1)
// {
// tail->next = cloneList(L1);
// }
// if (L2)
// {
// tail->next = cloneList(L2);
// }
//
// return head;
// }
//
//private:
// ListNode* cloneList(const ListNode* L)
// {
// ListNode* head = new ListNode(L->val);
// ListNode* tail = head;
// L = L->next;
//
// while (L)
// {
// tail->next = new ListNode(L->val);
// tail = tail->next;
// L = L->next;
// }
//
// return head;
// }
//};
// this solution does merging in-place
// possible improvement: use dummy head node to keep track and then return dummy.next, e.g.:
//ListNode* mergeTwoLists(ListNode* curr1, ListNode* curr2) {
// ListNode dummy(INT_MIN);
// ListNode *curr = &dummy;
// while(curr1 && curr2){
// if(curr1->val <= curr2->val){
// curr -> next = curr1;
// curr1 = curr1-> next;
// }
// else if(curr1->val > curr2->val){
// curr -> next = curr2;
// curr2 = curr2-> next;
// }
// curr = curr ->next;
// }
// if(curr1)
// curr -> next = curr1;
// else
// curr -> next = curr2;
//
// return dummy.next;
//}
class Solution {
public:
ListNode* mergeTwoLists(ListNode* L1, ListNode* L2) {
if (L1 == nullptr) return L2;
if (L2 == nullptr) return L1;
if (L1->val > L2->val)
{
std::swap(L1, L2);
}
ListNode* head = L1;
ListNode* tail = head;
L1 = L1->next;
while (L1 && L2)
{
if (L1->val < L2->val)
{
tail->next = L1;
L1 = L1->next;
}
else
{
tail->next = L2;
L2 = L2->next;
}
tail = tail->next;
}
if (L1)
{
tail->next = L1;
}
if (L2)
{
tail->next = L2;
}
return head;
}
private:
ListNode* cloneList(const ListNode* L)
{
ListNode* head = new ListNode(L->val);
ListNode* tail = head;
L = L->next;
while (L)
{
tail->next = new ListNode(L->val);
tail = tail->next;
L = L->next;
}
return head;
}
};
ListNode* vector_to_list(const std::vector<int>& v)
{
if(v.empty()) return nullptr;
ListNode* head = new ListNode(v[0]);
ListNode* tail = head;
for(size_t i=1;i<v.size();i++)
{
auto n = v[i];
tail->next = new ListNode(n);
tail = tail->next;
}
return head;
}
std::vector<int> list_to_vector(ListNode* head)
{
std::vector<int> v;
while (head)
{
v.push_back(head->val);
head = head->next;
}
return v;
}
TEST_CASE("Example null 1")
{
Solution solution;
CHECK(solution.mergeTwoLists(nullptr, nullptr) == nullptr);
}
TEST_CASE("Example null 2")
{
Solution solution;
auto r = solution.mergeTwoLists(nullptr, vector_to_list({ 1 }));
CHECK(list_to_vector(r) == std::vector<int>{1});
}
TEST_CASE("Example null 3")
{
Solution solution;
auto r = solution.mergeTwoLists(vector_to_list({ 1 }), nullptr);
CHECK(list_to_vector(r) == std::vector<int>{1});
}
TEST_CASE("Example 1")
{
Solution solution;
auto r = solution.mergeTwoLists(vector_to_list({ 1,2,4 }), vector_to_list({ 1,3,4 }));
CHECK(list_to_vector(r) == std::vector<int>{1, 1, 2, 3, 4, 4});
}
|
Markdown
|
UTF-8
| 1,565
| 2.765625
| 3
|
[
"Unlicense"
] |
permissive
|
# مستوطنون صهاينة يسرقون ثمار 900 شجرة زيتون جنوب نابلس
Published at: **2019-11-05T00:00:00+00:00**
Author: ****
Original: [almanar.com.lb](http://almanar.com.lb/5918926)
أقدم مستوطنون صهاينة الثلاثاء على سرقة ثمار مئات أشجار الزيتون من أراضي قرية “اللبن” الشرقية جنوب نابلس بالضفة الغربية الفلسطينية المحتلة.
وقالت مصادر فلسطينية إن “مزارعي قرية اللبن الشرقية، أفادوا بسرقة مستوطني مستوطنة عيليه الصهيونية، ثمار نحو 900 شجرة زيتون من حقولهم الواقعة في منطقة واد علي والمملوكة للعديد من العائلات”.
ولفتت المصادر الى ان “أشجار الفلسطينون تقع في محيط المستوطنة المقامة على أراضي البلدة ويمنع الأهالي الوصول لها دون تنسيق مع الجهات ذات الاختصاص”.
وأشارت المصادر الى ان “سلطات الاحتلال الإسرائيلي تمنع أصحاب الأراضي المحاذية للمستوطنات من دخول أراضيهم والاعتناء بها وتفقدها، إلا من خلال تصاريح لأيام محددة خلال العام، ما يجعلها هدفا للمستوطنين في اعتداءاتهم وسرقة محاصيلها”.
المصدر: وكالة شهاب الفلسطينية
|
C++
|
UTF-8
| 28,632
| 2.75
| 3
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
/**
* @file py_panda.cxx
* @author drose
* @date 2005-07-04
*/
#include "py_panda.h"
#include "config_interrogatedb.h"
#include "executionEnvironment.h"
#ifdef HAVE_PYTHON
#define _STRINGIFY_VERSION(a, b) (#a "." #b)
#define STRINGIFY_VERSION(a, b) _STRINGIFY_VERSION(a, b)
using std::string;
/**
*/
void DTOOL_Call_ExtractThisPointerForType(PyObject *self, Dtool_PyTypedObject *classdef, void **answer) {
if (DtoolInstance_Check(self)) {
*answer = DtoolInstance_UPCAST(self, *classdef);
} else {
*answer = nullptr;
}
}
/**
* This is a support function for the Python bindings: it extracts the
* underlying C++ pointer of the given type for a given Python object. If it
* was of the wrong type, raises an AttributeError.
*/
bool Dtool_Call_ExtractThisPointer(PyObject *self, Dtool_PyTypedObject &classdef, void **answer) {
if (self == nullptr || !DtoolInstance_Check(self) || DtoolInstance_VOID_PTR(self) == nullptr) {
Dtool_Raise_TypeError("C++ object is not yet constructed, or already destructed.");
return false;
}
*answer = DtoolInstance_UPCAST(self, classdef);
return true;
}
/**
* The same thing as Dtool_Call_ExtractThisPointer, except that it performs
* the additional check that the pointer is a non-const pointer. This is
* called by function wrappers for functions of which all overloads are non-
* const, and saves a bit of code.
*
* The extra method_name argument is used in formatting the error message.
*/
bool Dtool_Call_ExtractThisPointer_NonConst(PyObject *self, Dtool_PyTypedObject &classdef,
void **answer, const char *method_name) {
if (self == nullptr || !DtoolInstance_Check(self) || DtoolInstance_VOID_PTR(self) == nullptr) {
Dtool_Raise_TypeError("C++ object is not yet constructed, or already destructed.");
return false;
}
if (DtoolInstance_IS_CONST(self)) {
// All overloads of this function are non-const.
PyErr_Format(PyExc_TypeError,
"Cannot call %s() on a const object.",
method_name);
return false;
}
*answer = DtoolInstance_UPCAST(self, classdef);
return true;
}
/**
* Extracts the C++ pointer for an object, given its Python wrapper object,
* for passing as the parameter to a C++ function.
*
* self is the Python wrapper object in question.
*
* classdef is the Python class wrapper for the C++ class in which the this
* pointer should be returned. (This may require an upcast operation, if self
* is not already an instance of classdef.)
*
* param and function_name are used for error reporting only, and describe the
* particular function and parameter index for this parameter.
*
* const_ok is true if the function is declared const and can therefore be
* called with either a const or non-const "this" pointer, or false if the
* function is declared non-const, and can therefore be called with only a
* non-const "this" pointer.
*
* The return value is the C++ pointer that was extracted, or NULL if there
* was a problem (in which case the Python exception state will have been
* set).
*/
void *
DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef,
int param, const string &function_name, bool const_ok,
bool report_errors) {
// if (PyErr_Occurred()) { return nullptr; }
if (self == nullptr) {
if (report_errors) {
return Dtool_Raise_TypeError("self is nullptr");
}
return nullptr;
}
if (DtoolInstance_Check(self)) {
void *result = DtoolInstance_UPCAST(self, *classdef);
if (result != nullptr) {
if (const_ok || !DtoolInstance_IS_CONST(self)) {
return result;
}
if (report_errors) {
return PyErr_Format(PyExc_TypeError,
"%s() argument %d may not be const",
function_name.c_str(), param);
}
return nullptr;
}
}
if (report_errors) {
return Dtool_Raise_ArgTypeError(self, param, function_name.c_str(), classdef->_PyType.tp_name);
}
return nullptr;
}
/**
* This is similar to a PyErr_Occurred() check, except that it also checks
* Notify to see if an assertion has occurred. If that is the case, then it
* raises an AssertionError.
*
* Returns true if there is an active exception, false otherwise.
*
* In the NDEBUG case, this is simply a #define to PyErr_Occurred().
*/
bool _Dtool_CheckErrorOccurred() {
if (PyErr_Occurred()) {
return true;
}
if (Notify::ptr()->has_assert_failed()) {
Dtool_Raise_AssertionError();
return true;
}
return false;
}
/**
* Raises an AssertionError containing the last thrown assert message, and
* clears the assertion flag. Returns NULL.
*/
PyObject *Dtool_Raise_AssertionError() {
Notify *notify = Notify::ptr();
#if PY_MAJOR_VERSION >= 3
PyObject *message = PyUnicode_FromString(notify->get_assert_error_message().c_str());
#else
PyObject *message = PyString_FromString(notify->get_assert_error_message().c_str());
#endif
PyErr_SetObject(PyExc_AssertionError, message);
notify->clear_assert_failed();
return nullptr;
}
/**
* Raises a TypeError with the given message, and returns NULL.
*/
PyObject *Dtool_Raise_TypeError(const char *message) {
PyErr_SetString(PyExc_TypeError, message);
return nullptr;
}
/**
* Raises a TypeError of the form: function_name() argument n must be type,
* not type for a given object passed to a function.
*
* Always returns NULL so that it can be conveniently used as a return
* expression for wrapper functions that return a PyObject pointer.
*/
PyObject *Dtool_Raise_ArgTypeError(PyObject *obj, int param, const char *function_name, const char *type_name) {
#if PY_MAJOR_VERSION >= 3
PyObject *message = PyUnicode_FromFormat(
#else
PyObject *message = PyString_FromFormat(
#endif
"%s() argument %d must be %s, not %s",
function_name, param, type_name,
Py_TYPE(obj)->tp_name);
PyErr_SetObject(PyExc_TypeError, message);
return nullptr;
}
/**
* Raises an AttributeError of the form: 'type' has no attribute 'attr'
*
* Always returns NULL so that it can be conveniently used as a return
* expression for wrapper functions that return a PyObject pointer.
*/
PyObject *Dtool_Raise_AttributeError(PyObject *obj, const char *attribute) {
#if PY_MAJOR_VERSION >= 3
PyObject *message = PyUnicode_FromFormat(
#else
PyObject *message = PyString_FromFormat(
#endif
"'%.100s' object has no attribute '%.200s'",
Py_TYPE(obj)->tp_name, attribute);
PyErr_SetObject(PyExc_AttributeError, message);
return nullptr;
}
/**
* Raises a TypeError of the form: Arguments must match: <list of overloads>
*
* However, in release builds, this instead is defined to a function that just
* prints out a generic message, to help reduce the amount of strings in the
* compiled library.
*
* Always returns NULL so that it can be conveniently used as a return
* expression for wrapper functions that return a PyObject pointer.
*/
PyObject *_Dtool_Raise_BadArgumentsError() {
return Dtool_Raise_TypeError("arguments do not match any function overload");
}
/**
* Convenience method that checks for exceptions, and if one occurred, returns
* NULL, otherwise Py_None.
*/
PyObject *_Dtool_Return_None() {
if (UNLIKELY(PyErr_Occurred())) {
return nullptr;
}
#ifndef NDEBUG
if (UNLIKELY(Notify::ptr()->has_assert_failed())) {
return Dtool_Raise_AssertionError();
}
#endif
Py_INCREF(Py_None);
return Py_None;
}
/**
* Convenience method that checks for exceptions, and if one occurred, returns
* NULL, otherwise the given boolean value as a PyObject *.
*/
PyObject *Dtool_Return_Bool(bool value) {
if (UNLIKELY(PyErr_Occurred())) {
return nullptr;
}
#ifndef NDEBUG
if (UNLIKELY(Notify::ptr()->has_assert_failed())) {
return Dtool_Raise_AssertionError();
}
#endif
PyObject *result = (value ? Py_True : Py_False);
Py_INCREF(result);
return result;
}
/**
* Convenience method that checks for exceptions, and if one occurred, returns
* NULL, otherwise the given return value. Its reference count is not
* increased.
*/
PyObject *_Dtool_Return(PyObject *value) {
if (UNLIKELY(PyErr_Occurred())) {
return nullptr;
}
#ifndef NDEBUG
if (UNLIKELY(Notify::ptr()->has_assert_failed())) {
return Dtool_Raise_AssertionError();
}
#endif
return value;
}
#if PY_VERSION_HEX < 0x03040000
/**
* This function converts an int value to the appropriate enum instance.
*/
static PyObject *Dtool_EnumType_New(PyTypeObject *subtype, PyObject *args, PyObject *kwds) {
PyObject *arg;
if (!Dtool_ExtractArg(&arg, args, kwds, "value")) {
return PyErr_Format(PyExc_TypeError,
"%s() missing 1 required argument: 'value'",
subtype->tp_name);
}
if (Py_TYPE(arg) == subtype) {
Py_INCREF(arg);
return arg;
}
PyObject *value2member = PyDict_GetItemString(subtype->tp_dict, "_value2member_map_");
nassertr_always(value2member != nullptr, nullptr);
PyObject *member = PyDict_GetItem(value2member, arg);
if (member != nullptr) {
Py_INCREF(member);
return member;
}
PyObject *repr = PyObject_Repr(arg);
PyErr_Format(PyExc_ValueError, "%s is not a valid %s",
#if PY_MAJOR_VERSION >= 3
PyUnicode_AS_STRING(repr),
#else
PyString_AS_STRING(repr),
#endif
subtype->tp_name);
Py_DECREF(repr);
return nullptr;
}
static PyObject *Dtool_EnumType_Str(PyObject *self) {
PyObject *name = PyObject_GetAttrString(self, "name");
#if PY_MAJOR_VERSION >= 3
PyObject *repr = PyUnicode_FromFormat("%s.%s", Py_TYPE(self)->tp_name, PyString_AS_STRING(name));
#else
PyObject *repr = PyString_FromFormat("%s.%s", Py_TYPE(self)->tp_name, PyString_AS_STRING(name));
#endif
Py_DECREF(name);
return repr;
}
static PyObject *Dtool_EnumType_Repr(PyObject *self) {
PyObject *name = PyObject_GetAttrString(self, "name");
PyObject *value = PyObject_GetAttrString(self, "value");
#if PY_MAJOR_VERSION >= 3
PyObject *repr = PyUnicode_FromFormat("<%s.%s: %ld>", Py_TYPE(self)->tp_name, PyString_AS_STRING(name), PyLongOrInt_AS_LONG(value));
#else
PyObject *repr = PyString_FromFormat("<%s.%s: %ld>", Py_TYPE(self)->tp_name, PyString_AS_STRING(name), PyLongOrInt_AS_LONG(value));
#endif
Py_DECREF(name);
Py_DECREF(value);
return repr;
}
#endif
/**
* Creates a Python 3.4-style enum type. Steals reference to 'names', which
* should be a tuple of (name, value) pairs.
*/
PyTypeObject *Dtool_EnumType_Create(const char *name, PyObject *names, const char *module) {
static PyObject *enum_class = nullptr;
#if PY_VERSION_HEX >= 0x03040000
static PyObject *enum_meta = nullptr;
static PyObject *enum_create = nullptr;
if (enum_meta == nullptr) {
PyObject *enum_module = PyImport_ImportModule("enum");
nassertr_always(enum_module != nullptr, nullptr);
enum_class = PyObject_GetAttrString(enum_module, "Enum");
enum_meta = PyObject_GetAttrString(enum_module, "EnumMeta");
enum_create = PyObject_GetAttrString(enum_meta, "_create_");
nassertr(enum_meta != nullptr, nullptr);
}
PyObject *result = PyObject_CallFunction(enum_create, (char *)"OsN", enum_class, name, names);
nassertr(result != nullptr, nullptr);
#else
static PyObject *name_str;
static PyObject *name_sunder_str;
static PyObject *value_str;
static PyObject *value_sunder_str;
static PyObject *value2member_map_sunder_str;
// Emulate something vaguely like the enum module.
if (enum_class == nullptr) {
#if PY_MAJOR_VERSION >= 3
name_str = PyUnicode_InternFromString("name");
value_str = PyUnicode_InternFromString("value");
name_sunder_str = PyUnicode_InternFromString("_name_");
value_sunder_str = PyUnicode_InternFromString("_value_");
value2member_map_sunder_str = PyUnicode_InternFromString("_value2member_map_");
#else
name_str = PyString_InternFromString("name");
value_str = PyString_InternFromString("value");
name_sunder_str = PyString_InternFromString("_name_");
value_sunder_str = PyString_InternFromString("_value_");
value2member_map_sunder_str = PyString_InternFromString("_value2member_map_");
#endif
PyObject *name_value_tuple = PyTuple_New(4);
PyTuple_SET_ITEM(name_value_tuple, 0, name_str);
PyTuple_SET_ITEM(name_value_tuple, 1, value_str);
PyTuple_SET_ITEM(name_value_tuple, 2, name_sunder_str);
PyTuple_SET_ITEM(name_value_tuple, 3, value_sunder_str);
Py_INCREF(name_str);
Py_INCREF(value_str);
PyObject *slots_dict = PyDict_New();
PyDict_SetItemString(slots_dict, "__slots__", name_value_tuple);
Py_DECREF(name_value_tuple);
enum_class = PyObject_CallFunction((PyObject *)&PyType_Type, (char *)"s()N", "Enum", slots_dict);
nassertr(enum_class != nullptr, nullptr);
}
// Create a subclass of this generic Enum class we just created.
PyObject *value2member = PyDict_New();
PyObject *dict = PyDict_New();
PyDict_SetItem(dict, value2member_map_sunder_str, value2member);
PyObject *result = PyObject_CallFunction((PyObject *)&PyType_Type, (char *)"s(O)N", name, enum_class, dict);
nassertr(result != nullptr, nullptr);
((PyTypeObject *)result)->tp_new = Dtool_EnumType_New;
((PyTypeObject *)result)->tp_str = Dtool_EnumType_Str;
((PyTypeObject *)result)->tp_repr = Dtool_EnumType_Repr;
PyObject *empty_tuple = PyTuple_New(0);
// Copy the names as instances of the above to the class dict, and create a
// reverse mapping in the _value2member_map_ dict.
Py_ssize_t size = PyTuple_GET_SIZE(names);
for (Py_ssize_t i = 0; i < size; ++i) {
PyObject *item = PyTuple_GET_ITEM(names, i);
PyObject *name = PyTuple_GET_ITEM(item, 0);
PyObject *value = PyTuple_GET_ITEM(item, 1);
PyObject *member = PyType_GenericNew((PyTypeObject *)result, empty_tuple, nullptr);
PyObject_SetAttr(member, name_str, name);
PyObject_SetAttr(member, name_sunder_str, name);
PyObject_SetAttr(member, value_str, value);
PyObject_SetAttr(member, value_sunder_str, value);
PyObject_SetAttr(result, name, member);
PyDict_SetItem(value2member, value, member);
Py_DECREF(member);
}
Py_DECREF(names);
Py_DECREF(value2member);
Py_DECREF(empty_tuple);
#endif
if (module != nullptr) {
PyObject *modstr = PyUnicode_FromString(module);
PyObject_SetAttrString(result, "__module__", modstr);
Py_DECREF(modstr);
}
nassertr(PyType_Check(result), nullptr);
return (PyTypeObject *)result;
}
/**
*/
PyObject *DTool_CreatePyInstanceTyped(void *local_this_in, Dtool_PyTypedObject &known_class_type, bool memory_rules, bool is_const, int type_index) {
// We can't do the NULL check here like in DTool_CreatePyInstance, since the
// caller will have to get the type index to pass to this function to begin
// with. That code probably would have crashed by now if it was really NULL
// for whatever reason.
nassertr(local_this_in != nullptr, nullptr);
// IF the class is possibly a run time typed object
if (type_index > 0) {
// get best fit class...
Dtool_PyInstDef *self = (Dtool_PyInstDef *)TypeHandle::from_index(type_index).wrap_python(local_this_in, &known_class_type._PyType);
if (self != nullptr) {
self->_memory_rules = memory_rules;
self->_is_const = is_const;
return (PyObject *)self;
}
}
// if we get this far .. just wrap the thing in the known type ?? better
// than aborting...I guess....
Dtool_PyInstDef *self = (Dtool_PyInstDef *)PyType_GenericAlloc(&known_class_type._PyType, 0);
if (self != nullptr) {
self->_signature = PY_PANDA_SIGNATURE;
self->_My_Type = &known_class_type;
self->_ptr_to_object = local_this_in;
self->_memory_rules = memory_rules;
self->_is_const = is_const;
}
return (PyObject *)self;
}
// DTool_CreatePyInstance .. wrapper function to finalize the existance of a
// general dtool py instance..
PyObject *DTool_CreatePyInstance(void *local_this, Dtool_PyTypedObject &in_classdef, bool memory_rules, bool is_const) {
if (local_this == nullptr) {
// This is actually a very common case, so let's allow this, but return
// Py_None consistently. This eliminates code in the wrappers.
Py_INCREF(Py_None);
return Py_None;
}
Dtool_PyInstDef *self = (Dtool_PyInstDef *)PyType_GenericAlloc(&in_classdef._PyType, 0);
if (self != nullptr) {
self->_signature = PY_PANDA_SIGNATURE;
self->_My_Type = &in_classdef;
self->_ptr_to_object = local_this;
self->_memory_rules = memory_rules;
self->_is_const = is_const;
self->_My_Type = &in_classdef;
}
return (PyObject *)self;
}
/**
* Returns a borrowed reference to the global type dictionary.
*/
Dtool_TypeMap *Dtool_GetGlobalTypeMap() {
PyObject *capsule = PySys_GetObject((char *)"_interrogate_types");
if (capsule != nullptr) {
return (Dtool_TypeMap *)PyCapsule_GetPointer(capsule, nullptr);
} else {
Dtool_TypeMap *type_map = new Dtool_TypeMap;
capsule = PyCapsule_New((void *)type_map, nullptr, nullptr);
PySys_SetObject((char *)"_interrogate_types", capsule);
Py_DECREF(capsule);
return type_map;
}
}
#define PY_MAJOR_VERSION_STR #PY_MAJOR_VERSION "." #PY_MINOR_VERSION
#if PY_MAJOR_VERSION >= 3
PyObject *Dtool_PyModuleInitHelper(const LibraryDef *defs[], PyModuleDef *module_def) {
#else
PyObject *Dtool_PyModuleInitHelper(const LibraryDef *defs[], const char *modulename) {
#endif
// Check the version so we can print a helpful error if it doesn't match.
string version = Py_GetVersion();
size_t version_len = version.find('.', 2);
if (version_len != string::npos) {
version.resize(version_len);
}
if (version != STRINGIFY_VERSION(PY_MAJOR_VERSION, PY_MINOR_VERSION)) {
// Raise a helpful error message. We can safely do this because the
// signature and behavior for PyErr_SetString has remained consistent.
std::ostringstream errs;
errs << "this module was compiled for Python "
<< PY_MAJOR_VERSION << "." << PY_MINOR_VERSION << ", which is "
<< "incompatible with Python " << version;
string error = errs.str();
PyErr_SetString(PyExc_ImportError, error.c_str());
return nullptr;
}
Dtool_TypeMap *type_map = Dtool_GetGlobalTypeMap();
// the module level function inits....
MethodDefmap functions;
for (size_t i = 0; defs[i] != nullptr; i++) {
const LibraryDef &def = *defs[i];
// Accumulate method definitions.
for (PyMethodDef *meth = def._methods; meth->ml_name != nullptr; meth++) {
if (functions.find(meth->ml_name) == functions.end()) {
functions[meth->ml_name] = meth;
}
}
// Define exported types.
const Dtool_TypeDef *types = def._types;
if (types != nullptr) {
while (types->name != nullptr) {
(*type_map)[std::string(types->name)] = types->type;
++types;
}
}
}
// Resolve external types, in a second pass.
for (size_t i = 0; defs[i] != nullptr; i++) {
const LibraryDef &def = *defs[i];
Dtool_TypeDef *types = def._external_types;
if (types != nullptr) {
while (types->name != nullptr) {
auto it = type_map->find(std::string(types->name));
if (it != type_map->end()) {
types->type = it->second;
} else {
return PyErr_Format(PyExc_NameError, "name '%s' is not defined", types->name);
}
++types;
}
}
}
PyMethodDef *newdef = new PyMethodDef[functions.size() + 1];
MethodDefmap::iterator mi;
int offset = 0;
for (mi = functions.begin(); mi != functions.end(); mi++, offset++) {
newdef[offset] = *mi->second;
}
newdef[offset].ml_doc = nullptr;
newdef[offset].ml_name = nullptr;
newdef[offset].ml_meth = nullptr;
newdef[offset].ml_flags = 0;
#if PY_MAJOR_VERSION >= 3
module_def->m_methods = newdef;
PyObject *module = PyModule_Create(module_def);
#else
PyObject *module = Py_InitModule((char *)modulename, newdef);
#endif
if (module == nullptr) {
#if PY_MAJOR_VERSION >= 3
return Dtool_Raise_TypeError("PyModule_Create returned NULL");
#else
return Dtool_Raise_TypeError("Py_InitModule returned NULL");
#endif
}
// MAIN_DIR needs to be set very early; this seems like a convenient place
// to do that. Perhaps we'll find a better place for this in the future.
static bool initialized_main_dir = false;
if (!initialized_main_dir) {
if (interrogatedb_cat.is_debug()) {
// Good opportunity to print this out once, at startup.
interrogatedb_cat.debug()
<< "Python " << version << "\n";
}
if (!ExecutionEnvironment::has_environment_variable("MAIN_DIR")) {
// Grab the __main__ module.
PyObject *main_module = PyImport_ImportModule("__main__");
if (main_module == NULL) {
interrogatedb_cat.warning() << "Unable to import __main__\n";
}
// Extract the __file__ attribute, if present.
Filename main_dir;
PyObject *file_attr = nullptr;
if (main_module != nullptr) {
file_attr = PyObject_GetAttrString(main_module, "__file__");
}
if (file_attr == nullptr) {
// Must be running in the interactive interpreter. Use the CWD.
main_dir = ExecutionEnvironment::get_cwd();
} else {
#if PY_MAJOR_VERSION >= 3
Py_ssize_t length;
wchar_t *buffer = PyUnicode_AsWideCharString(file_attr, &length);
if (buffer != nullptr) {
main_dir = Filename::from_os_specific_w(std::wstring(buffer, length));
main_dir.make_absolute();
main_dir = main_dir.get_dirname();
PyMem_Free(buffer);
}
#else
char *buffer;
Py_ssize_t length;
if (PyString_AsStringAndSize(file_attr, &buffer, &length) != -1) {
main_dir = Filename::from_os_specific(std::string(buffer, length));
main_dir.make_absolute();
main_dir = main_dir.get_dirname();
}
#endif
else {
interrogatedb_cat.warning() << "Invalid string for __main__.__file__\n";
}
}
ExecutionEnvironment::shadow_environment_variable("MAIN_DIR", main_dir.to_os_specific());
PyErr_Clear();
}
initialized_main_dir = true;
// Also, while we are at it, initialize the thread swap hook.
#if defined(HAVE_THREADS) && defined(SIMPLE_THREADS)
global_thread_state_swap = PyThreadState_Swap;
#endif
}
PyModule_AddIntConstant(module, "Dtool_PyNativeInterface", 1);
return module;
}
// HACK.... Be careful Dtool_BorrowThisReference This function can be used to
// grab the "THIS" pointer from an object and use it Required to support
// historical inheritance in the form of "is this instance of"..
PyObject *Dtool_BorrowThisReference(PyObject *self, PyObject *args) {
PyObject *from_in = nullptr;
PyObject *to_in = nullptr;
if (PyArg_UnpackTuple(args, "Dtool_BorrowThisReference", 2, 2, &to_in, &from_in)) {
if (DtoolInstance_Check(from_in) && DtoolInstance_Check(to_in)) {
Dtool_PyInstDef *from = (Dtool_PyInstDef *) from_in;
Dtool_PyInstDef *to = (Dtool_PyInstDef *) to_in;
// if (PyObject_TypeCheck(to_in, Py_TYPE(from_in))) {
if (from->_My_Type == to->_My_Type) {
to->_memory_rules = false;
to->_is_const = from->_is_const;
to->_ptr_to_object = from->_ptr_to_object;
Py_INCREF(Py_None);
return Py_None;
}
return PyErr_Format(PyExc_TypeError, "types %s and %s do not match",
Py_TYPE(from)->tp_name, Py_TYPE(to)->tp_name);
} else {
return Dtool_Raise_TypeError("One of these does not appear to be DTOOL Instance ??");
}
}
return nullptr;
}
// We do expose a dictionay for dtool classes .. this should be removed at
// some point..
EXPCL_PYPANDA PyObject *
Dtool_AddToDictionary(PyObject *self1, PyObject *args) {
PyObject *self;
PyObject *subject;
PyObject *key;
if (PyArg_ParseTuple(args, "OSO", &self, &key, &subject)) {
PyObject *dict = ((PyTypeObject *)self)->tp_dict;
if (dict == nullptr || !PyDict_Check(dict)) {
return Dtool_Raise_TypeError("No dictionary On Object");
} else {
PyDict_SetItem(dict, key, subject);
}
}
if (PyErr_Occurred()) {
return nullptr;
}
Py_INCREF(Py_None);
return Py_None;
}
/**
* This is a support function for a synthesized __copy__() method from a C++
* make_copy() method.
*/
PyObject *copy_from_make_copy(PyObject *self, PyObject *noargs) {
PyObject *callable = PyObject_GetAttrString(self, "make_copy");
if (callable == nullptr) {
return nullptr;
}
PyObject *result = PyObject_CallNoArgs(callable);
Py_DECREF(callable);
return result;
}
/**
* This is a support function for a synthesized __copy__() method from a C++
* copy constructor.
*/
PyObject *copy_from_copy_constructor(PyObject *self, PyObject *noargs) {
PyObject *callable = (PyObject *)Py_TYPE(self);
return PyObject_CallOneArg(callable, self);
}
/**
* This is a support function for a synthesized __deepcopy__() method for any
* class that has a __copy__() method. The sythethic method simply invokes
* __copy__().
*/
PyObject *map_deepcopy_to_copy(PyObject *self, PyObject *args) {
PyObject *callable = PyObject_GetAttrString(self, "__copy__");
if (callable == nullptr) {
return nullptr;
}
PyObject *result = PyObject_CallNoArgs(callable);
Py_DECREF(callable);
return result;
}
/**
* A more efficient version of PyArg_ParseTupleAndKeywords for the special
* case where there is only a single PyObject argument.
*/
bool Dtool_ExtractArg(PyObject **result, PyObject *args, PyObject *kwds,
const char *keyword) {
if (PyTuple_GET_SIZE(args) == 1) {
if (kwds == nullptr || PyDict_GET_SIZE(kwds) == 0) {
*result = PyTuple_GET_ITEM(args, 0);
return true;
}
}
else if (!keyword || !keyword[0]) {
return false;
}
else if (PyTuple_GET_SIZE(args) == 0) {
PyObject *key;
Py_ssize_t ppos = 0;
if (kwds != nullptr && PyDict_GET_SIZE(kwds) == 1 &&
PyDict_Next(kwds, &ppos, &key, result)) {
// We got the item, we just need to make sure that it had the right key.
#if PY_MAJOR_VERSION >= 3
return PyUnicode_CheckExact(key) && PyUnicode_CompareWithASCIIString(key, keyword) == 0;
#else
return PyString_CheckExact(key) && strcmp(PyString_AS_STRING(key), keyword) == 0;
#endif
}
}
return false;
}
/**
* Variant of Dtool_ExtractArg that does not accept a keyword argument.
*/
bool Dtool_ExtractArg(PyObject **result, PyObject *args, PyObject *kwds) {
if (PyTuple_GET_SIZE(args) == 1 &&
(kwds == nullptr || PyDict_GET_SIZE(kwds) == 0)) {
*result = PyTuple_GET_ITEM(args, 0);
return true;
}
return false;
}
/**
* A more efficient version of PyArg_ParseTupleAndKeywords for the special
* case where there is only a single optional PyObject argument.
*
* Returns true if valid (including if there were 0 items), false if there was
* an error, such as an invalid number of parameters.
*/
bool Dtool_ExtractOptionalArg(PyObject **result, PyObject *args, PyObject *kwds,
const char *keyword) {
if (PyTuple_GET_SIZE(args) == 1) {
if (kwds == nullptr || PyDict_GET_SIZE(kwds) == 0) {
*result = PyTuple_GET_ITEM(args, 0);
return true;
}
}
else if (!keyword || !keyword[0]) {
return (kwds == nullptr || PyDict_GET_SIZE(kwds) == 0);
}
else if (PyTuple_GET_SIZE(args) == 0) {
if (kwds != nullptr && PyDict_GET_SIZE(kwds) == 1) {
PyObject *key;
Py_ssize_t ppos = 0;
if (!PyDict_Next(kwds, &ppos, &key, result)) {
return true;
}
// We got the item, we just need to make sure that it had the right key.
#if PY_VERSION_HEX >= 0x03060000
return PyUnicode_CheckExact(key) && _PyUnicode_EqualToASCIIString(key, keyword);
#elif PY_MAJOR_VERSION >= 3
return PyUnicode_CheckExact(key) && PyUnicode_CompareWithASCIIString(key, keyword) == 0;
#else
return PyString_CheckExact(key) && strcmp(PyString_AS_STRING(key), keyword) == 0;
#endif
} else {
return true;
}
}
return false;
}
/**
* Variant of Dtool_ExtractOptionalArg that does not accept a keyword argument.
*/
bool Dtool_ExtractOptionalArg(PyObject **result, PyObject *args, PyObject *kwds) {
if (kwds != nullptr && PyDict_GET_SIZE(kwds) != 0) {
return false;
}
if (PyTuple_GET_SIZE(args) == 1) {
*result = PyTuple_GET_ITEM(args, 0);
return true;
}
return (PyTuple_GET_SIZE(args) == 0);
}
#endif // HAVE_PYTHON
|
C#
|
UTF-8
| 2,087
| 2.515625
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
//
// GetAdmx.cs
//
namespace PSPEdit.Cmdlet
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// <para type="synopsis">Parses ADMX file</para>
/// <para type="description">Parses the ADMX file</para>
/// </summary>
/// <example>
/// <code>Import-AdmxFile -File C:\ADMX\Policy.admx</code>
/// <para>
/// Parses the given ADMX file in the language of the current UI culture
/// </para>
/// </example>
/// <example>
/// <code>Get-ChildItems C:\ADMX -Include *.admx | Import-AdmxFile</code>
/// <para>
/// Parses all the given ADMX files in the language of the current UI culture
/// </para>
/// </example>
/// <example>
/// <code>Import-AdmxFile -File C:\ADMX\Policy.admx -Language en-ES</code>
/// <para>
/// Parses the given ADMX file in the specified language
/// </para>
/// </example>
[Cmdlet(VerbsData.Import, "AdmxFile", SupportsShouldProcess = true)]
public class ImportAdmxFile : PSCmdlet
{
/// <summary>
/// default cTor
/// </summary>
public ImportAdmxFile()
{
this.Language = System.Globalization.CultureInfo.CurrentUICulture.Name;
}
/// <summary>
/// <para type="description">The ADMX file to parse</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
public FileInfo File { get; set; }
/// <summary>
/// <para type="description">Language Tag (as definied in RFC5646)</para>
/// </summary>
[Parameter(Mandatory = false)]
public String Language { get; set; }
/// <summary>
/// Powershell cmdlet processing
/// </summary>
protected override void BeginProcessing()
{
WriteObject(new AdmxParse(this.File.FullName, this.Language));
}
}
}
|
Java
|
UTF-8
| 684
| 2.3125
| 2
|
[] |
no_license
|
package com.epam.preprod.pavlov.entity.order;
public class OrderStatus {
private int orderStatusId;
private String orderStatusName;
public OrderStatus(int orderStatusId, String orderStatusName) {
this.orderStatusId = orderStatusId;
this.orderStatusName = orderStatusName;
}
public String getOrderStatusName() {
return orderStatusName;
}
public void setOrderStatusName(String orderStatusName) {
this.orderStatusName = orderStatusName;
}
public int getOrderStatusId() {
return orderStatusId;
}
public void setOrderStatusId(int orderStatusId) {
this.orderStatusId = orderStatusId;
}
}
|
Markdown
|
UTF-8
| 847
| 3.34375
| 3
|
[] |
no_license
|
#my-diary
How to run this:
1) Make sure you have python 2.7 installed: `python -v`
2) Run next command: `python my_diary.py <file_name.txt>` Instead of file_name.txt use any file you want.
For example: `python my_diary.py mydiary.txt`
This is the repository to test my skills in Python.
You have some file, in which you will record data.
File begins from note
----My Diary----.
This project is about working with diary, list of functions can be found below:
- Run the program and write answers to the questions, which you see in console
- You can write or read your notes or if you want you can exit
- If you choose "write", write down what happened, this data will be saved to the file
- Record will be automatically attached to the day when it was created
- If you choose "read", program will show your notes, which you did before
|
Markdown
|
UTF-8
| 16,323
| 2.75
| 3
|
[] |
no_license
|
---
layout: post
title: "06.SpringBoot的错误机制"
date: 2018-06-21
description: "SpringBoot的错误机制"
tag: SpringBoot
---
### 一、SpringBoot错误的默认页面
1. 这里需要分为两种情况:
- 浏览器访问:

- 其他客户端访问:

2. 为什么会出现两种情况?
- 浏览器访问时,在请求头中的Accept对应的值为text/html,所以返回的是一个错误页面
- 其他客户端访问时,在请求头的Accept对应的值为`*/*`,所以返回的是一个Json数据
下面让我们来看看原理
### 二、SpringMVC错误页的自动配置类 ErrorMvcAutoConfiguration
1. 类声明如下:
```java
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, ResourceProperties.class })
public class ErrorMvcAutoConfiguration {
}
```
2. 我们主要来看这几个方法和内部类
1. errorAttributes方法
- 方法的代码如下:
```java
@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException());
}
```
该方法返回一个DefaultErrorAttributes对象,并注册到Spring容器中。下面我们来看看DefaultErrorAttributes对象的getErrorAttributes方法
- DefaultErrorAttributes对象的getErrorAttributes方法
```java
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest,
boolean includeStackTrace) {
Map<String, Object> errorAttributes = new LinkedHashMap<>();//错误属性map
errorAttributes.put("timestamp", new Date());//时间戳,见上面错误页
addStatus(errorAttributes, webRequest);//状态码
addErrorDetails(errorAttributes, webRequest, includeStackTrace);//错误详情
addPath(errorAttributes, webRequest);//访问的路径
return errorAttributes;
}
```
以上就是我们看到错误页面的提示内容,返回的JSON错误信息提示也是如此。
2. basicErrorController方法
- 方法代码如下:
```java
@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
this.errorViewResolvers);
}
```
和errorAttributes方法一样,返回一个BasicErrorController对象,并加入到Spring容器中,下面我们看看BasicErrorController是什么
- BasicErrorController
```java
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties;
public BasicErrorController(ErrorAttributes errorAttributes,
ErrorProperties errorProperties) {
this(errorAttributes, errorProperties, Collections.emptyList());
}
public BasicErrorController(ErrorAttributes errorAttributes,
ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, errorViewResolvers);
Assert.notNull(errorProperties, "ErrorProperties must not be null");
this.errorProperties = errorProperties;
}
@Override
public String getErrorPath() {
return this.errorProperties.getPath();
}
@RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status = getStatus(request);//获取状态码
//调用上面的getErrorAttributes方法获取错误属性
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);//解析错误视图
return (modelAndView != null ? modelAndView : new ModelAndView("error", model));
}
@RequestMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
//调用上面的getErrorAttributes方法获取错误属性
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);//获取状态码
return new ResponseEntity<>(body, status);//序列化为JSON
}
protected boolean isIncludeStackTrace(HttpServletRequest request,
MediaType produces) {
IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
if (include == IncludeStacktrace.ALWAYS) {
return true;
}
if (include == IncludeStacktrace.ON_TRACE_PARAM) {
return getTraceParameter(request);
}
return false;
}
protected ErrorProperties getErrorProperties() {
return this.errorProperties;
}
}
```
BasicErrorController本质上也是一个Controller,他映射的地址是`/error` ,所以有/error请求,就会来到这个Controller,观察`errorHtml`方法,发现他使用`@RequestMapping(produces = "text/html")` 标注,即我们的accept为`text/html` 时会来到这个方法,而这个方法组装错误提示后,返回视图。而accept不是`text/html` 时,会来到`error` 这个方法,组装提示信息后,返回JSON。
3. errorPageCustomizer方法
- 方法源码如下:
```java
@Bean
public ErrorPageCustomizer errorPageCustomizer() {
return new ErrorPageCustomizer(this.serverProperties);
}
```
方法返回一个ErrorPageCustomizer对象,并把这个对象注册到Spring容器中。下面我们看看这个对象registerErrorPages方法
- ErrorPageCustomizer.registerErrorPages()
```java
@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
//新建一个错误页,path是/error
ErrorPage errorPage = new ErrorPage(this.properties.getServlet().getServletPrefix()
+ this.properties.getError().getPath());
//添加错误页。
errorPageRegistry.addErrorPages(errorPage);
}
```
因上,于是乎,只要服务器出现错误,都会访问`/error` 这个请求。这是由web.xml注册的错误页规则所定,而BaseErrorController专门负责拦截这个请求,然后通过Accept来判断不同的客户端,已达到返回不同的结果的效果。
4. DefaultErrorViewResolverConfiguration内部类
- 类的源码如下;
```java
@Configuration
static class DefaultErrorViewResolverConfiguration {
private final ApplicationContext applicationContext;
private final ResourceProperties resourceProperties;
DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext,
ResourceProperties resourceProperties) {
this.applicationContext = applicationContext;
this.resourceProperties = resourceProperties;
}
@Bean
@ConditionalOnBean(DispatcherServlet.class)
@ConditionalOnMissingBean
public DefaultErrorViewResolver conventionErrorViewResolver() {
return new DefaultErrorViewResolver(this.applicationContext,this.resourceProperties);
}
}
```
`DefaultErrorViewResolverConfiguration` 只有一个`conventionErrorViewResolver` 方法需要我们看下,通过字面意思理解,这个方法是返回一个默认的错误视图解析器。那么我们来看看这个解析器的`resolveErrorView`方法
- DefaultErrorViewResolver.resolveErrorView
```java
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,
Map<String, Object> model) {
ModelAndView modelAndView = resolve(String.valueOf(status), model); //调用下面的方法进行解析
if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
}
return modelAndView;
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
//根据上面的调用,viewName值为错误码。如果是404,则为error/404.html
String errorViewName = "error/" + viewName;
//如果模板引擎可以解析这个页面地址就用模板引擎解析
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders
.getProvider(errorViewName, this.applicationContext);
if (provider != null) {
//模板引擎可用的情况下返回到errorViewName指定的视图地址
return new ModelAndView(errorViewName, model);
}
//模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
return resolveResource(errorViewName, model);
}
```
3. 错误页步骤
1. 一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则),发送`/error` 请求
2. 请求被`BaseErrorController`拦截。根据客户端类型,来判断返回视图。
3. 如果静态资源文件夹下找不到,则会创建一个ModelAndView(“error”)的视图。
4. 在`ErrorMvcAutoConfiguration`类中,有如下配置。配置了error模版
```java
@Configuration
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
@Conditional(ErrorTemplateMissingCondition.class)
protected static class WhitelabelErrorViewConfiguration {
//这就是error模版,上面的错误页面内容就是这里的。
private final SpelView defaultErrorView = new SpelView(
"<html><body><h1>Whitelabel Error Page</h1>"
+ "<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>"
+ "<div id='created'>${timestamp}</div>"
+ "<div>There was an unexpected error (type=${error}, status=${status}).</div>"
+ "<div>${message}</div></body></html>");
//返回error视图
@Bean(name = "error")
@ConditionalOnMissingBean(name = "error")
public View defaultErrorView() {
return this.defaultErrorView;
}
//添加BeanName视图解析器,加在这里是为了避免我们在类声明处加上 @EnableWebMvc 注解,
//从而使SpringMVC的自动配置不生效,而且又忘了配置BeanNameViewResolver的情况
@Bean
@ConditionalOnMissingBean
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return resolver;
}
}
```
### 三、自定义我们自己的错误页
上面介绍了SpringBoot错误页的原理。那么接下来我们就着手定制我们自己的错误页。
1. 定制错误页面
根据上面的分析,我们知道如果有模版解析器,会转到对应的模版解析器中去处理,如果没有的话就会在静态资源路径下去找对应的`状态码.html`页面 ,再没有的话就会应用默认的页面。那么我们可以这样来定制我们的错误页面
- 有模版解析器,就把错误页(`状态码.htlm`)放入到`resources/templates`下面。我们可以使用`4xx.html`、`5xx.html` 来匹配所有4和5开头的错误码。但是优先会寻找准确的。比如同一个目录下有`400.html ` 和`4xx.html` 优先显示的是`400.html` 中的内容
- 没有模版解析器,则可以把自定义错误页面放到静态资源路径下。
- 页面能够获取的属性如下:
- timestamp:时间戳
- status:状态码
- error:错误提示
- exception:异常对象
- message:异常消息
- errors:JSR303数据校验的错误都在这里
2. 定制错误JSON
1. 自定义异常处理&返回定制json数据(**没有自适应效果**)
```java
@ControllerAdvice //@ControllerAdvice 具体可参考 https://blog.csdn.net/w372426096/article/details/78429141
public class MyExceptionHandler {
@ResponseBody
//异常处理器,UserNotExistException是自己写的异常类,此注解的作用是当出现其定义的异常时,进行处理方法
@ExceptionHandler(UserNotExistException.class)
public Map<String,Object> handleException(Exception e){
Map<String,Object> map = new HashMap<>();
map.put("code","user.notexist");
map.put("message",e.getMessage());
return map;
}
}
```
2. 转发到/error进行自适应响应效果处理
```java
@ExceptionHandler(UserNotExistException.class)
public String handleException(Exception e, HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
//传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
/**
* Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",500);
map.put("code","user.notexist");
map.put("message",e.getMessage());
//转发到/error
return "forward:/error";
}
```
3. 如何携带我们自己定义的数据
经过上面的分析,我们已经知道,出现错误以后,会来到`/error`请求,会被`BasicErrorController`处理,响应出去可以获取的数据是由`DefaultErrorAttributes.getErrorAttributes`得到的。我们来看`DefaultErrorAttributes`的声明
```java
@Bean
//当容器中没有ErrorAttributes这个Bean是才会去创建。
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException());
}
```
那么,我们是否可以继承`DefaultErrorAttributes`这个类,来 定义一个自己的类,用于自定义数据的返回呢?答案是肯定的。源码如下:
```java
//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
map.put("blog","zyzl.github.io");
return map;
}
}
```
最终的结果是,响应是自适应的,而且响应也有我们自己定义的数据。
分析完毕,谢谢大家观看!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.