language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 5,728 | 2.984375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
"""Multi-scale Attention Convolutional Neural Network (MACNN)."""
__author__ = ["jnrusson1"]
from sktime.networks.base import BaseDeepNetwork
from sktime.utils.validation._dependencies import _check_dl_dependencies
class MACNNNetwork(BaseDeepNetwork):
"""Base MACNN Network for MACNNClassifier and MACNNRegressor.
Parameters
----------
padding : str, optional (default="same")
The type of padding to be provided in MACNN Blocks. Accepts
all the string values that keras.layers supports.
pool_size : int, optional (default=3)
A single value representing pooling windows which are applied
between two MACNN Blocks.
strides : int, optional (default=2)
A single value representing strides to be taken during the
pooling operation.
repeats : int, optional (default=2)
The number of MACNN Blocks to be stacked.
filter_sizes : tuple, optional (default=(64, 128, 256))
The input size of Conv1D layers within each MACNN Block.
kernel_size : tuple, optional (default=(3, 6, 12))
The output size of Conv1D layers within each MACNN Block.
reduction : int, optional (default=16)
The factor by which the first dense layer of a MACNN Block will be divided by.
random_state: int, optional (default=0)
The seed to any random action.
"""
_tags = {"python_dependencies": "tensorflow"}
def __init__(
self,
padding="same",
pool_size=3,
strides=2,
repeats=2,
filter_sizes=(64, 128, 256),
kernel_size=(3, 6, 12),
reduction=16,
random_state=0,
):
_check_dl_dependencies(severity="error")
super().__init__()
self.padding = padding
self.pool_size = pool_size
self.strides = strides
self.repeats = repeats
self.filter_sizes = filter_sizes
self.kernel_size = kernel_size
self.reduction = reduction
self.random_state = random_state
def _macnn_block(self, x, kernels, reduce):
"""Implement a single MACNN Block.
Parameters
----------
x : An instance of keras.layers.Layer
The previous layer, in case of the first
block it represents the input layer.
kernels: int
The base output dimension for dense layers, it corresponds
to elements `filter_sizes` attributes.
reduce: int
The factor by which, the first dense layer's output dimension
should be divided by, it corresponds to the `reduction` attribute.
Returns
-------
block_output: An instance of keras.layers.Layer
Represents the last layer of a MACNN Block, to be used by the next block.
"""
from tensorflow import keras, reduce_mean, reshape
conv_layers = []
for i in range(len(self.kernel_size)):
conv_layers.append(
keras.layers.Conv1D(kernels, self.kernel_size[i], padding=self.padding)(
x
)
)
x1 = keras.layers.Concatenate(axis=2)(conv_layers)
x1 = keras.layers.BatchNormalization()(x1)
x1 = keras.layers.Activation("relu")(x1)
x2 = reduce_mean(x1, 1)
x2 = keras.layers.Dense(
int(kernels * 3 / reduce), use_bias=False, activation="relu"
)(x2)
x2 = keras.layers.Dense(int(kernels * 3), use_bias=False, activation="relu")(x2)
x2 = reshape(x2, [-1, 1, kernels * 3])
return x1 * x2
def _stack(self, x, repeats, kernels, reduce):
"""Build MACNN Blocks and stack them.
Parameters
----------
x : Instance of keras.layers.Layer
The previous layer, in case of the first
block it represents the input layer.
repeats : int
The number of MACNN Blocks to be used.
Corresponds to `repeats` attribute.
kernels : int
The base output dimension for dense layers, it corresponds
to elements `filter_sizes` attributes.
Returns
-------
x : Instance of keras.layers.Layer
The final layer after repeatedly applying MACNN Blocks.
"""
for _ in range(repeats):
x = self._macnn_block(x, kernels, reduce)
return x
def build_network(self, input_shape, **kwargs):
"""Construct a network and return its input and output layers.
Parameters
----------
input_shape : tuple
The shape of the data(without batch) fed into the input layer
Returns
-------
input_layer : An instance of keras.layers.Input
The input layer of this Network.
output_layer: An instance of keras.layers.Layer
The output layer of this Network.
"""
from tensorflow import keras, reduce_mean
input_layer = keras.layers.Input(shape=input_shape)
x = self._stack(input_layer, self.repeats, self.filter_sizes[0], self.reduction)
x = keras.layers.MaxPooling1D(
self.pool_size, self.strides, padding=self.padding
)(x)
x = self._stack(x, self.repeats, self.filter_sizes[1], self.reduction)
x = keras.layers.MaxPooling1D(
self.pool_size, self.strides, padding=self.padding
)(x)
x = self._stack(x, self.repeats, self.filter_sizes[2], self.reduction)
output_layer = reduce_mean(x, 1)
return input_layer, output_layer
|
Markdown
|
UTF-8
| 1,581 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# TomatoTimer for Android
<a href='https://play.google.com/store/apps/details?id=artem122ya.tomatotimer'><img height="100" alt='Get it on Google Play' src='https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png'/></a>
TomatoTimer helps you increase productivity and fight procrastination with Pomodoro Technique.
TomatoTimer encourages you to divide your work time into 25-minute chunks separated by five-minute breaks. By doing that you'll be able to control how much time you spend working on your task.
Every fourth work interval you have to take a longer break of 15 minutes.
The app lets you fully customize these intervals, to completely fill your needs.
<p align="left">
<img src="https://user-images.githubusercontent.com/25901464/38814619-91db7c00-419a-11e8-9451-8f970aabd0e0.png" width="200"/>
<img src="https://user-images.githubusercontent.com/25901464/38814623-949ee8aa-419a-11e8-86df-e311610c32c5.png" width="200"/>
<img src="https://user-images.githubusercontent.com/25901464/38814627-967963d0-419a-11e8-8f1b-f57ced8e83db.png" width="200"/>
<img src="https://user-images.githubusercontent.com/25901464/38814630-992184b4-419a-11e8-9035-eb8a56ce6c6f.png" width="200"/>
<img src="https://user-images.githubusercontent.com/25901464/38814633-9b27f9e6-419a-11e8-95d1-957525feb916.png" height="200"/>
</p>
<b>Copyright 2018 Artem Yakushev
[Licensed](https://github.com/artem122ya/TomatoTimer-Android/blob/master/LICENSE) under the Apache License, Version 2.0</b>
Google Play and the Google Play logo are trademarks of Google LLC.
|
Markdown
|
UTF-8
| 2,032 | 2.5625 | 3 |
[] |
no_license
|
---
layout: post
title: 'Bag snatchers'
author: 'Maggie Ad'
image: ''
categories: ['Living in ST', 'Shantouer', 'ๆชๅ็ฑป']
tags: []
---
Ahh... I'm a little bit depressed today coz my parents are here and I can't take them anywhere. Also my friend Jonny has just arrived for the travelling we'd planned before I broke my foot. Also tomorrow my other friend Jess and her friend Nana arrive instead of us going to Yunnan. :(
The weather is in the high twenties, maybe into thirties, and tomorrow is National Day (1st October) - this country is hot!
I think it should be known that Shantou's a really safe place to live and hang around in except for if you have a bag. There's a really big problem at the moment with bag snatchers on scooters - and they're good, I know someone who got her bumbag snatched two nights ago (the third time she's been snatched from!).
Here you can walk around late at night, you don't have to worry about abductions or murder or even face-to-face muggings with knives, not even burglarly. Women can walk around at night and have no worries, and there's no significant problem with drunken violence. We don't even have pickpockets. But we do have those bag snatchers on bikes and my word are there a lot at the moment. My friend is a policeman in this department and often calls after having just spent 30 hrs (with no sleep?!) catching a bag snatcher and processing the necessary documents and things.
They come from outside Shantou and are either drug addicts or (mostly, I think) people with no job and no money. There's no social security here. Local people are utterly unforgiving and think it paints a really bad image onto their city, which I suppose it does - but it's really the only crime they have (aside from some gang activity in some clubs) - the only crime that affects the public. I just want people to be aware and know about it but also know that it's literally the only criminal danger you have to beware of.
Point: carry supermarket plastic bags or a rucksack on both shoulders!
|
Python
|
UTF-8
| 3,317 | 3.015625 | 3 |
[] |
no_license
|
import PIL
import matplotlib.pyplot as plt # single use of plt is commented out
import os.path
import PIL.ImageDraw
import random
def make_collage(original_image):
return original_image
def get_images(directory=None):
""" Returns PIL.Image objects for all the images in directory.
If directory is not specified, uses current directory.
Returns a 2-tuple containing
a list with a PIL.Image object for each image file in root_directory, and
a list with a string filename for each image file in root_directory
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
image_list = [] # Initialize aggregaotrs
file_list = []
directory_list = os.listdir(directory) # Get list of files
for entry in directory_list:
absolute_filename = os.path.join(directory, entry)
try:
image = PIL.Image.open(absolute_filename)
file_list += [entry]
image_list += [image]
except IOError:
pass # do nothing with errors tying to open non-images
return image_list, file_list
def make_collages(number_of_images=2, border_shape='rectangle', filter_color='random', directory=None):
"""
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
# Create a new directory 'framed'
new_directory = os.path.join(directory, 'collages')
try:
os.mkdir(new_directory)
except OSError:
pass # if the directory already exists, proceed
# Load all the images
image_list, file_list = get_images(directory)
random.shuffle(image_list)
# Go through the images and save modified versions
for n in range(len(image_list)/number_of_images):
# Round the corners with default percent of radius
curr_images = []
widths = []
heights = []
for i in range(number_of_images):
curr_images.append(image_list[2*n+i])
w, h = curr_images[i].size
widths.append(w)
heights.append(h)
if number_of_images == 2:
if sum(widths) > sum(heights): #vertical
width = min(widths)
if widths[0] == width:
heights[1] = heights[1]*widths[0]/widths[1]
widths[1] = widths[0]
else:
heights[0] = heights[0]*widths[1]/widths[0]
widths[0] = widths[1]
height = sum(heights)
curr_images[0] = curr_images[0].resize((widths[0],heights[0]))
curr_images[1] = curr_images[1].resize((widths[1],heights[1]))
canvas = PIL.Image.new('RGB', (width, height), 'white')
canvas.paste(curr_images[0], (0,0))
canvas.paste(curr_images[1], (0, heights[0]))
new_image_filename = os.path.join(new_directory, 'collage' + str(n+1) + '.png')
canvas.save(new_image_filename)
print n
else: #horizontal
pass
# Save the altered image, suing PNG to retain transparency
|
C++
|
UTF-8
| 1,274 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
//////////////////////////////////////////////////////////////////////////
#include "Math/BitManipulation.hpp"
#include <gtest/gtest.h>
TEST(Math, Bits_SplitByOne_Limits)
{
using namespace CPF::Math;
uint32_t maxBit32 = uint32_t(1) << 15;
uint32_t maxBit64 = uint32_t(1) << 31;
// Zero
EXPECT_EQ(0, SplitByOne32(0));
EXPECT_EQ(0, SplitByOne64(0));
// Epsilon
EXPECT_EQ(1, SplitByOne32(1));
EXPECT_EQ(1, SplitByOne64(1));
// Max bit
EXPECT_EQ(0x40000000, SplitByOne32(maxBit32));
EXPECT_EQ(0x4000000000000000, SplitByOne64(maxBit64));
// Max value
EXPECT_EQ(0x55555555, SplitByOne32(maxBit32 + (maxBit32 - 1)));
EXPECT_EQ(0x5555555555555555, SplitByOne64(maxBit64 + (maxBit64 - 1)));
}
TEST(Math, Bits_SplitByTwo_Limits)
{
using namespace CPF::Math;
uint32_t maxBit32 = uint32_t(1) << 9;
uint32_t maxBit64 = uint32_t(1) << 20;
// Zero
EXPECT_EQ(0, SplitByTwo32(0));
EXPECT_EQ(0, SplitByTwo64(0));
// Epsilon
EXPECT_EQ(1, SplitByTwo32(1));
EXPECT_EQ(1, SplitByTwo64(1));
// Max bit
EXPECT_EQ(0x08000000, SplitByTwo32(maxBit32));
EXPECT_EQ(0x1000000000000000, SplitByTwo64(maxBit64));
// Max value
EXPECT_EQ(0x09249249, SplitByTwo32(maxBit32 + (maxBit32 - 1)));
EXPECT_EQ(0x1249249249249249, SplitByTwo64(maxBit64 + (maxBit64 - 1)));
}
|
C
|
UTF-8
| 302 | 2.515625 | 3 |
[] |
no_license
|
#ifndef HEADER
#define HEADER
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_PASS_LEN 20
//Structs
typedef struct user {
char name[MAX_NAME_LEN + 1];
char password[MAX_PASS_LEN + 1];
int num_articles_written;
struct user* next;
} User;
#endif
|
Python
|
UTF-8
| 232 | 2.65625 | 3 |
[] |
no_license
|
import random
class Person(object):
def __init__(self, is_vaccinated, is_dead, is_infected):
self._id = 0
self.is_vaccinated = is_vaccinated
self.is_dead = is_dead
self.is_infected = is_infected
|
SQL
|
UTF-8
| 141 | 2.921875 | 3 |
[] |
no_license
|
SELECT e1.first_name
FROM employees e1
WHERE
(
SELECT COUNT(*)
FROM employees e2
WHERE e2.first_name <= e1.first_name
)
% 2 = 1;
|
Java
|
UTF-8
| 2,461 | 3.671875 | 4 |
[] |
no_license
|
//*******************************************************************
//StoryNode.java @author Jane Abernathy
//CS230 Final Project Voyage Through Time
//
//Represents a node in the graph of the story. Stores the name of the
//node, descriptive text for the game user to read, point value to add
//to score, an importance boolean, and the name of an image to
//display on the GUI.
//
//Primary Coder: Jane
//*******************************************************************
public class StoryNode{
//Instance Variables
public String name;
public String description;
public int value;
public boolean isImportant;
public String image;
/**
* Constructor, sets the name, description, value, isImportant boolean, and image
* to be the given values
*/
public StoryNode (String n,String d, int v, boolean i, String im){
name = n;
description = d;
value = v;
isImportant = i;
image = im;
}
/**
* Returns the name of the node, String
*
* @return name
*/
public String getName()
{
return name;
}
/**
* Returns the description String
*
* @return description
*/
public String getDescription()
{
return description;
}
/**
* Returns the value int
*
* @return value
*/
public int getValue()
{
return value;
}
/**
* Returns the importance boolean
*
* @return isImprtant
*/
public boolean getImportance()
{
return isImportant;
}
/**
* Returns the image String
*
* @return image
*/
public String getImage()
{
return image;
}
/**
* Returns a string reresentation of the node
*
* @return string representation
*/
public String toString(){
return "The node name is " + name + "\nThe node descrition is " + description +
"\nThe value is " +value+ "\nThe node imprtance is " + isImportant +
"\nThe node image is "+ image;
}
// public static void main(String[] args) {
// StoryNode one = new StoryNode("Enter the building", "You walk into the saloon and see lots of stuff", 0, false, "oldWest");
// //System.out.println(one);
// System.out.println(one.getName());
// System.out.println(one.getDescription());
// System.out.println(one.getValue());
// System.out.println(one.getImportance());
// System.out.println(one.getImage());
// }
}
|
C
|
UTF-8
| 1,044 | 3.1875 | 3 |
[] |
no_license
|
/* Cpt S 483, Introduction to Parallel Computing
* School of Electrical Engineering and Computer Science
*
* Example code
* Send receive test:
* implement the ring permutation (rank i sends to rank i-1 and receives from rank i+1)
* */
#include <stdio.h>
#include <mpi.h>
#include <assert.h>
int main(int argc,char *argv[])
{
int rank,p;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&p);
//printf("my rank=%d\n",rank);
// printf("Rank=%d: number of processes =%d\n",rank,p);
// post send first and then recv.
int x = rank;
int dest = rank-1;
if(rank==0) dest=p-1;
MPI_Send(&x,1,MPI_INT,dest,0,MPI_COMM_WORLD);
printf("Rank=%d: sent message %d to rank %d\n", rank,x,dest);
fflush(stdout);
int y=0;
MPI_Status status;
int src = rank+1;
if(rank==(p-1)) src = 0;
MPI_Recv(&y,1,MPI_INT,src,MPI_ANY_TAG,MPI_COMM_WORLD,&status);
printf("Rank=%d: received message %d from rank %d\n",rank,y,status.MPI_SOURCE);
fflush(stdout);
MPI_Finalize();
}
|
PHP
|
UTF-8
| 856 | 2.796875 | 3 |
[] |
no_license
|
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class KeysMatchFields implements Rule
{
private $model;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct($model)
{
$this->model = $model;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$keys = array_keys(json_decode($value, true));
$diff = array_diff($keys, $this->model->getFillable());
return !count($diff);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The array keys do not match the database fields.';
}
}
|
Java
|
UTF-8
| 2,427 | 2.109375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.didiglobal.turbo.engine.dao.mapper;
import com.didiglobal.turbo.engine.common.FlowDeploymentStatus;
import com.didiglobal.turbo.engine.entity.FlowDeploymentPO;
import com.didiglobal.turbo.engine.runner.BaseTest;
import com.didiglobal.turbo.engine.util.EntityBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class FlowDeploymentMapperTest extends BaseTest {
@Autowired
private FlowDeploymentMapper flowDeploymentMapper;
@Test
public void insert() {
FlowDeploymentPO flowDeploymentPO = EntityBuilder.buildFlowDeploymentPO();
flowDeploymentPO.setFlowDeployId("testFlowDeployId_" + System.currentTimeMillis());
int result = flowDeploymentMapper.insert(flowDeploymentPO);
Assert.assertTrue(result == 1);
}
@Test
public void selectByDeployId() {
FlowDeploymentPO flowDeploymentPO = EntityBuilder.buildFlowDeploymentPO();
flowDeploymentPO.setStatus(FlowDeploymentStatus.DEPLOYED);
flowDeploymentPO.setFlowDeployId("testFlowDeployId_" + System.currentTimeMillis());
flowDeploymentMapper.insert(flowDeploymentPO);
String flowDeployId = flowDeploymentPO.getFlowDeployId();
flowDeploymentPO = flowDeploymentMapper.selectByDeployId(flowDeployId);
Assert.assertTrue(flowDeployId.equals(flowDeploymentPO.getFlowDeployId()));
}
@Test
public void selectByModuleId() {
FlowDeploymentPO flowDeploymentPO = EntityBuilder.buildFlowDeploymentPO();
flowDeploymentPO.setStatus(FlowDeploymentStatus.DEPLOYED);
flowDeploymentPO.setFlowDeployId("testFlowDeployId_" + System.currentTimeMillis());
flowDeploymentMapper.insert(flowDeploymentPO);
FlowDeploymentPO flowDeploymentPONew = EntityBuilder.buildFlowDeploymentPO();
String flowModuleId1 = flowDeploymentPO.getFlowModuleId();
flowDeploymentPONew.setFlowModuleId(flowModuleId1);
flowDeploymentPONew.setStatus(FlowDeploymentStatus.DEPLOYED);
flowDeploymentPO.setFlowDeployId("testFlowDeployId_" + System.currentTimeMillis());
flowDeploymentMapper.insert(flowDeploymentPONew);
FlowDeploymentPO flowDeploymentPORes = flowDeploymentMapper.selectByModuleId(flowModuleId1);
Assert.assertTrue(flowDeploymentPONew.getFlowDeployId().equals(flowDeploymentPORes.getFlowDeployId()));
}
}
|
Python
|
UTF-8
| 16,036 | 2.65625 | 3 |
[] |
no_license
|
# supposed to handle passing "str | list" type-hinting to get_stat()
# but breaks print(f'string') because python 2.7? don't understand that
# from __future__ import annotations
import doctest
import logging
# https://inventwithpython.com/blog/2014/12/02/why-is-object-oriented-programming-useful-with-a-role-playing-game-example/
# http://pythonfiddle.com/text-based-rpg-code-python/
class Player(object):
"""
Attributes, flags and other stuff about players.
"""
"""
There should be methods here for Inventory:
Inventory.item_held(item): check player/ally inventory, return True or False
(is it important to know whether the player or ally is carrying an item?)
maybe return Player or Ally object if they hold it, or None if no-one holds it
"""
# def __init__(self, connection_id=None, name=None, gender=None, stats=None,
# flags=None, silver=None, client=None, age=None, birthday=None,
# guild=None, char_class=None, race=None, hit_points=None,
# shield=None, armor=None, experience=None):
def __init__(self, connection_id, name, gender, stats,
flags, silver, client, age, birthday,
guild, char_class, race, hit_points,
shield, armor, experience):
"""this code is called when creating a new character"""
# specifying e.g., 'hit_points=None' makes it a required parameter
# FIXME: probably just forget this, net_server.py handles connected_users(set)
# connection_id: list of CommodoreServer IDs: {'connection_id': id, 'name': 'name'}
# for k in len(connection_ids):
# if connection_id in connection_ids[1][k]:
# logging.info(f'Player.__init__: duplicate {connection_id['id']} assigned to '
# f'{connection_ids[1][connection_id]}')
# return
# temp = {self.name, connection_id}
# connection_ids.append({'name': name, connection_id})
# logging.info(f'Player.__init__: Connections: {len(connection_ids)}, {connection_ids}')
# self.connection_id = connection_id # 'id' shadows built-in name
self.connection_id = connection_id # keep this until I figure out where it is in net_server.py
self.name = name
self.gender = gender
# creates a new stats dict for each Player, zero all stats:
# set with Player.set_stat('xyz', val)
self.stats = stats
# if self.stats is not None:
# self.stats = stats
# else:
# self.stats = {'chr': 0, 'con': 0, 'dex': 0, 'int': 0, 'str': 0, 'wis': 0, 'egy': 0}
print(f"stats: {self.stats}")
# flags:
if self.flags is not None:
self.flags = flags
else:
self.flags = {'room_descriptions': bool, 'autoduel': bool, 'hourglass': bool,
'expert': bool, 'more_prompt': bool, 'architect': bool,
# TODO: orator_mode: bool # define orator_mode more succinctly
'hungry': bool, 'thirsty': bool, 'diseased': bool, 'poisoned': bool,
'debug': bool, 'dungeon_master': bool
}
logging.info(f'{self.flags=}')
# creates a new silver dict for each Player:
# in_bank may be cleared on character death (TODO: look in TLOS source)
# in_bar should be preserved after character's death (TODO: same)
# use Player.set_silver("kind", value)
if self.silver is not None:
self.silver = silver
else:
self.silver = {"in_hand": 0, "in_bank": 0, "in_bar": 0}
# logging.info(f'Player.__init__: Silver in hand: {self.silver["in_hand"]}')
# client settings - set up some defaults
if self.client is not None:
self.client = client
else:
self.client = {'name': None, 'rows': None, 'columns': 80, 'translation': None,
# colors for [bracket reader] text highlighting on C64/128:
'text': None, 'highlight': None, 'background': None, 'border': None}
self.age = age
self.birthday = birthday # tuple: (month, day, year)
"""
proposed stats:
some (not all) other stats, still collecting them:
times_played: int
last_play_date: tuple # (month, day, year) like birthday
special_items[
SCRAP OF PAPER is randomly placed on level 1 with a random elevator combination
BOAT # does not actually need to be carried around in inventory, I don't suppose, just a flag?
combinations{'elevator', 'locker', 'castle'} # tuple? combo is 3 digits: (nn, nn, nn)
]
map_level: int # cl
map_room: int # cr
moves_made: int
"""
self.guild = guild # [civilian | fist | sword | claw | outlaw]
# 1 2 3 4 5 6 7 8 9
self.char_class = char_class # Wizard Druid Fighter Paladin Ranger Thief Archer Assassin Knight
self.race = race # Human Ogre Pixie Elf Hobbit Gnome Dwarf Orc Half-Elf
self.hit_points = hit_points
self.shield = shield
self.armor = armor
self.experience = experience
"""
combat:
honor: int
weapon_percentage{'weapon': percentage [, ...]}
weapon_ammunition{'weapon': ammo_count [, ...]}
bad_hombre_rating is calculated from stats, not stored in player log
once_per_day[] flags: # things you can only do once per day (file_formats.txt)
'pr' has PRAYed once
'pr2' can PRAY twice per day (only if player class is Druid)
"""
def __str__(self):
"""print formatted Player object (double-quoted since ' in string)"""
_ = f"Name: {self.name}\t\t"
f"Age: {'Undetermined' if self.age == 0 else '{self.age}'}"
f'\tBirthday: {self.birthday[0]}/{self.birthday[1]}/{self.birthday[2]}\n'
f"Silver: In hand: {self.silver['in_hand']}\n"
f'Guild: {self.guild}\n'
return _
def set_stat(self, stat: str, adj: int):
"""
:param stat: statistic in stats{} dict to adjust
:param adj: adjustment (+x or -x)
:return: stat, maybe also 'success': True if 0 > stat > <limit>
TODO: example for doctest:
>>> Rulan.set_stat['str': -5] # decrement Rulan's strength by 5
"""
if stat not in self.stats:
logging.warning(f"Stat {stat} doesn't exist.")
# raise ValueError?
return
# self.stats = {'con': 0, 'dex': 0, 'ego': 0, 'int': 0, 'str': 0, 'wis': 0}
# adjust stat by <adjustment>:
before = self.stats[stat]
after = before + adj
logging.info(f"set_stat: Before: {stat=} {before=} {adj=}")
if not self.flags['expert_mode']:
descriptive = zip(['chr', 'con', 'dex', 'int', 'str', 'wis', 'egy'],
['influential', 'hearty', 'agile', 'intelligent',
'strong', 'wise', 'energetic'])
# TODO: jwhoag suggested adding 'confidence' -> 'brave' -- good idea,
# not sure where it can be added yet.
# returns ('con', 'hearty') -- etc.
for n in descriptive:
# FIXME: I don't know of a more efficient way to refer to a subscript in this case.
# This may be good enough, it's a small loop
if n[0] == stat:
print(f"You feel {'more' if after > before else 'less'} {n[1]}.")
logging.info(f"set_stat: After: {stat=} {after=}")
self.stats[stat] = after
def get_stat(self, stat):
"""
if 'stat' is str: return value of single stat as str: 'stat'
TODO: if 'stat' is list: sum up contents of list: ['str', 'wis', 'int']...
-- avoids multiple function calls
"""
if type(stat) is list:
_sum = 0 # 'sum' shadows built-in type
for k in stat:
if stat not in self.stats:
logging.warning(f"get_stat: Stat {stat} doesn't exist.")
# TODO: raise ValueError?
return
_sum += self.stats[k]
logging.info(f'get_stat[list]: {stat=} {_sum=}')
return _sum
# otherwise, get just a single stat:
if stat not in self.stats:
logging.warning(f"get_stat: Stat {stat} doesn't exist.")
# TODO: raise ValueError?
return
return self.stats[stat]
def print_stat(self, stat: str):
"""
print player stat in title case: '<Stat>: <value>'
for doctest
FIXME: eventually. can't figure out how to test functions which have a prerequisite function
>>> Rulan = Player(name="Rulan",
connection_id=1,
client={'name': 'Commodore 64'},
flags={'dungeon_master': True, 'debug': True, 'expert_mode': False}
)
>>> Rulan.print_stat('int')
Int: 5
"""
if stat not in self.stats:
logging.warning(f"get_stat: Stat {stat} doesn't exist.")
# TODO: raise ValueError?
return
# return e.g., "Int: 4"
return f'{stat.title()}: {self.stats[stat]}'
def print_all_stats(self):
"""
print all player stats in title case: '<Stat>: <value>'
for doctest eventually
FIXME: can't figure out how to test routines which have other function call prerequisites
>>> Rulan = Player(name="Rulan",
connection_id=1,
client={'name': 'Commodore 64'},
flags={'dungeon_master': True, 'debug': True, 'expert_mode': False}
)
>>> Rulan.print_all_stats()
Chr: 8 Int: 5 Egy: 3
Con: 15 Str: 8
Dex: 3 Wis: 3
"""
for stat in ['chr', 'int', 'egy']:
print(f'{stat.title()}: {self.stats[stat]:2} ', end='')
print()
for stat in ['con', 'str']:
print(f'{stat.title()}: {self.stats[stat]:2} ', end='')
print()
for stat in ['dex', 'wis']:
print(f'{stat.title()}: {self.stats[stat]:2} ', end='')
print()
def get_silver(self, kind):
"""
get and return amount of silver player has
'kind': 'in_hand', 'in_bank', or 'in_bar'
"""
if kind not in self.silver:
logging.info(f"get_silver: Bad type '{kind}'.")
return
logging.info(f'get_silver: {self.silver[kind]}')
return self.silver[kind]
def set_silver(self, kind: str, adj: int):
"""
:param kind: 'in_hand', 'in_bank' or 'in_bar'
:param adj: amount to add (<adj>) or subtract (-<adj>)
:return: None
"""
before = self.silver[kind]
# TODO: check for negative amount
after = before + adj
if after < 0:
logging.info(f'set_silver: {after=}, negative amount not allowed')
return
self.silver[kind] = after
def transfer_money(p1: Player, p2: Player, kind: str, adj: int):
"""
:param p1: Player to transfer <adj> gold to
:param p2: Player to transfer <adj> gold from
:param kind: classification ('in_hand' most likely)
:param adj: amount to transfer
:return: none
"""
# as suggested by Shaia:
# (will be useful for future bank, or future expansion: gold transfer spell?)
if p2.silver[kind] >= adj:
p1.set_silver(kind, adj)
p2.set_silver(kind, -adj)
logging.info(f'transfer_money: {p2.name} {adj} {kind} -> {p1.name}: {p1.silver[kind]}')
print(f'{p2.name} transferred {adj} silver {kind} to {p1.name}.')
print(f'{p1.name} now has {p1.silver[kind]}.')
else:
print(f"{p2.name} doesn't have {adj} silver to give.")
class Ally(object):
def __init__(self):
"""
Ally['name'][stat], position: str
where (as in TLOS): empty=0, lurking=1, point=2, flank=2, rear=3,
(guard=4?), unconscious=5 (in python I will spell out positions as strings)
abilities[
'tracking': int # number of rooms away an ally can detect a target
# TLOS: distance between tracker and target determined track strength.
# target's last play date delta compared to date.today determines
# "strength" of tracks: 1-3 days: very fresh, >3 days: weak (?)
# https://docs.python.org/3/library/datetime.html
# TODO: look at Skip's branch on GitHub, it has more TRACKing stuff:
# https://github.com/Pinacolada64/TADA-old/blob/4c24c069139a495f97b2964d54c374b957c9eeab/SPUR-code/SPUR.MISC9.S
'ayf': int # ally has a 1-ayf% chance of randomly finding sack of gold/diamond/etc.
'alignment': str # in TLOS: '(' good, ')' evil
]
flags[ # | = TLOS ally string postfix, then:
'elite': bool # !
'mount': bool # =
'body_build': bool # #nn <nn=1...25?> Not clear what this is for, Str improvement?
# TODO: find ally guild code
]
silver: int
"""
pass
class Horse(object):
def __init__(self):
"""
horse[name: str, have_horse: bool, armor: int, saddlebags: bool,
saddle: bool, armor: int, training: bool (I think), mounted_on_horse: bool,
lasso: bool
inventory[] # mash, hay, oats, apples, sugar cubes
]
"""
pass
if __name__ == '__main__':
# import logging
logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] | %(message)s')
import doctest
# doctest.testmod(verbose=True)
# connection_ids = [] # initialize empty list for logging connection_id's
Rulan = Player()
Rulan.name = "Rulan"
Rulan.connection_id = 1
Rulan.client = {'name': 'Commodore 128', 'columns': 80}
Rulan.flags = {'dungeon_master': True, 'debug': True, 'expert_mode': False}
print(Rulan)
Rulan.set_stat('int', 5)
print(f"{Rulan.print_stat('int')}") # show "Int: 5", this passes
Rulan.set_stat('int', 4) # add to Rulan's Intelligence of 5, total 9
print(f"{Rulan.print_stat('int')}") # show "Int: 9", this passes
# when print_stat returned None, had to do this:
# print(f'Rulan ...... ', end='')
# Rulan.print_stat('int') # should print 'Rulan ...... Int: 9'
Rulan.set_silver(kind='in_hand', adj=100)
Rulan.set_silver(kind='in_bank', adj=200)
Rulan.set_silver(kind='in_bar', adj=300)
print(f"Silver in bank: {Rulan.get_silver('in_bank')}") # should print 200, this passes
Rulan.print_all_stats()
Shaia = Player(name="Shaia",
connection_id=2)
Shaia.client = {'name': 'TADA', 'columns': 80, 'rows': 25}
Shaia.flags = {'expert_mode': True, 'debug': True}
Shaia.set_stat(stat='int', adj=18)
print(f"Shaia ...... {Shaia.print_stat('int')}") # should print 'Shaia ...... Int: 18': passes
# when print_stat returned None, did this:
# print(f'Shaia ...... ', end='')
# Shaia.print_stat('int') # should print 'Shaia ...... Int: 18'
Shaia.set_silver(kind='in_hand', adj=10)
Shaia.set_silver(kind='in_bank', adj=200)
Shaia.set_silver(kind='in_bar', adj=300)
Shaia.print_all_stats()
transfer_money(Shaia, Rulan, kind='in_hand', adj=500) # should rightfully fail
transfer_money(Shaia, Rulan, kind='in_hand', adj=100) # this passes
|
Markdown
|
UTF-8
| 13,301 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
# Hazy
> :partly_sunny: Lazy JSON fixtures in Node
-----
Hazy aims to ease the hassle of generating, maintaining and working with fixtures by making them DRY and more expressive.
Hazy lets developers describe and generate test data in a normailzed fasion and allows for fixtures to be processed further
at run-time for increased flexibility.
### Features
* Simple syntax for supporting both normalized and random data in fixtures
* DRY, embeddable, and queryable fixtures / sub-fixtures
* Random `String`, `Number` and `Date` data via `ChanceJS`
* Lazy processing via run-time queries ([JsonPath](http://goessner.net/articles/JsonPath/))
### Design Goals
* Non-invasive (retain all involved standards, especially JSON)
* Unique and identifiable syntax
* Convention based, interpreter agnostic
* Pre-processed, but optionally evaluated at run-time
* Cleanly integrate with __all__ Node testing frameworks
### Example
Here we register a couple of JSON fixtures into what's refered to as the fixture pool:
```javascript
import hazy from 'hazy'
hazy.fixture.register('someDude', {
id : '|~misc.guid|',
name : '|~person.prefix| |~person.name|',
email : '|~web.email|',
bday : '|~person.birthday|',
ssn : '|~person.ssn| (not really)',
})
/* loads someDog.json (assumes .json extension when none is provided), containing:
{
id : '|~misc.guid|',
owner : '|*someDude|'
name : 'Dawg',
}*/
hazy.fixture.src('someDog')
const hazyDude = hazy.fixture.get('someDude')
const hazyDog = hazy.fixture.get('someDog')
```
The processed fixtures result as follows:
```javascript
// hazyDude
{
id: 'e76de72e-6010-5140-a270-da7b6b6ad2d7',
name: 'Mr. Agnes Hammond',
bday: Wed Apr 27 1994 04:05:27 GMT-0700 (Pacific Daylight Time),
ssn: '264-66-4154 (not really)'
}
// hazyDog
{
id: '427b2fa6-02f8-5be5-b3d1-cdf96f432e28',
name: 'Dawg',
owner: {
id: 'e76de72e-6010-5140-a270-da7b6b6ad2d7',
name: 'Mr. Agnes Hammond',
bday: Wed Apr 27 1994 04:05:27 GMT-0700 (Pacific Daylight Time),
ssn: '264-66-4154 (not really)'
}
}
```
### Installation
```
> npm install hazy
```
if you wish to develop:
```
> git clone http://github.com/slurmulon/hazy.git
> cd hazy
> npm link hazy
```
### Test
```
> cd hazy
```
then
```
> npm test
```
# Documentation
The following provides a high-level summary of all of Hazy's features as well as some examples and gotchas.
A notable observation is that Hazy's syntax can be expressed quite simply:
`|<operator> <expression|statement>|`
Supported operators are:
* `~` generate random data
* `*` embed fixture data from pool
* `$` query by `JsonPath` pattern and embed fixture from pool
* `@` find and embed fixture from filesystem
* `?` find and embed fixture from pool or filesystem
* `>` evaluate content as literal JavaScript
* `=` interpolate expression result
(more thorough documentation on the way)
## Randomness
Hazy sits on top of ChanceJS, a great library for generating all sorts of useful random data.
Hazy categorizes ChanceJS's generation methods for a more symantic syntax, but otherwise integration
is completely transparent.
The token for generating random data is `~`:
`|~ <class>.<type>|`
### Random Data Tokens
* `|~basic.<type>|`
supports `'bool', 'character', 'integer', 'natural', 'string'`
* `|~text.<type>|`
supports `'paragraph', 'sentence', 'syllable', 'word'`
* `|~person.<type>|`
supports `'age', 'birthday', 'cpf', 'first', 'gender', 'last', 'name', 'prefix', 'ssn', 'suffix'`
* `|~mobile.<type>|`
supports `'android_id', 'apple_token', 'bb_pin', 'wp7_anid', 'wp8_anid2'`
* `|~web.<type>|`
supports `'color', 'domain', 'email', 'fbid', 'google_analytics', 'hashtag', 'ip', 'ipv6', 'klout', 'tld', 'twitter', 'url'`
* `|~geo.<type>|`
supports `'address', 'altitude', 'areacode', 'city', 'coordinates', 'country', 'depth', 'geohash', 'latitude', 'longitude', 'phone', 'postal', 'province', 'state', 'street', 'zip'`
* `|~time.<type>|`
supports `'ampm', 'date', 'hammertime', 'hour', 'millisecond', 'minute', 'month', 'second', 'timestamp', 'year'`
* `|~misc.<type>|`
supports `'guid', 'hash', 'hidden', 'n', 'normal', 'radio', 'rpg', 'tv', 'unique', 'weighted'`
## Embedding
Hazy supports referencing and embedding other JSON fixtures (or really any value) present in the fixture pool using the `*` operator.
`|* <fixture-pool-key>|`
The `someDog` example above already shows how this is used:
```javascript
hazy.fixture.register('someDog', {
id : '|~misc.guid|',
owner : '|*someDude|'
name : 'Dawg',
})
```
the above will resolve to the following provided that `someDude` is in the fixture pool:
```javascript
{
id: '427b2fa6-02f8-5be5-b3d1-cdf96f432e28',
name: 'Dawg',
owner: {
id: 'e76de72e-6010-5140-a270-da7b6b6ad2d7',
name: 'Mr. Agnes Hammond',
bday: Wed Apr 27 1994 04:05:27 GMT-0700 (Pacific Daylight Time),
ssn: '264-66-4154 (not really)'
}
}
```
Hazy also supports more advanced ways of embedding fixtures using queries, but more on that will follow
in the next section.
## Queries
Hazy utilizes `JsonPath` for defining functionality to pre-processed fixtures in a query-like fasion.
Details on `JsonPath` can be found at http://goessner.net/articles/JsonPath/. There are many ways in which
JSON objects can be queried using this flexible technique.
A primary goal of Hazy is to give developers both fine grained and generalized control over the data and
functionality relevant to their fixtures.
Take our `someDog` fixture, for example:
```javascript
{
id: '427b2fa6-02f8-5be5-b3d1-cdf96f432e28',
name: 'Dawg',
owner: {
id: 'e76de72e-6010-5140-a270-da7b6b6ad2d7',
name: 'Mr. Agnes Hammond',
bday: Wed Apr 27 1994 04:05:27 GMT-0700 (Pacific Daylight Time),
ssn: '264-66-4154 (not really)'
}
}
```
We can obtain the `id` of the dog's owner with the following query:
`$.owner.id`
After the fixture has been queried, this will result with:
`e76de72e-6010-5140-a270-da7b6b6ad2d7`
### Embedded Queries
`JsonPath` expressions that match against the fixture pool can be specified with the query operator `$`.
The results of the expression and will be embedded into the fixture upon processing. The syntax for embedded queries is:
`|$ <jsonpath-expression>|`
where `<jsonpath-expression>` is a valid [JsonPath](http://goessner.net/articles/JsonPath/) expression (minus the leading '$')
> **Note:** Embedded queries (i.e. those defined outside of the lazy matcher pool `hazy.matcher`, particularly in source *.json files/data) are **not** and cannot be lazily evaluated because:
>
> 1. Very high risk of cyclic dependencies and infinite recursion (e.g., some fixtures may need to be lazily evaluated if they have not already been, potentially triggering an endless cycle)
> 2. Applying queries to pre-processed fixtures allows for cleaner queries (since you can query against Hazy tags) and provides consistent results.
> If queries were applied to post-processed fixtures, they would be bottlenecked to only working with properties since the processed random values
> are obviously inconsistent.
>
> See the section on [Lazy Query Matchers](#lazy-query-matchers) for a pragmatic and idiomatic solution to the issue.
Use of the operator is straight forward:
```javascript
hazy.fixture.register('someShark', {
id : '|~misc.guid|',
name : 'Tiger Shark',
ate : '|$.id|', // queries pool for any fixture with an "id" property at the highest level
})
```
this will result with something like:
```javascript
{
id: '64af61f8-daa8-5959-8be4-bdd536ecc5bd',
name: 'Tiger Shark',
ate:
[ {
id: 'e76de72e-6010-5140-a270-da7b6b6ad2d7',
name: 'Mr. Agnes Hammond',
bday: Wed Apr 27 1994 04:05:27 GMT-0700 (Pacific Daylight Time),
ssn: '264-66-4154 (not really)'
},
{
id: '427b2fa6-02f8-5be5-b3d1-cdf96f432e28',
name: 'Dawg',
owner: {
id: 'e76de72e-6010-5140-a270-da7b6b6ad2d7',
name: 'Mr. Agnes Hammond',
bday: Wed Apr 27 1994 04:05:27 GMT-0700 (Pacific Daylight Time),
ssn: '264-66-4154 (not really)'
}
}
]
}
```
> **Note:** The query operator currently always returns an `Array`. I consider this a limitation because it makes it difficult to integrate queries with other expressions. I hope to address this issue soon.
The only known limitation on the nesting depth of embedded fixtures is the stack size of the process. I have not pushed this limitation very far at all, but if any
issues are encountered then please open an issue on Github.
### Lazy Query Matchers
With Hazy we can leverage this powerful query mechanism in any Node environment to provide test-specific functionality to your fixtures.
This is achieved by monkey-patching fixtures in the pool that match a specific `JsonPath` pattern.
For example, if we wanted to query our fixture pool for any fixture with an `owner` object containing an `id` property
and then update those fixtures with new `bark()` functionality, then we would use the following:
```javascript
hazy.matcher.config({
path : '$.owner.id',
handle : (fixture, matches, pattern) => {
// return the fixture after mutating it (if you so desire)
return Object.assign({
hasOwner : true,
bark : () => {
console.log('woof woof, my owner is ', matches[0])
}
}, fixture)
}
})
hazy.fixture.register('someDogWithOwner', {
id : '|~misc.guid|',
owner : '|*someDude|'
name : 'Happy Dog',
})
hazy.fixture.register('someDogWithoutOwner', {
id : '|~misc.guid|',
name : 'Lonely Dog'
})
const happyDog = hazy.fixture.get('someDogWithOwner')
const lonelyDog = hazy.fixture.get('someDogWithoutOwner')
```
Since the `matcher` only applies to fixtures with an owner id, only `happyDog` will contain the `hasOwner` property and
a `bark` method:
```javascript
happyDog.bark()
```
> `woof woof, my owner is e76de72e-6010-5140-a270-da7b6b6ad2d7`
```javascript
lonelyDog.bark()
```
> `Error: undefined is not a method`
-----
This feature can also be combined with `hazy.fork()` so that query matchers can be scoped to a particular state of the fixture pool.
Any query matcher defined at a higher scope can be easily and safely overwritten in a Hazy fork:
```javascript
hazy.matcher.config({
path : '$.owner.id',
handle : (fixture, matches, pattern) => {
// return the fixture after mutating it (if you so desire)
return Object.assign({
hasOwner : true,
bark : () => {
console.log('woof woof, my owner is ', matches[0])
}
}, fixture)
}
})
hazy.fixture.register('someDogWithOwner', {
id : '|~misc.guid|',
owner : '|*someDude|'
name : 'Happy Dog',
})
const happyDog = hazy.fixture.get('someDogWithOwner')
let sleepyDog = null
function forkTest() {
const newHazy = hazy.fork()
newHazy.matcher.config({
path : '$.owner.id',
handle : (fixture) => {
fixture.bark = () => {
console.log('zzzz, too tired')
}
return fixture
}
})
sleepyDog = newHazy.fixture.get('someDogWithOwner')
}
forkTest()
```
and now...
```javascript
happyDog.bark()
```
> still prints `woof woof, my owner is e76de72e-6010-5140-a270-da7b6b6ad2d7`, while
```javascript
sleepyDog.bark()
```
> now prints `zzzz, too tired`, overriding the matcher defined at a higher context level (AKA `happyDog`'s) safely
Lastly, you have some control over when evaluation occurs:
* `hazy.fixture.get` will apply any pattern-matched functionality to the relevant fixture **each time** it is called.
* `hazy.fixture.lazyGet` applies any pattern-matched functionality to the relevant fixture, but only does so **once (memoized)**.
Both implementations are technically lazy since their evaluation is deferred until the last minute, but `lazyGet` is even more so since it only runs once.
## Scripting
Hazy also evaluates text through a `lodash` interpolation template. This enables you
to include JavaScript expressions in your fixtures.
This is an experimental feature, so use it with caution.
### Interpolate
Insert the result of an expression. The fixture pool and random data factories are all available as variables.
Specified with the `=` operator.
```javascript
hazy.lang.process('{"random_point": "|= random.basic.integer({min: 0, max: 100})|"}')
```
As a convenience, ES6's interpolation syntax can also be used:
```javascript
hazy.lang.process('{"random_point": "${random.basic.integer({min: 0, max: 100})}"}')
```
### Evaluate
Evaluates content as JavaScript, allowing you to perform `if` statements, loops, etc.
Specified with the `>` operator.
```javascript
hazy.lang.process('{"random_point": |> if (foo) {| |=random.basic.integer({min: 0, max: 100})| |> }|}', {foo: true})
```
## TODO
- [ ] Silent/collapsed whitespace override (useful for loading fixtures into pool without having to print the contents)
- [ ] Retain indentation of parent line
- [ ] Cache last randomly generated result and allow user to easily re-use the latest value (allows fixtures to be consistent with each other when needed)
- [ ] Array literal operator
- [ ] Seeds for random data
- [ ] Memoized/scoped random data
- [ ] Support JSON Pointer
- [ ] Support `json-rel`
- [ ] Remote fixtures via `http`
- [ ] CLI
|
Markdown
|
UTF-8
| 459 | 2.546875 | 3 |
[] |
no_license
|
# Predictive-Cricket
<ul>
<li>This is a console based project.</li>
<li>In this project your predicted number is matched with computer generated number,run depends upon how close your prediction was.</li>
<li>I have used only random module to generate random numbers</li>
<li>Not only this but It is having dunamic commentry which changes each time upon same shot.</li>
<li>Last but not least, Please don't delete any file for errorless execution.</li>
</ul>
|
Java
|
UTF-8
| 12,080 | 1.773438 | 2 |
[] |
no_license
|
package com.example.es_demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.es_demo.model.MovieModel;
import org.apache.http.HttpEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.ml.job.results.Bucket;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.json.JsonbTester;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class DocumentsQueryTests {
@Resource
private RestHighLevelClient client;
@Test
void contextLoads() {
}
/**
* ๆฅ่ฏขๆๆ
*
* @throws Exception
*/
@Test
public void searchAll() throws Exception {
QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
System.out.println(searchByQueryBuilder(client, queryBuilder));
}
/**
* ๅน้
ๆฅ่ฏข
*/
@Test
public void matchQuery() {
try {
QueryBuilder queryBuilder = QueryBuilders.matchQuery("director", "James-Cameron");
System.out.println(searchByQueryBuilder(client, queryBuilder));
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* ๅคไธชๅน้
ๆฅ่ฏข
*/
@Test
public void multiMatchQuery() {
try {
//ๆฅ่ฏข contry typeๅญๆฎต้ฝๅ
ๅซce ็ๆฐๆฎ
QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("romance", "counrty", "type").operator(Operator.OR);
System.out.println(searchByQueryBuilder(client, queryBuilder));
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* ๅญๆฎตๅน้
ๆฅ่ฏข
*/
@Test
public void termQuery() {
try {
//ๆฅ่ฏข type ไธบ "romance"ๆ"action" ็ๆๆๆฐๆฎ
QueryBuilder queryBuilder = QueryBuilders.termsQuery("type", "romance", "action");
System.out.println(searchByQueryBuilder(client, queryBuilder));
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* ๅธๅฐๆฅ่ฏข
*/
@Test
public void boolQuery() {
try {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
QueryBuilder queryBuilder_name = QueryBuilders.termQuery("name", "leon");
// QueryBuilder queryBuilder_type = QueryBuilders.termQuery("type", "romance");
//ๆฅ่ฏขname ไธบ "leon" ๆ่
type ไธบ "romance"็ๆฐๆฎ
// boolQueryBuilder.should(queryBuilder_name);
// boolQueryBuilder.should(queryBuilder_type);
QueryBuilder queryBuilder_type = QueryBuilders.termQuery("type", "action");
//ๆฅ่ฏขnameไธบ"leon"ๅนถไธtypeไธบ"action"็ๆฐๆฎ
// boolQueryBuilder.must(queryBuilder_name);
// boolQueryBuilder.must(queryBuilder_type);
//ๆฅ่ฏขdate>1997-01-01็ๆฐๆฎ
// RangeQueryBuilder rangeQueryBuilder =QueryBuilders.rangeQuery("date").gt("1997-01-01");
// boolQueryBuilder.must(rangeQueryBuilder);
//id่ๅดๆฅ่ฏข
int[] ids = {1, 2, 3};
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("_id", ids);
boolQueryBuilder.must(termsQueryBuilder);
System.out.println(searchByQueryBuilder(client, boolQueryBuilder));
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* String ๆ็ดข
*/
@Test
public void stringQuery() {
try {
//ๆฅ่ฏข ๅซๆ France็ๆฐๆฎ
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("France");
System.out.println(searchByQueryBuilder(client, queryBuilder));
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* ๆๅบ
*
* @throws IOException
*/
@Test
public void sort() throws IOException {
SearchRequest searchRequest = new SearchRequest("movie");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.from(0).size(10);
//่ฎพ็ฝฎไธไธชๅฏ้็่ถ
ๆถๆถ้ด๏ผ็จไบๅฏๆงๅถๆ็ดขๅ
่ฎธ็ๆถ้ด
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//ๅฐๆฐๆฎๆdateๆๅบ
FieldSortBuilder sortBuilder = SortBuilders.fieldSort("date").order(SortOrder.DESC);
searchSourceBuilder.sort(sortBuilder);
//ๆๅฎ่ฟๅๅญๆฎต
// String[] includeFields = {"name", "director"};
// String[] excludeFields = {"date"};
// searchSourceBuilder.fetchSource(includeFields, excludeFields);
//ๅฎ็ฐๅญๆฎต้ซไบฎๆพ็คบ
// HighlightBuilder highlightBuilder = new HighlightBuilder();
// HighlightBuilder.Field highlightName = new HighlightBuilder.Field("name");
// highlightBuilder.field(highlightName);
// searchSourceBuilder.highlighter(highlightBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//่ทๅ็ญ็นๆฐๆฎ
SearchHits searchHits = searchResponse.getHits();
SearchHit[] hits = searchHits.getHits();
//ๅฐ็ปๆ่ฃ
่ฟๅฏน่ฑกlistไธญ
List<MovieModel> list = new ArrayList<>();
for (SearchHit searchHit : hits) {
String sourceAsString = searchHit.getSourceAsString();
list.add(JSON.parseObject(sourceAsString, new TypeReference<MovieModel>() {
}));
}
System.out.println(list);
client.close();
}
/**
* ่ๅๆฅ่ฏข
*
* @throws IOException
*/
@Test
public void agg() throws IOException {
// SearchRequest searchRequest = new SearchRequest("movie");
SearchRequest searchRequest = new SearchRequest("people");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//ๆtypeๅ็ป
TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("by_sex").field("sex.keyword");
searchSourceBuilder.aggregation(aggregationBuilder);
//ๆฑๅนณๅๅผๅๆปๅ(ๆnameๅ็ป)
// //ๅฏนๅบ็jsonไธฒ
// String json_es = "GET people/_search\n" +
// "{\n" +
// " \"aggs\": {\n" +
// " \"by_sex\":{\n" +
// " \"terms\": {\n" +
// " \"field\": \"sex.keyword\"\n" +
// " },\n" +
// " \"aggs\": {\n" +
// " \"avg_age\": {\n" +
// " \"avg\": {\n" +
// " \"field\": \"age\"\n" +
// " }\n" +
// " },\n" +
// " \"sum_age\":{\n" +
// " \"sum\": {\n" +
// " \"field\": \"age\"\n" +
// " }\n" +
// " }\n" +
// " }\n" +
// " }\n" +
// " }\n" +
// "}";
// TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("by_sex").field("sex.keyword");
// AvgAggregationBuilder avgAggregationBuilder = AggregationBuilders.avg("avg_age").field("age");
// SumAggregationBuilder sumAggregationBuilder = AggregationBuilders.sum("sum_age").field("age");
// searchSourceBuilder.aggregation(aggregationBuilder.subAggregation(avgAggregationBuilder).subAggregation(sumAggregationBuilder));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Aggregations aggregations = searchResponse.getAggregations();
//่ทๅๆtypeๅ็ป่ๅ็ปๆ
Terms byTypeAggregation = aggregations.get("by_sex");
for (Terms.Bucket bucket : byTypeAggregation.getBuckets()) {
System.out.println("key:" + bucket.getKey());
System.out.println("docCount:" + bucket.getDocCount());
}
//่ทๅๆฑๅนณๅๅผๅๆปๅ่ๅ็ปๆ
// Aggregations aggregations = searchResponse.getAggregations();
// Terms byAgeAggregation = aggregations.get("by_sex");
// for (Terms.Bucket bucket : byAgeAggregation.getBuckets()){
// System.out.println("key:"+bucket.getKey());
// System.out.println("docCount:"+bucket.getDocCount());
// Avg avg = bucket.getAggregations().get("avg_age");
// System.out.println("avg_age:"+avg.getValue());
// Sum sum = bucket.getAggregations().get("sum_age");
// System.out.println("sum:"+sum.getValue());
// }
client.close();
}
private static List searchByQueryBuilder(RestHighLevelClient client, QueryBuilder queryBuilder) throws IOException {
//ๅๅปบmovie็ดขๅผ็ๆ็ดข่ฏทๆฑ
SearchRequest searchRequest = new SearchRequest("movie");
//ๅๅปบๆ็ดขๆๆกฃๅ
ๅฎนๅฏน่ฑก
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder);
//่ฎพ็ฝฎๆฅ่ฏข็่ตทๅง็ดขๅผไฝ็ฝฎๅๆฐ้๏ผไปฅไธ่กจ็คบไป็ฌฌ1ๆกๅผๅง๏ผๅ
ฑ่ฟๅ1000ๆกๆๆกฃๆฐๆฎ
searchSourceBuilder.from(0).size(1000);
searchRequest.source(searchSourceBuilder);
//ๆ นๆฎๆ็ดข่ฏทๆฑ่ฟๅ็ปๆ
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//่ทๅ็ญ็นๆฐๆฎ
SearchHits searchHits = searchResponse.getHits();
SearchHit[] hits = searchHits.getHits();
//ๅฐ็ปๆ่ฃ
่ฟๅฏน่ฑกlistไธญ
List<MovieModel> list = new ArrayList<>();
for (SearchHit searchHit : hits) {
String sourceAsString = searchHit.getSourceAsString();
list.add(JSON.parseObject(sourceAsString, new TypeReference<MovieModel>() {
}));
}
return list;
}
}
|
C
|
UTF-8
| 3,815 | 3.53125 | 4 |
[
"MIT",
"BSD-4-Clause-UC",
"BSD-3-Clause"
] |
permissive
|
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* ls: List directory contents. Author: Warren Toomey */
/* External variables. */
extern int optind;
extern char *optarg;
int longoutput=0; // Do a long (-l) output
int showdots=0; // Show dot files
int showinums=0; // Show i-numbers not link counts
int dircontents=1; // Show the contents of a directory
void listone(char *entry, struct stat *sbptr)
{
// Lose the year on the time string
char *timestring= ctime(&(sbptr->st_mtime));
timestring[ strlen(timestring) - 6 ]= '\0';
char ftype;
if (longoutput) {
// Print the type of entry as the first character
switch (sbptr->st_mode& S_IFMT) {
case S_IFDIR: ftype='d'; break;
case S_IFREG: ftype='-'; break;
case S_IFBLK:
case S_IFCHR: ftype='c'; break;
default: ftype=' ';
}
printf("%crwxrwxrwx %5d root root %6ld %s %s\n",
ftype, (showinums ? sbptr->st_ino : sbptr->st_nlink),
sbptr->st_size, timestring, entry);
} else {
// Just print out the name
puts(entry);
}
}
// We keep a array structure of dirents and their stat buffers
typedef struct {
struct dirent *dent;
struct stat sb;
} Namestat;
#define NLISTSIZE 200
Namestat namelist[NLISTSIZE];
// Compare two Namestat structs using the entry names
int namecmp(const void *a, const void *b)
{
Namestat *aa= (Namestat *)a;
Namestat *bb= (Namestat *)b;
return(strcmp(aa->dent->d_name, bb->dent->d_name));
}
// List the entry (if a file), or its contents (if a directory)
void listmany(char *entry)
{
DIR *D;
struct dirent *dent;
struct stat sb;
int count=0;
// Ensure the entry exists
if (stat(entry, &sb)==-1) {
printf("%s: non-existent\n", entry);
return;
}
// It's a file, just print it out
if (S_ISREG(sb.st_mode)) {
listone(entry, &sb);
return;
}
// It's a directory, deal with all of it
if (S_ISDIR(sb.st_mode)) {
// Only list the directory, not its contents
if (dircontents==0) {
listone(entry, &sb);
return;
}
// Open the directory and move into it
D= opendir(entry);
if (D==NULL) {
printf("%s: unable to opendir\n", entry);
return;
}
chdir(entry);
// Process each entry
while ((dent=readdir(D))!=NULL) {
// Skip empty directory entries
if (dent->d_name[0]=='\0') continue;
// Skip dot files
if ((showdots==0) && (dent->d_name[0]=='.')) continue;
// Get the file's stats
if (stat(dent->d_name, &sb)==-1) {
printf("%s: non-existent\n", dent->d_name);
continue;
}
// and add the file to the array
namelist[count].dent= dent;
memcpy(&(namelist[count].sb), &sb, sizeof(sb));
count++;
}
// Sort the array into name order
qsort(namelist, count, sizeof(Namestat), namecmp);
// Print each one out
for (int i=0; i < count; i++)
listone(namelist[i].dent->d_name, &(namelist[i].sb));
// Go back to where we came from. XXX: not always "..", so fix
closedir(D);
chdir("..");
}
}
int main(int argc, char *argv[])
{
int opt; /* option letter from getopt() */
/* Process any command line flags. */
while ((opt = getopt(argc, argv, "ilad")) != EOF) {
if (opt == 'l')
longoutput = 1;
if (opt == 'a')
showdots = 1;
if (opt == 'i')
showinums = 1;
if (opt == 'd')
dircontents = 0;
}
// No further arguments, list the current directory
if (optind==argc) {
listmany("."); exit(0);
}
// Otherwise, process the arguments left
for (int i=optind; i<argc; i++)
listmany(argv[i]);
exit(0);
}
|
Java
|
GB18030
| 6,169 | 2.46875 | 2 |
[] |
no_license
|
package com.zzy.threadpooldemo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.FileNameMap;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.zzy.threadpooldemo.fragment.ListFragment;
import com.zzy.threadpooldemo.util.CommonUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Environment;
import android.widget.ProgressBar;
/**
* AsyncTask ะตาปdoInBackgroundฤฒ ฺถonProgressUpdateฤฒ
* doInBackgroundุตอฃาฒonPostExecuteฤฒ
*
* @author jack
*
*/
public class MyListAsyncTask extends AsyncTask<String, Integer, String> {
private MemoCache _mc;
private FileUtil _fu;
private String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ImageLoader/";
private ProgressBar pb_progress;
private ImageView iv_image;
private TextView tv_text;
private boolean isVisible;
private String url;
public MyListAsyncTask(View view, MemoCache mc, FileUtil fu) {
_mc = mc;
_fu = fu;
HashMap<String, Object> map = (HashMap<String, Object>) view.getTag(R.string.list_item_view_tag);
tv_text = (TextView) map.get("text");
pb_progress = (ProgressBar) map.get("progess");
iv_image = (ImageView) map.get("image");
}
@Override
protected void onCancelled(String result) {
pb_progress.setVisibility(View.INVISIBLE);
pb_progress.setProgress(0);
iv_image.setImageResource(R.drawable.ic_launcher);
super.onCancelled(result);
}
@Override
protected String doInBackground(String... params) {
if (!isCancelled()) {
url = params[0];// ฺถิฑศดฮปUrlึตศซึฑิฑUI฿ณะฝะถิฑ
File myFilePath = new File(rootPath);
// ฤผ
if (!myFilePath.exists()) {
myFilePath.mkdirs();
}
File file = null;
File newFile=null;
try {
file = new File(myFilePath.getAbsoluteFile() + File.separator + url.substring(url.lastIndexOf("/")+1)+".tmp");
newFile=new File(myFilePath.getAbsoluteFile() + File.separator + url.substring(url.lastIndexOf("/")+1));
// SDะถศกอผฦฌ--2 ึนุธ
if (_fu.isFileExists(newFile)) {
_mc.putBitmap(params[0], CommonUtil.convertToBitmap(newFile.getAbsolutePath(),200,200));// ยปๆตฝฺด
return newFile.getAbsolutePath();
}else if(_fu.isFileExists(file)){
// สฑฤผึฑหณ
return "";
}
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
float length = conn.getContentLength();
if (length < 0) {
return "error";
}
// String type = conn.getContentType();
// file = new File(myFilePath.getAbsoluteFile() + File.separator
// + tv_text.getText() + "." + type.substring(type.indexOf("/")
// + 1));
/*
* ฮปิฑ---ึปุถะตวฐฯตฤฟัพสผอฃึนูปสฑึปฦถะต
* หถิฑศทฺปศกฤผึฎ
* สผึฎวฐconvertViewtextviewgetViewสฑะฑไปฏ
* ฺถะตึปะฟสผึดึฎdoInBackgroundฤผะฑไปฏสตฤผึดฮป
* --------------หถิฑัพฯณฤผัพฬถtextviewtext
*/
// if (!iv_image.getTag().toString().equals(params[0])) {
// return "";
// }
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
float total = 0f;
publishProgress(0);
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
total += len;
float percent = total * 100 / length;
publishProgress((int) percent);
}
fos.close();
bis.close();
is.close();
file.renameTo(newFile);
_mc.putBitmap(params[0], CommonUtil.convertToBitmap(newFile.getAbsolutePath(),200,200));// ุบรตอผฺดๆปบ
} catch (MalformedURLException e) {
if(file.exists()){
// ุนะณษพสฑฤผ
file.delete();
}
return "error";
} catch (IOException e) {
if(file.exists()){
// ุนะณษพสฑฤผ
file.delete();
}
return "error";
} finally {
publishProgress(101);
}
return newFile.getAbsolutePath();
}
return "";
}
@Override
protected void onPostExecute(String result) {
if (result.equals("error") && url.equals(iv_image.getTag().toString()))// ฮปิฑ
{
iv_image.setImageResource(R.drawable.ic_error);
} else if (url != null && url.equals(iv_image.getTag().toString())) // ฮปิฑ
{
iv_image.setImageBitmap(CommonUtil.convertToBitmap(result,200,200));
}
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
if (values[0] < 100 && values[0] > 0&&url.equals(iv_image.getTag().toString())) {
if (!isVisible) {
pb_progress.setVisibility(View.VISIBLE);
}
isVisible = true;
pb_progress.setProgress(values[0]);// ยฝ
} else {
if (isVisible) {
pb_progress.setVisibility(View.INVISIBLE);
}
isVisible = false;
pb_progress.setProgress(0);
}
super.onProgressUpdate(values);
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}
|
Java
|
UTF-8
| 3,239 | 2.765625 | 3 |
[] |
no_license
|
package gestionecampionati.grafica.popMenu;
import gestionecampionati.Campionato;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.text.View;
/**
* Pannello in alto della finestra di modifica dei risultati del calendario
*
* @author Enrico
*/
public class InsRisPopUp extends JPanel{
private Campionato c;
private JTable tabella;
private JLabel sq1,sq2;
private int tipo;
private JComboBox p1,p2;
/**
* Costruttore del pannello di modifica dei risultati
* @param tipo codice girone
* @param c struttura dati in cui recupare le squadre
*
* @param tabella jtable utile per recuperare la giornata
*/
public InsRisPopUp(int tipo,Campionato c, JTable tabella) {
this.c = c;
this.tabella = tabella;
this.tipo=tipo;
/** girono andata */
if(tipo == 1){
sq1 = new JLabel(c.getC().getGironeAndata().get(tabella.getSelectedRow()).getCoppia().getA().getNome());
sq2 = new JLabel(c.getC().getGironeAndata().get(tabella.getSelectedRow()).getCoppia().getB().getNome());
}
else { /** girone ritorno */
sq1 = new JLabel(c.getC().getGironeRitorno().get(tabella.getSelectedRow()).getCoppia().getA().getNome());
sq2 = new JLabel(c.getC().getGironeRitorno().get(tabella.getSelectedRow()).getCoppia().getB().getNome());
}
p1 = new JComboBox();
p2 = new JComboBox();
p1.setBackground(Color.white);
p2.setBackground(Color.white);
p1.setMaximumSize(new Dimension(50,20));
p1.setMinimumSize(new Dimension(50,20));
p2.setMaximumSize(new Dimension(50,20));
p2.setMinimumSize(new Dimension(50,20));
riempi(30);
this.setLayout(new BoxLayout(this, View.X_AXIS));
this.add(sq1);
this.add(Box.createRigidArea(new Dimension(10, 0)));
this.add(p1);
this.add(Box.createRigidArea(new Dimension(30, 0)));
this.add(sq2);
this.add(Box.createRigidArea(new Dimension(10, 0)));
this.add(p2);
}
/**
* funzione per riempire le combo box con i possibili risultati
* @param n numero max risultato
*/
public void riempi(int n){
for(int i=0; i<n; i++) {
p1.addItem(i);
p2.addItem(i);
}
}
public JComboBox getP1() {
return p1;
}
public void setP1(JComboBox p1) {
this.p1 = p1;
}
public JComboBox getP2() {
return p2;
}
public void setP2(JComboBox p2) {
this.p2 = p2;
}
@Override
public void paint(Graphics g){
super.paint(g);
}
}
|
Java
|
UTF-8
| 1,082 | 2.84375 | 3 |
[] |
no_license
|
package aodspace.ood.staff;
import java.time.LocalDate;
import aodspace.ood.staff.base.Member;
import aodspace.ood.staff.base.MemberType;
/**
* initialize percent of sales
*
* @author davit
*/
public class Sales extends Member {
private static final int SALES_SALARY_WITH_PERCENT = 1;
private static final int SALES_MAXIMUM_SALARY_PERCENTAGE = 35;
private static final double SALES_SUBORDINATE_UP_PERCENT = 0.3;
/**
* constructor for initialize Sales percent
*/
public Sales() {
type = MemberType.SALES;
annualSalaryWithPercent = SALES_SALARY_WITH_PERCENT;
maximumSalaryPercentage = SALES_MAXIMUM_SALARY_PERCENTAGE;
subordinatesWithPercent = SALES_SUBORDINATE_UP_PERCENT;
}
/*
* (non-Javadoc)
*
* @see aodspace.ood.staff.base.StaffMember#calculateSalary(java.time.LocalDate)
*/
public Double calculateSalary(LocalDate payDay) {
Double salary = super.calculateSalary(payDay);
for (Member subordinate : subordinates) {
salary += calculatePercent(subordinate.calculateSalary(payDay), subordinatesWithPercent);
}
return salary;
}
}
|
Swift
|
UTF-8
| 4,395 | 2.59375 | 3 |
[] |
no_license
|
//
// ViewController.swift
// iphoneWatch
//
// Created by Mrudula on 1/14/18.
// Copyright ยฉ 2018 Mrudula. All rights reserved.
//
import UIKit
import Foundation
import WatchConnectivity
class ViewController: UIViewController,URLSessionDelegate,WCSessionDelegate {
@available(iOS 9.3, *)
public func sessionDidDeactivate(_ session: WCSession) {
//..
}
/** Called when the session can no longer be used to modify or add any new transfers and, all interactive messages will be cancelled, but delegate callbacks for background transfers can still occur. This will happen when the selected watch is being changed. */
@available(iOS 9.3, *)
public func sessionDidBecomeInactive(_ session: WCSession) {
//..
}
/** Called when the session has completed activation. If session state is WCSessionActivationStateNotActivated there will be an error with more details. */
@available(iOS 9.3, *)
public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
//..
}
fileprivate var session: WCSession!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if WCSession.isSupported() {
session = WCSession.default
session.delegate = self
session.activate()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var loginStatus:Bool = false
@IBAction func Loginclick() {
let grantType = "client_credentials"
let clientId = "asm"
let clientSecret = "test"
var postParams = "grant_type=\(grantType)&"
postParams += "client_id=\(clientId)&"
postParams += "client_secret=\(clientSecret)"
let postData = postParams.data(using: String.Encoding.utf8)
let path = "https://50.193.56.106:9002/authorizationserver/oauth/token"
let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
request.httpMethod = "POST"
request.httpBody = postData
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue:OperationQueue.main)
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1
print("status code value",statusCode)
if(statusCode == 401){
let alertController = UIAlertController(title: "Hello", message:
"Please check client credentials!!!", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
self.loginStatus = false
}else{
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
// print(json)
let dict = json as? NSDictionary
let token = "\(dict!["access_token"]!)"
print(token);
let loginView = UIStoryboard(name: "Login", bundle: nil).instantiateViewController(withIdentifier: "LoginVC") as! LoginController
loginView.oauthToken = token
self.present(loginView, animated: false, completion: nil)
// self.sendMessage(tokenVal: token)
}
})
task.resume()
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!) )
}
}
/*typealias PairedActions = ViewController
extension PairedActions {
// Send message to Apple Watch
func sendToWatch(_ sender: AnyObject) {
sendMessage()
}
}*/
|
C#
|
UTF-8
| 1,758 | 3.734375 | 4 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoxAutoCode
{
public class PalindromeDetection
{
public static void checkPalindrone()
{
string[] array =
{
"civic",
"deified",
"deleveled",
"devoved",
"dewed",
"Pop",
"Net",
"Ah",
"sees",
"Natasha",
"Satan",
"Palindrome"
};
foreach (string value in array)
{
if(IsPalindrome(value))
{
Console.WriteLine("\n\t{0} -- {1}", value, "is a palindrome");
}
else
{
Console.WriteLine("\n\t{0}--{1}", value, "is not a palindrome");
}
}
Console.WriteLine(Environment.NewLine);
}
/// <summary>
/// Determines whether the string is a palindrome.
/// </summary>
public static bool IsPalindrome(string value)
{
int min = 0;
int max = value.Length - 1;
while (true)
{
if (min > max)
{
return true;
}
char a = value[min];
char b = value[max];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
min++;
max--;
}
}
}
}
|
PHP
|
UTF-8
| 161 | 2.578125 | 3 |
[] |
no_license
|
<?php
namespace Gametrade;
abstract class BaseList
{
abstract public function fetch_all();
abstract public function fetch_by_filter($filter_array);
}
|
C++
|
UTF-8
| 5,171 | 2.578125 | 3 |
[] |
no_license
|
#include "process_scheduler.h"
#include "os_base.h"
bool g_bTerminate = FALSE;
CProcessScheduler::CProcessScheduler()
:m_processRunning(NULL),
m_nRunForApp(0),
m_nIdle(0)
{
};
CProcessScheduler::~CProcessScheduler()
{
};
void CProcessScheduler::HeartBeat()
{
if(g_bTerminate)
return;
// OutputStatus();
ScanWaittingVector();
if(m_processRunning)
{
if(m_processRunning->complete())
{
TerminateProcess(m_processRunning);
AddCompleteProcess(m_processRunning);
ExecNextProcess();
}
else if(m_processRunning->go_waitting())
{
TerminateProcess(m_processRunning);
AddWaittingProcess(m_processRunning);
ExecNextProcess();
}
else
ExecuteProcess(m_processRunning);
}
else
ExecNextProcess();
};
void CProcessScheduler::ExecuteProcess(IProcess* pProcess)
{
if(pProcess)
{
pProcess->decreace_slice();
pProcess->start();
++m_nRunForApp;
}
};
void CProcessScheduler::TerminateProcess(IProcess* pProcess)
{
if(pProcess)
pProcess->stop();
};
void CProcessScheduler::AddReadyProcess(IProcess* pProcess)
{
if(pProcess)
m_queueReady.put(pProcess);
};
void CProcessScheduler::AddWaittingProcess(IProcess* pProcess)
{
if(pProcess)
{
pProcess->set_waitting_time(pProcess->get_last_allocated());
m_vectorWaitting.push_back(pProcess);
}
};
void CProcessScheduler::AddCompleteProcess(IProcess* pProcess)
{
if(pProcess)
{
cout<<"!!! process "<<pProcess->get_pid()<<" complete!"<<endl;
m_queueComplete.put(pProcess);
}
};
/*static*/ void APIENTRY CProcessScheduler::OSAPC(
LPVOID lpArgToCompletionRoutine,
DWORD dwTimerLowValue,
DWORD dwTimerHighValue
)
{
CProcessScheduler* pScheduler = (CProcessScheduler*)lpArgToCompletionRoutine;
if(!pScheduler)
return;
pScheduler->HeartBeat();
};
void CProcessScheduler::TerminateKernel()
{
if(m_processRunning)
{
TerminateProcess(m_processRunning);
m_processRunning = NULL;
}
g_bTerminate = TRUE;
cout<<"total run for applicate is:"<<m_nRunForApp<<endl;
cout<<"total idle is:"<<m_nIdle<<endl;
};
void CProcessScheduler::ScanWaittingVector()
{
IProcess* pTemp = NULL;
for(int i=0; i<m_vectorWaitting.size();)
{
pTemp = m_vectorWaitting[i];
if(pTemp && pTemp->waitting_complete())
{
m_queueReady.put(pTemp);
m_vectorWaitting.remove(i);
}
else
++i;
};
};
void CProcessScheduler::ExecNextProcess()
{
m_processRunning = NULL;
IProcess* pNextRunningProcess = m_queueReady.get();
if(pNextRunningProcess)
{
m_processRunning = pNextRunningProcess;
m_processRunning->allocate_timer();
ExecuteProcess(m_processRunning);
}
else
{
if(!m_queueReady.empty() || m_vectorWaitting.size()!=0)
{
++m_nIdle;
cout<<"idle"<<endl;
}
}
};
void CProcessScheduler::OutputStatus()
{
cout<<"waitting size="<<m_vectorWaitting.size()
<<" ready queue is empty="<<m_queueReady.empty()<<endl;
};
//////////////////////////////////////////////////////////////////////////
/*static*/ void COSHeartBeat::kernel_start(CProcessScheduler* pScheduler)
{
if(!s_pWaitableTimer)
{
s_pWaitableTimer = new CWaitableTimer("system kernel timer");
if(s_pWaitableTimer)
s_pWaitableTimer->SetWaitableTimer(100, CProcessScheduler::OSAPC, pScheduler);
}
while(!g_bTerminate)
{
SleepEx(INFINITE, TRUE);
}
};
/*static*/ void COSHeartBeat::kernel_end()
{
if(s_pWaitableTimer)
{
delete s_pWaitableTimer;
s_pWaitableTimer = NULL;
}
};
/*static*/ CWaitableTimer* COSHeartBeat::s_pWaitableTimer = NULL;
//////////////////////////////////////////////////////////////////////////
CWinEvent::CWinEvent(char* strName)
:m_hEvent(INVALID_HANDLE_VALUE)
{
m_hEvent = CreateEvent(NULL, TRUE, FALSE, strName);
};
CWinEvent::~CWinEvent()
{
if(m_hEvent)
{
CloseHandle(m_hEvent);
m_hEvent = INVALID_HANDLE_VALUE;
}
};
BOOL CWinEvent::SetEvent()
{
if(INVALID_HANDLE_VALUE == m_hEvent)
return FALSE;
return ::SetEvent(m_hEvent);
};
BOOL CWinEvent::ResetEvent()
{
if(INVALID_HANDLE_VALUE == m_hEvent)
return FALSE;
return ::ResetEvent(m_hEvent);
};
HANDLE CWinEvent::GetHandle()
{
return m_hEvent;
};
//////////////////////////////////////////////////////////////////////////
/*static*/ void CKernelEvent::init()
{
if(!m_pEventTerminate)
m_pEventTerminate = new CWinEvent("event terminate system");
};
/*static*/ void CKernelEvent::term()
{
if(m_pEventTerminate)
{
delete m_pEventTerminate;
m_pEventTerminate = NULL;
}
};
/*static*/ void CKernelEvent::SetTerminateEvent()
{
if(m_pEventTerminate)
m_pEventTerminate->SetEvent();
};
/*static*/ void CKernelEvent::ResetTerminateEvent()
{
if(m_pEventTerminate)
m_pEventTerminate->ResetEvent();
};
/*static*/ CWinEvent* CKernelEvent::m_pEventTerminate = NULL;
/*static*/ HANDLE CKernelEvent::GetTerminateHandle()
{
return m_pEventTerminate->GetHandle();
};
//////////////////////////////////////////////////////////////////////////
|
Java
|
UTF-8
| 1,202 | 1.992188 | 2 |
[
"Apache-2.0"
] |
permissive
|
package se.smokestack.bm;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.io.IOException;
import java.nio.file.Files;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.apache.deltaspike.core.util.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import se.bm.server.CommandWrapper;
@ApplicationScoped
public class WarFileHandler implements BMCommandHandler {
private static final Logger LOG = LogManager.getLogger();
@Inject
private IOHelper ioHelper;
@Inject
private BMConfig bmConfig;
@Override
public Command command() {
return Command.RESTART;
}
public void handle(BMCommand data) {
if (bmConfig.isShutdownWhenNewWar()) {
ioHelper.stopTomcat();
}
replaceWar();
ioHelper.startTomcat();
}
private void replaceWar() {
try {
Files.copy(bmConfig.fullWarFilePath(), bmConfig.fullWarFileTargetPath(), REPLACE_EXISTING);
} catch (IOException e) {
ExceptionUtils.throwAsRuntimeException(e);
}
}
@Override
public void handle(CommandWrapper commandWrapper) {
// TODO Auto-generated method stub
}
}
|
Python
|
UTF-8
| 1,055 | 3.078125 | 3 |
[] |
no_license
|
import copy
from version_control.State import State
from version_control.Operation import Operation
class CSVFileOpInsertRow(Operation):
def __init__(self, file_name, index, value):
self.file_name = file_name
self.index = index
self.value = value
def apply_operation(self, state):
if not self.valid_operation(state):
return None
files = copy.deepcopy(state.files)
self.apply_operation_to_file(files[self.file_name])
return State(files)
def apply_operation_to_file(self, file):
file.insert_row(self.index, self.value)
def valid_operation(self, state):
if self.file_name not in state.files:
return False
return True
def to_string(self):
return "CSVFileInsertRow\t{}\t{}\t{}".format(self.file_name, self.index, self.value)
@staticmethod
def from_string(operation_string):
operation = operation_string.split("\t")
return CSVFileOpInsertRow(operation[1], operation[2], int(operation[3]))
|
Python
|
UTF-8
| 651 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
from sympy import ( symbols, solve, diff, integrate, exp, sqrt, lambdify, Integral, ln, pprint, oo )
# Researchers have shown that the number of successive dry days that occur after a rainstorm for a particular region is a random variable that is distributed exponentially with a mean of 9 days
mu = 9
t = symbols( 't' )
a = 1/mu
pdf = a * exp( -a*t )
# What is the probability that 11 or more successive dry days occur after aโ rainstorm?
prob = integrate( pdf, ( t, 11, oo ) ).doit()
round( prob, 4 )
# What is the probability that fewer than 4 dry days occur after aโ rainstorm?
prob = integrate( pdf, ( t, 0, 2 ) ).doit()
round( prob, 4 )
|
C#
|
UTF-8
| 1,166 | 2.890625 | 3 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace TablesTest
{
class Household
{
public int Number { set; get; }
public String Name { set; get; }
static public int Inhab { set; get; }
public Household(Excel.Worksheet ws, int i)
{
int p;
Excel.Range range1, range2, range3;
range1 = ws.get_Range("A" + i);
range2 = ws.get_Range("B" + i);
range3 = ws.get_Range("C" + i);
Number = Convert.ToInt32(range1.Text.ToString());
Name = range2.Text.ToString();
if (range3.Text.ToString() == "")
{
Inhab = -1;
}
else
{
if (Int32.TryParse(range3.Text.ToString(), out p))
{
Inhab = p;
}
else
{
Inhab = 0;
}
}
}
}
}
|
Shell
|
UTF-8
| 11,598 | 3.3125 | 3 |
[] |
no_license
|
if [[ "$HOME" ]] && [[ -f ${MAS_ETC_BASH:=/etc/mastar/shell/bash}/.topparamfuncs ]] ; then
. ${MAS_ETC_BASH:=/etc/mastar/shell/bash}/.topparamfuncs
function mas_src_not_found ()
{
local errlineno=$1
shift
local errmpath=$1
shift
dbgmasp 3 "$LINENO:$FUNCNAME"
case $MAS_SCRIPTSN_ERRTYPE in
notify)
mas_get_lib_ifnot notify mas_notify
mas_notify mas_src_scripts "Error DS ($errlineno) - file/dir not found: [$errmpath] $@ pwd:`pwd`"
;;
*)
builtin echo "Error DS ($errlineno) - file absent: $@" >&2
;;
esac
}
# source file subscripts
# args
# - full path
# - cnt
# action : read all scripts from directory "$path.d"
function mas_src_literal_sub ()
{
local shs=$1
shift
local cnt=$1
shift
local shscr=$1
shift
dbgmasp 3 "$LINENO:$FUNCNAME"
mas_src_literal_script - "./$shs" "$cnt" $@
dbgmasp 3 "$LINENO:/$FUNCNAME"
}
# scripts in <directory>.d/
function mas_src_literal_subscripts ()
{
local shscr ddir cnt shs
shscr=$1
shift
cnt=$1
shift
dbgmasp 3 "$LINENO:$FUNCNAME"
ddir="${shscr}.d"
if [[ -d "$ddir" ]] ; then
mas_sourcing_start_r '@/' $ddir
dbgmasp 3 "$LINENO:-$FUNCNAME source dir @RP$ddir@"
#${MAS_ECHO_CMD:=/bin/echo} $ddir/* >&2
##### mas_echo_trace "-- Call from $ddir"
# echo "-- Call from $ddir" >&2
pushd $ddir &>/dev/null
## if [[ "$MAS_CONF_DIR_TERM_STAT" ]] ; then
## echo ">>>msls (pushd) `pwd`" >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
## echo ">>>msls (pushd) pushd $ddir" >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
## cat $prog >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
## fi
dbgmasp 3 "$LINENO:-$FUNCNAME"
for shs in * ; do
dbgmasp 3 "$LINENO:-$FUNCNAME"
if [[ -f "$shs" ]] ; then
dbgmasp 3 "$LINENO:-$FUNCNAME"
mas_src_literal_sub "$shs" $cnt "${shscr}" $@
dbgmasp 3 "$LINENO:-$FUNCNAME"
fi
# find "$ddir" -maxdepth 1 -type f >&2
# find "$ddir" -maxdepth 1 -type f -exec mas_src_literal_sub \{} $cnt >&2 \;
done
## if [[ "$MAS_CONF_DIR_TERM_STAT" ]] ; then
## echo ">>>msls (popd) `pwd`" >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
## fi
popd &>/dev/null
## if [[ "$MAS_CONF_DIR_TERM_STAT" ]] ; then
## echo ">>>msls (popd) `pwd`" >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
## fi
mas_sourcing_end_r '@/' $ddir
# else
else
dbgmasp 3 "$LINENO:-$FUNCNAME :: no subdir @RP$ddir@"
fi
dbgmasp 3 "$LINENO:/$FUNCNAME"
return 0
}
# source file
# and subscripts
# args:
# - default script (if ONE OF scripts is absent) or -
# - full path
# - cnt
function mas_src_literal_script ()
{
local cnt name result
defscript=$1
shift
name=$1
shift
cnt=$1
shift
dbgmasp 3 "$LINENO:$FUNCNAME"
result=0
mas_sourcing_start_r '@' $name
#### mas_echo_trace " Call $name"
MAS_CALL_SCRIPT_SERIAL=$(( ${MAS_CALL_SCRIPT_SERIAL:=0} + 1 ))
# echo "${MAS_CALL_SCRIPT_SERIAL:=0} Call $name" >&2
if [[ "$name" ]] ; then
if [[ -r "$name" ]] ; then
dbgmasp 1 "$LINENO:$FUNCNAME () source @RP$name@"
dbgmas 0 "source (present) @RP$name@"
if ! source $name ; then
mas_src_not_found $LINENO $name
result=1
elif ! [[ "$mas_src_scripts_no_subscript" ]] ; then
dbgmas 0 "sourced @RP$name@; do subscripts for it"
result=0
if ! mas_src_literal_subscripts "$name" "$cnt" $@ ; then
mas_src_not_found $LINENO "sub: ($name)"
result=1
fi
dbgmasp 3 "$LINENO:-$FUNCNAME"
else
dbgmas 0 "sourced @RP$name@"
fi
elif [[ -r "$defscript" ]] ; then
dbgmasp 0 "source (present) default @RP$defscript@"
if ! source $defscript ; then
mas_src_not_found $LINENO "$name / $defscript"
result=1
else
dbgmasp 0 "sourced default @RP$defscript@"
fi
elif [[ "${mas_src_scripts_optional}" ]] ; then
dbgmas 0 "not source (optional) @RP$shs@"
result=7
else
mas_src_not_found $LINENO "name: $name default: $defscript"
result=1
fi
fi
# source file subscripts ; args: full path, cnt
mas_sourcing_end_r '@' $name
dbgmasp 3 "$LINENO:/$FUNCNAME"
return $result
}
function mas_src_get_mpath ()
{
local mpath_name=$1 mpath_x mpath
dbgmasp 3 "$LINENO:$FUNCNAME"
if [[ "$mpath_name" =~ ^(.*)\+(.*)$ ]] ; then
mpath_name=${BASH_REMATCH[1]}
mpath_x=${BASH_REMATCH[2]}
fi
if [[ "$mpath_name" ]] ; then
mpath=${!mpath_name}
fi
if [[ "$mpath" ]] && [[ "$mpath_x" ]] ; then
mpath="$mpath/$mpath_x"
fi
if [[ "$mpath" ]] ; then
echo "$mpath"
fi
dbgmasp 3 "$LINENO:/$FUNCNAME"
}
# do scripts, report absent files (if mas_src_scripts_optional not set)
# args:
# - mpath var name
# - default script (if ONE OF scripts is absent) or -
# - ...... (scripts)
# env:
# - $mas_src_scripts_tail==<extension>
# - $mas_src_scripts_name=<name>
# - $mas_src_scripts_optional - if set, don't report error if file absent
function mas_src_scripts ()
{
local s s1 shscrx mpath_name mpath mpath_more result=127 res defscript
mpath_name="$1"
shift
defscript="$1"
shift
if ! [[ "$MAS_SCRIPTS_WORKDIR" ]] ; then local MAS_SCRIPTS_WORKDIR=$PWD ; fi
dbgmasp 3 "$LINENO:$FUNCNAME"
if [[ "$defscript" ]] && ! [[ "$defscript" == '-' ]] ; then
defscript="./$defscript"
fi
# mas_call_from define_std_directories stddirs
mas_get_lib_call stddirs define_std_directories
# mpath="${!mpath_name}"
mpath=$( mas_src_get_mpath ${mpath_name} )
# ${MAS_ECHO_CMD:=/bin/echo} "directory ($mas_src_scripts_optional): '$mpath' <== '$mpath_name'" >&2
local cnt=0 mid
declare -gx MAS_DOSCRIPT_MPATH=$mpath
## if [[ "$MAS_CONF_DIR_TERM_STAT" ]] ; then
## echo ">>>mss (pushd) `pwd`" >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
## echo ">>>mss (pushd) pushd $mpath" >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
## fi
dbgmasp 3 "$LINENO:$FUNCNAME"
if [[ "$mpath" ]] && pushd "$mpath" &>/dev/null ; then
dbgmasp 3 "$LINENO:$FUNCNAME"
for s in $@ ; do
# if [[ "$s" ]] ; then
# echo "eval ... $s" >&2
# s=`eval "builtin echo $s"`
# fi
dbgmasp 3 "$LINENO:$FUNCNAME"
if [[ "$s" ]] ; then
cnt=$(( $cnt + 1 ))
shscrx="${s}${mas_src_scripts_tail}"
declare -gx MAS_DOSCRIPT_NAME=$s
mas_src_literal_script "${defscript:--}" "./$shscrx" "$cnt"
dbgmasp 3 "$LINENO:-$FUNCNAME"
result=$?
if [[ $result -ne 7 ]] ; then
dbgmasp 3 "$LINENO:$FUNCNAME"
break
fi
# if [[ "$shscrx" ]] && [[ -f $shscrx ]] ; then
# # do script + subscripts
# if ! mas_src_literal_script "${defscript:--}" "./$shscrx" "$cnt" "${shscr}" ; then
# mas_src_not_found $LINENO $mpath $shscrx
# result=2
# else
# result=0
# fi
# break
# elif [[ "${mas_src_scripts_optional}" ]] ; then
# :
# else
# mas_src_not_found $LINENO $mpath $shscrx
# result=2
# break
# fi
fi
done
## echo ">>>mss (popd) `pwd`" >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
dbgmasp 3 "$LINENO:$FUNCNAME"
popd &>/dev/null
dbgmasp 3 "$LINENO:$FUNCNAME"
## echo ">>>mss (popd) `pwd`" >> $MAS_CONF_DIR_TERM_STAT/sourcing.$UID.$$.stat
else
# ${MAS_ECHO_CMD:=/bin/echo} "directory error: '$mpath' <== '$mpath_name'" >&2
[[ "${mas_src_scripts_optional}" ]] || mas_src_not_found $LINENO ${mpath:-EMPTY} "$mpath_name"
dbgmasp 5 " --- $FUNCNAME () -- bad mpath:$mpath"
result=2
fi
dbgmasp 3 "$LINENO:/$FUNCNAME"
return $result
}
# do scripts, report absent files (if mas_src_scripts_optional not set)
# args:
# - scriptset name
# - extension ('.sh', for instance) or '-' for none
# - mpath var name
# - default script (if ONE OF scripts is absent) or -
# - ....... (scripts)
function mas_src_scriptsn ()
{
local mas_src_scripts_tail
local mas_src_scripts_name=$1
shift
local exten=$1
shift
dbgmasp 3 "$LINENO:$FUNCNAME"
if [[ "$exten" ]] && ! [[ "$exten" == '-' ]] ; then
mas_src_scripts_tail="$exten"
fi
# args: mpath var name , ...... (scripts)
# env : $mas_src_scripts_tail==<extension> ; $mas_src_scripts_name=<name>
#### mas_echo_trace ">To call $mas_src_scripts_name [$exten] $@"
mas_src_scripts $@
dbgmasp 3 "$LINENO:/$FUNCNAME"
}
# do scripts, don't report absent files
# args:
# - scriptset name
# - extension ('.sh', for instance) or '-' for none
# - mpath var name
# - default script (if ONE OF scripts is absent) or -
# - ....... (scripts)
function mas_src_scriptsn_optional ()
{
local mas_src_scripts_optional=yes
dbgmasp 3 "$LINENO:$FUNCNAME"
mas_src_scriptsn $@
dbgmasp 3 "$LINENO:/$FUNCNAME"
}
# do std scripts (opt.?) default and opt. rc with opt.subscripts
# args:
# - scriptset name
# - mpath var names...
function mas_src_scriptsn_opt_std ()
{
local mas_src_scripts_name=$1
dbgmasp 3 "$LINENO:$FUNCNAME"
shift
local mpath_name
local mas_src_scripts_no_subscript
for mpath_name in $@ ; do
# ${MAS_ECHO_CMD:=/bin/echo} "[Do std] ${MAS_SCREEN_MODE_NEW}:${MAS_SCREEN_MODE} - ${mpath_name} : ${!mpath_name}" >&2
mas_src_scripts_no_subscript=yes
mas_src_scriptsn_optional "${mas_src_scripts_name:-unknown_mssn}" - ${mpath_name:-unknown_mpn} - default
unset mas_src_scripts_no_subscript
mas_src_scriptsn_optional "${mas_src_scripts_name:-unknown_mssn}" - ${mpath_name:-unknown_mpn} - rc
done
dbgmasp 3 "$LINENO:/$FUNCNAME"
}
# do scripts, report absent files (if mas_src_scripts_optional not set)
# SAME as mas_src_scriptsn, but with timing
# args:
# - scriptset name
# - extension ('.sh', for instance) or '-' for none
# - mpath var name
# - default script (if ONE OF scripts is absent) or -
# - ....... (scripts)
function mas_src_scriptsnt ()
{
local start_time end_time interval intervalp
dbgmasp 3 "$LINENO:$FUNCNAME"
if [[ "$MAS_RC_TIMING" ]] ; then
start_time=$(umoment)
fi
mas_src_scriptsn $@
if [[ "$MAS_RC_TIMING" ]] ; then
end_time=$(umoment)
if [[ "$end_time" && "$start_time" ]] ; then
interval=$( /usr/bin/dc --expression="$end_time $start_time -p" )
if [[ "${interval}" ]] ; then
# ${MAS_ECHO_CMD:=/bin/echo} "$PPID:$$ :r:[${interval} sec]" >>$MAS_BASH_LOG/screen/timing.$$.txt
:
fi
fi
if [[ "$end_time" && "$MAS_T00SP" ]] ; then
intervalp=$( /usr/bin/dc --expression="$end_time $MAS_T00SP -p" )
if [[ "${intervalp}" ]] ; then
# ${MAS_ECHO_CMD:=/bin/echo} "$PPID:$$ :p:[${intervalp} sec]" >>$MAS_BASH_LOG/screen/timing.$$.txt
:
fi
fi
fi
dbgmasp 3 "$LINENO:/$FUNCNAME"
}
# do scripts, don't report absent files
# SAME as mas_src_scriptsn_optional, but with timing
# args:
# - scriptset name
# - extension ('.sh', for instance) or '-' for none
# - mpath var name
# - default script (if ONE OF scripts is absent) or -
# - ....... (scripts)
function mas_src_scriptsnt_optional ()
{
local mas_src_scripts_optional=yes
dbgmasp 3 "$LINENO:$FUNCNAME"
mas_src_scriptsnt $@
}
function mas_interactive ()
{
dbgmasp 3 "$LINENO:$FUNCNAME"
[[ $- =~ 'i' ]] && return 0
return 2
}
fi
# vi: ft=sh
|
C++
|
UTF-8
| 9,225 | 2.78125 | 3 |
[] |
no_license
|
#include "cuimage/cuda/conversion.h"
#include <gtest/gtest.h>
using namespace cuimage;
TEST(RgbaToGrayTest, works_float)
{
float4 c1 = make_float4(1.f, 1.f, 1.f, 1.f);
float4 c2 = make_float4(0.f, 0.f, 0.f, 0.f);
float4 c3 = make_float4(0.3f, 0.2f, 0.4f, 0.f);
float4 c4 = make_float4(0.3f, 0.2f, 0.4f, 1.f);
EXPECT_FLOAT_EQ(1.f, rgba2gray(c1));
EXPECT_FLOAT_EQ(0.f, rgba2gray(c2));
EXPECT_FLOAT_EQ(0.f, rgba2gray(c3));
EXPECT_GT(rgba2gray(c4), 0.f);
EXPECT_LT(rgba2gray(c4), 1.f);
}
TEST(RgbaToGrayTest, works_uchar)
{
uchar4 c1 = make_uchar4(255, 255, 255, 255);
uchar4 c2 = make_uchar4(0, 0, 0, 0);
uchar4 c3 = make_uchar4(100, 200, 150, 0);
uchar4 c4 = make_uchar4(100, 200, 150, 255);
EXPECT_FLOAT_EQ(255, rgba2gray(c1));
EXPECT_FLOAT_EQ(0, rgba2gray(c2));
EXPECT_FLOAT_EQ(0, rgba2gray(c3));
EXPECT_GT(rgba2gray(c4), 0);
EXPECT_LT(rgba2gray(c4), 255);
}
TEST(RgbaToGrayTest, works_int)
{
int4 c1 = make_int4(255, 255, 255, 255);
int4 c2 = make_int4(0, 0, 0, 0);
int4 c3 = make_int4(100, 200, 150, 0);
int4 c4 = make_int4(100, 200, 150, 255);
EXPECT_FLOAT_EQ(255, rgba2gray(c1));
EXPECT_FLOAT_EQ(0, rgba2gray(c2));
EXPECT_FLOAT_EQ(0, rgba2gray(c3));
EXPECT_GT(rgba2gray(c4), 0);
EXPECT_LT(rgba2gray(c4), 255);
}
TEST(RgbToGrayTest, works_float)
{
float3 c1 = make_float3(1.f, 1.f, 1.f);
float3 c2 = make_float3(0.f, 0.f, 0.f);
float3 c3 = make_float3(0.3f, 0.2f, 0.5f);
EXPECT_FLOAT_EQ(1.f, rgb2gray(c1));
EXPECT_FLOAT_EQ(0.f, rgb2gray(c2));
EXPECT_GT(rgb2gray(c3), 0.f);
EXPECT_LT(rgb2gray(c3), 1.f);
}
TEST(RgbToGrayTest, works_uchar)
{
uchar3 c1 = make_uchar3(255, 255, 255);
uchar3 c2 = make_uchar3(0, 0, 0);
uchar3 c3 = make_uchar3(100, 200, 150);
EXPECT_FLOAT_EQ(255, rgb2gray(c1));
EXPECT_FLOAT_EQ(0, rgb2gray(c2));
EXPECT_GT(rgb2gray(c3), 0);
EXPECT_LT(rgb2gray(c3), 255);
}
TEST(RgbToGrayTest, works_int)
{
int3 c1 = make_int3(255, 255, 255);
int3 c2 = make_int3(0, 0, 0);
int3 c3 = make_int3(100, 200, 150);
EXPECT_FLOAT_EQ(255, rgb2gray(c1));
EXPECT_FLOAT_EQ(0, rgb2gray(c2));
EXPECT_GT(rgb2gray(c3), 0);
EXPECT_LT(rgb2gray(c3), 255);
}
TEST(RgbaToRgbTest, works_float)
{
float4 c1 = make_float4(1.f, 1.f, 1.f, 1.f);
float4 c2 = make_float4(0.f, 0.f, 0.f, 0.f);
float4 c3 = make_float4(0.3f, 0.2f, 0.4f, 0.f);
float4 c4 = make_float4(0.3f, 0.2f, 0.4f, 1.f);
float3 r1 = rgba2rgb<float3>(c1);
EXPECT_FLOAT_EQ(1.f, r1.x);
EXPECT_FLOAT_EQ(1.f, r1.y);
EXPECT_FLOAT_EQ(1.f, r1.z);
float3 r2 = rgba2rgb<float3>(c2);
EXPECT_FLOAT_EQ(0.f, r2.x);
EXPECT_FLOAT_EQ(0.f, r2.y);
EXPECT_FLOAT_EQ(0.f, r2.z);
float3 r3 = rgba2rgb<float3>(c3);
EXPECT_FLOAT_EQ(0.f, r3.x);
EXPECT_FLOAT_EQ(0.f, r3.y);
EXPECT_FLOAT_EQ(0.f, r3.z);
float3 r4 = rgba2rgb<float3>(c4);
EXPECT_FLOAT_EQ(c4.x, r4.x);
EXPECT_FLOAT_EQ(c4.y, r4.y);
EXPECT_FLOAT_EQ(c4.z, r4.z);
}
TEST(RgbaToRgbTest, works_uchar)
{
uchar4 c1 = make_uchar4(255, 255, 255, 255);
uchar4 c2 = make_uchar4(0, 0, 0, 0);
uchar4 c3 = make_uchar4(100, 200, 150, 0);
uchar4 c4 = make_uchar4(100, 200, 150, 255);
uchar3 r1 = rgba2rgb<uchar3>(c1);
EXPECT_EQ(255, r1.x);
EXPECT_EQ(255, r1.y);
EXPECT_EQ(255, r1.z);
uchar3 r2 = rgba2rgb<uchar3>(c2);
EXPECT_EQ(0, r2.x);
EXPECT_EQ(0, r2.y);
EXPECT_EQ(0, r2.z);
uchar3 r3 = rgba2rgb<uchar3>(c3);
EXPECT_EQ(0, r3.x);
EXPECT_EQ(0, r3.y);
EXPECT_EQ(0, r3.z);
uchar3 r4 = rgba2rgb<uchar3>(c4);
EXPECT_EQ(c4.x, r4.x);
EXPECT_EQ(c4.y, r4.y);
EXPECT_EQ(c4.z, r4.z);
}
TEST(RgbaToRgbTest, works_int)
{
int4 c1 = make_int4(255, 255, 255, 255);
int4 c2 = make_int4(0, 0, 0, 0);
int4 c3 = make_int4(100, 200, 150, 0);
int4 c4 = make_int4(100, 200, 150, 255);
int3 r1 = rgba2rgb<int3>(c1);
EXPECT_EQ(255, r1.x);
EXPECT_EQ(255, r1.y);
EXPECT_EQ(255, r1.z);
int3 r2 = rgba2rgb<int3>(c2);
EXPECT_EQ(0, r2.x);
EXPECT_EQ(0, r2.y);
EXPECT_EQ(0, r2.z);
int3 r3 = rgba2rgb<int3>(c3);
EXPECT_EQ(0, r3.x);
EXPECT_EQ(0, r3.y);
EXPECT_EQ(0, r3.z);
int3 r4 = rgba2rgb<int3>(c4);
EXPECT_EQ(c4.x, r4.x);
EXPECT_EQ(c4.y, r4.y);
EXPECT_EQ(c4.z, r4.z);
}
TEST(RgbToRgbaTest, works_float)
{
float3 c1 = make_float3(1.f, 1.f, 1.f);
float3 c2 = make_float3(0.f, 0.f, 0.f);
float3 c3 = make_float3(0.3f, 0.2f, 0.4f);
float4 r1 = rgb2rgba<float4>(c1);
EXPECT_FLOAT_EQ(1.f, r1.x);
EXPECT_FLOAT_EQ(1.f, r1.y);
EXPECT_FLOAT_EQ(1.f, r1.z);
EXPECT_FLOAT_EQ(1.f, r1.w);
float4 r2 = rgb2rgba<float4>(c2);
EXPECT_FLOAT_EQ(0.f, r2.x);
EXPECT_FLOAT_EQ(0.f, r2.y);
EXPECT_FLOAT_EQ(0.f, r2.z);
EXPECT_FLOAT_EQ(1.f, r2.w);
float4 r3 = rgb2rgba<float4>(c3);
EXPECT_FLOAT_EQ(c3.x, r3.x);
EXPECT_FLOAT_EQ(c3.y, r3.y);
EXPECT_FLOAT_EQ(c3.z, r3.z);
EXPECT_FLOAT_EQ(1.f, r3.w);
}
TEST(RgbToRgbaTest, works_uchar)
{
uchar3 c1 = make_uchar3(255, 255, 255);
uchar3 c2 = make_uchar3(0, 0, 0);
uchar3 c3 = make_uchar3(100, 200, 150);
uchar4 r1 = rgb2rgba<uchar4>(c1);
EXPECT_EQ(255, r1.x);
EXPECT_EQ(255, r1.y);
EXPECT_EQ(255, r1.z);
EXPECT_EQ(255, r1.w);
uchar4 r2 = rgb2rgba<uchar4>(c2);
EXPECT_EQ(0, r2.x);
EXPECT_EQ(0, r2.y);
EXPECT_EQ(0, r2.z);
EXPECT_EQ(255, r1.w);
uchar4 r3 = rgb2rgba<uchar4>(c3);
EXPECT_EQ(c3.x, r3.x);
EXPECT_EQ(c3.y, r3.y);
EXPECT_EQ(c3.z, r3.z);
EXPECT_EQ(255, r1.w);
}
TEST(RgbToRgbaTest, works_int)
{
int3 c1 = make_int3(255, 255, 255);
int3 c2 = make_int3(0, 0, 0);
int3 c3 = make_int3(100, 200, 150);
int4 r1 = rgb2rgba<int4>(c1);
EXPECT_EQ(255, r1.x);
EXPECT_EQ(255, r1.y);
EXPECT_EQ(255, r1.z);
EXPECT_EQ(255, r1.w);
int4 r2 = rgb2rgba<int4>(c2);
EXPECT_EQ(0, r2.x);
EXPECT_EQ(0, r2.y);
EXPECT_EQ(0, r2.z);
EXPECT_EQ(255, r1.w);
int4 r3 = rgb2rgba<int4>(c3);
EXPECT_EQ(c3.x, r3.x);
EXPECT_EQ(c3.y, r3.y);
EXPECT_EQ(c3.z, r3.z);
EXPECT_EQ(255, r1.w);
}
TEST(GrayToRgbTest, works_float)
{
float v1 = 1.f, v2 = 0.f, v3 = 0.3f;
float3 r1 = gray2rgb<float3>(v1);
EXPECT_FLOAT_EQ(v1, r1.x);
EXPECT_FLOAT_EQ(v1, r1.y);
EXPECT_FLOAT_EQ(v1, r1.z);
float3 r2 = gray2rgb<float3>(v2);
EXPECT_FLOAT_EQ(v2, r2.x);
EXPECT_FLOAT_EQ(v2, r2.y);
EXPECT_FLOAT_EQ(v2, r2.z);
float3 r3 = gray2rgb<float3>(v3);
EXPECT_FLOAT_EQ(v3, r3.x);
EXPECT_FLOAT_EQ(v3, r3.y);
EXPECT_FLOAT_EQ(v3, r3.z);
}
TEST(GrayToRgbTest, works_uchar)
{
float v1 = 255.f, v2 = 0.f, v3 = 30.f;
uchar u1 = 255, u2 = 0, u3 = 30;
uchar3 r1 = gray2rgb<uchar3>(v1);
EXPECT_EQ(u1, r1.x);
EXPECT_EQ(u1, r1.y);
EXPECT_EQ(u1, r1.z);
uchar3 r2 = gray2rgb<uchar3>(v2);
EXPECT_EQ(u2, r2.x);
EXPECT_EQ(u2, r2.y);
EXPECT_EQ(u2, r2.z);
uchar3 r3 = gray2rgb<uchar3>(v3);
EXPECT_EQ(u3, r3.x);
EXPECT_EQ(u3, r3.y);
EXPECT_EQ(u3, r3.z);
}
TEST(GrayToRgbTest, works_int)
{
float v1 = 255.f, v2 = 0.f, v3 = 30.f;
int u1 = 255, u2 = 0, u3 = 30;
int3 r1 = gray2rgb<int3>(v1);
EXPECT_EQ(u1, r1.x);
EXPECT_EQ(u1, r1.y);
EXPECT_EQ(u1, r1.z);
int3 r2 = gray2rgb<int3>(v2);
EXPECT_EQ(u2, r2.x);
EXPECT_EQ(u2, r2.y);
EXPECT_EQ(u2, r2.z);
int3 r3 = gray2rgb<int3>(v3);
EXPECT_EQ(u3, r3.x);
EXPECT_EQ(u3, r3.y);
EXPECT_EQ(u3, r3.z);
}
TEST(GrayToRgbaTest, works_float)
{
float v1 = 1.f, v2 = 0.f, v3 = 0.3f;
float4 r1 = gray2rgba<float4>(v1);
EXPECT_FLOAT_EQ(v1, r1.x);
EXPECT_FLOAT_EQ(v1, r1.y);
EXPECT_FLOAT_EQ(v1, r1.z);
EXPECT_FLOAT_EQ(1.f, r1.w);
float4 r2 = gray2rgba<float4>(v2);
EXPECT_FLOAT_EQ(v2, r2.x);
EXPECT_FLOAT_EQ(v2, r2.y);
EXPECT_FLOAT_EQ(v2, r2.z);
EXPECT_FLOAT_EQ(1.f, r2.w);
float4 r3 = gray2rgba<float4>(v3);
EXPECT_FLOAT_EQ(v3, r3.x);
EXPECT_FLOAT_EQ(v3, r3.y);
EXPECT_FLOAT_EQ(v3, r3.z);
EXPECT_FLOAT_EQ(1.f, r3.w);
}
TEST(GrayToRgbaTest, works_uchar)
{
float v1 = 255.f, v2 = 0.f, v3 = 30.f;
uchar u1 = 255, u2 = 0, u3 = 30;
uchar4 r1 = gray2rgba<uchar4>(v1);
EXPECT_EQ(u1, r1.x);
EXPECT_EQ(u1, r1.y);
EXPECT_EQ(u1, r1.z);
EXPECT_EQ(255, r1.w);
uchar4 r2 = gray2rgba<uchar4>(v2);
EXPECT_EQ(u2, r2.x);
EXPECT_EQ(u2, r2.y);
EXPECT_EQ(u2, r2.z);
EXPECT_EQ(255, r2.w);
uchar4 r3 = gray2rgba<uchar4>(v3);
EXPECT_EQ(u3, r3.x);
EXPECT_EQ(u3, r3.y);
EXPECT_EQ(u3, r3.z);
EXPECT_EQ(255, r3.w);
}
TEST(GrayToRgbaTest, works_int)
{
float v1 = 255.f, v2 = 0.f, v3 = 30.f;
int u1 = 255, u2 = 0, u3 = 30;
int4 r1 = gray2rgba<int4>(v1);
EXPECT_EQ(u1, r1.x);
EXPECT_EQ(u1, r1.y);
EXPECT_EQ(u1, r1.z);
EXPECT_EQ(255, r1.w);
int4 r2 = gray2rgba<int4>(v2);
EXPECT_EQ(u2, r2.x);
EXPECT_EQ(u2, r2.y);
EXPECT_EQ(u2, r2.z);
EXPECT_EQ(255, r2.w);
int4 r3 = gray2rgba<int4>(v3);
EXPECT_EQ(u3, r3.x);
EXPECT_EQ(u3, r3.y);
EXPECT_EQ(u3, r3.z);
EXPECT_EQ(255, r3.w);
}
|
Python
|
UTF-8
| 6,188 | 2.671875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import time
import datetime
import re
import cloudscraper
import pandas as pd
from bs4 import BeautifulSoup
now = datetime.datetime.now()
# def convertPrice(price, area):
# '''Convert price format'''
# if price == "Giรก thแปa thuแบญn":
# return None
# elif price.split(" ")[1]=="nghรฌn/mยฒ":
# return float(re.match("(.*?) nghรฌn/mยฒ", price).group(1))*float(re.match("(.*?) mยฒ", area).group(1))*1000
# elif price.split(" ")[1]=="triแปu/mยฒ":
# return float(re.match("(.*?) triแปu/mยฒ", price).group(1))*float(re.match("(.*?) mยฒ", area).group(1))*1000000
# elif price.split(" ")[1]=="tแปท/mยฒ":
# return float(re.match("(.*?) tแปท/mยฒ", price).group(1))*float(re.match("(.*?) mยฒ", area).group(1))*1000000000
# elif price.split(" ")[1]=="nghรฌn":
# return float(re.match("(.*?) nghรฌn", price).group(1))*1000
# elif price.split(" ")[1]=="triแปu":
# return float(re.match("(.*?) triแปu", price).group(1))*1000000
# elif price.split(" ")[1]=="tแปท":
# return float(re.match("(.*?) tแปท", price).group(1))*1000000000
# else:
# return price
def getPages(root):
'''Scrape root to get all pages from finding the max; sublinks are in the form of ie. /p2, /p3, /p100'''
last = None
while last is None: #Retry until last page is found
try:
scraper = cloudscraper.create_scraper() #cloudscraper to bypass Cloudfare
html = scraper.get(root).text
soup = BeautifulSoup(html, "html.parser")
last = max([int(link['pid']) for link in soup.findAll("a", href=re.compile(r"/p[0-9]"))])
except:
print("Reading root page fails. Retry in 2s...")
time.sleep(1.5)
pass
if int(last) > 2500:
last = 2500 #grab first 2500 pages only - Lambda function limits
print("Scanning {0} pages".format(last-2+1))
#get pages
pages = []
for i in range(2, int(last) + 1): # starts at 2
page = "/p{0}".format(str(i))
if page not in pages:
pages.append(page)
pages.append('/') #root also scrapable
return pages
def writeData(subUrls):
'''Iterate through links and write rows'''
rows = []
fails = []
for subUrl in subUrls:
print("Writing data: {0}".format(subUrl))
#grab html soup
scraper = cloudscraper.create_scraper()
time.sleep(1)
html = scraper.get(root+subUrl).text
soup = BeautifulSoup(html, "html.parser")
# listings per page
if not soup.findAll("div", {"class":re.compile(".* product-item clearfix .*")}):
print("Scrape unsuccessful: {0}".format(subUrl))
fails.append(subUrl)
else:
for listing in soup.findAll("div", {"class":re.compile(".* product-item clearfix .*")}):
uid = listing['uid']
prid = listing['prid']
url = root+subUrl
title = listing.find("a", {"class":"wrap-plink"})["title"] if listing.find("a", {"class":"wrap-plink"}) else None
price = listing.find("span", {"class":"price"}).text if listing.find("span", {"class":"price"}) else None
area = listing.find("span", {"class":"area"}).text if listing.find("span", {"class":"area"}) else None
bedroom = listing.find("span", {"class":"bedroom"}).text if listing.find("span", {"class":"bedroom"}) else None
toilet = listing.find("span", {"class":"toilet"}).text if listing.find("span", {"class":"toilet"}) else None
location = listing.find("span", {"class":"location"}).text if listing.find("span", {"class":"location"}) else None
content = listing.find("div", {"class":"product-content"}).text if listing.find("div", {"class":"product-content"}) else None
post_date = datetime.datetime.strptime(listing.find("span", {"class":"tooltip-time"}).text, "%d/%m/%Y").strftime("%Y-%m-%d") if listing.find("span", {"class":"tooltip-time"}) else None
# price_vnd = convertPrice(listing.find("span", {"class":"price"}).text, listing.find("span", {"class":"area"}).text) if listing.find("span", {"class":"price"}) and listing.find("span", {"class":"area"}) else None
# area_m2 = float(re.match("(.*?) mยฒ", listing.find("span", {"class":"area"}).text).group(1)) if listing.find("span", {"class":"area"}) else None
# city = listing.find("span", {"class":"location"}).text.split(", ")[1] if listing.find("span", {"class":"location"}) else None
# district = listing.find("span", {"class":"location"}).text.split(", ")[0] if listing.find("span", {"class":"location"}) else None
scrape_timestamp = now
row = {}
row.update({
"uid": uid,
"prid": prid,
"url": url,
"title_raw": title,
"price_raw": price,
"area_raw": area,
"bedroom_raw": bedroom,
"toilet_raw": toilet,
"location_raw": location,
"content_raw": content,
"post_date": post_date,
# "price_vnd": price_vnd,
# "area_m2": area_m2,
# "city": city,
# "district": district,
"scrape_timestamp": scrape_timestamp
})
rows.append(row)
return rows, fails
if __name__ == "__main__":
root = "https://batdongsan.com.vn/nha-dat-ban-tp-hcm"
pages = getPages(root=root)
rows, fails = writeData(pages)
print("Number of rows: {0}".format(len(rows)))
print("Number of pages failed: {0}".format(len(fails)))
print("Page success rate: {0}%".format(len(fails)/len(pages)))
df = pd.DataFrame(rows)
today = now.date()
sub_root = root.partition("https://batdongsan.com.vn/")[2]
df.to_csv("{0}-{1}.csv".format(today, sub_root))
print("Scrape job done!")
|
C++
|
UTF-8
| 263 | 2.828125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
int n;
string s;
cin >> n;
while(n--)
{ cin >> s;
if( s.size()<11)
{cout<< s<<endl;}
else
cout << s[0]<<s.size()-2<<s[s.size()-1]<<endl;
}
}
|
PHP
|
UTF-8
| 1,942 | 3.875 | 4 |
[] |
no_license
|
<?php
/*
*Classe TFilter
*provรช uma interface para definiรงรฃo de filtros de seleรงรฃo
*P. 174
*/
class TFilter extends TExpression
{
private $variable; //Variavel
private $operator; //Operador;
private $value; //Valor
/*
*metodo __construct()
*Instancia um novo filtro
*@param $variable = Variavel
*@param $operator = operador (>,<,<>,etc)
*@param $value = valor a ser comparado
*/
public function __construct($variable, $operator, $value)
{
//armazena as propriedades
$this->variable = $variable;
$this->operator = $operator;
//transforma o valor de acordo com certas regras antes de atribuir ร propriedade this->$value
$this->value = $this->transform($value);
}
/*
*mรฉtodo transform
*recebe um valor e faaz as tranformaรงรตes necessรกrias para ele ser interpretado pela base de dados
*podendo ser um INTEGER/STRING/BOOLEAN/ARRAY/ETC
*@param $value = valor a ser tranformado
*/
private function transform($value)
{
//se for um array
if(is_array($value))
{
//percorre os valores
foreach($value as $x)
{
//se for um inteiro
if(is_integer($x))
{
$foo[]= $x;
}
else if(is_string($x))
{
//se for uma string, adiciona aspas
$foo[]= "'$x'";
}
}
//converte o array em string separada por ","
$result = '(' . implode(',', $foo) . ')';
}
//se for uma string
else if(is_string($value))
{
//adiciona aspas
$result = "'$value'";
}
//se for um valor nulo
else if(is_null($value))
{
//armazena NULL
$result = 'NULL';
}
//se for um booleano
else if(is_bool($value))
{
//armazena TRUE ou FALSE
$result = $value ? 'TRUE' : 'FALSE';
}
else
{
$result = $value;
}
//retorna o valor
return $result;
}
/*
*mรฉtodo dump()
*retorna o filtro em forma de expressรฃo
*/
public function dump()
{
//concatena a expressao
return "{$this->variable} {$this->operator} {$this->value}";
}
}
?>
|
PHP
|
UTF-8
| 2,826 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use finfo;
use Respect\Validation\Test\RuleTestCase;
use SplFileInfo;
use SplFileObject;
use function random_int;
use function tmpfile;
use const FILEINFO_MIME_TYPE;
use const PHP_INT_MAX;
/**
* @group rule
*
* @covers \Respect\Validation\Rules\Mimetype
*
* @author Alexandre Gomes Gaigalas <alganet@gmail.com>
* @author Danilo Correa <danilosilva87@gmail.com>
* @author Gabriel Caruso <carusogabriel34@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
*/
final class MimetypeTest extends RuleTestCase
{
/**
* @test
*/
public function itShouldValidateWithDefinedFinfoInstance(): void
{
$mimetype = 'application/octet-stream';
$filename = 'tests/fixtures/valid-image.png';
$fileInfoMock = $this
->getMockBuilder(finfo::class)
->disableOriginalConstructor()
->getMock();
$fileInfoMock
->expects(self::once())
->method('file')
->with($filename, FILEINFO_MIME_TYPE)
->will(self::returnValue($mimetype));
$rule = new Mimetype($mimetype, $fileInfoMock);
self::assertTrue($rule->validate($filename));
}
/**
* {@inheritDoc}
*/
public function providerForValidInput(): array
{
return [
'image/png' => [new Mimetype('image/png'), 'tests/fixtures/valid-image.png'],
'image/gif' => [new Mimetype('image/gif'), 'tests/fixtures/valid-image.gif'],
'image/jpeg' => [new Mimetype('image/jpeg'), 'tests/fixtures/valid-image.jpg'],
'text/plain' => [new Mimetype('text/plain'), 'tests/fixtures/executable'],
'SplFileInfo' => [new Mimetype('image/png'), new SplFileInfo('tests/fixtures/valid-image.png')],
'SplFileObject' => [new Mimetype('image/png'), new SplFileObject('tests/fixtures/valid-image.png')],
];
}
/**
* {@inheritDoc}
*/
public function providerForInvalidInput(): array
{
return [
'invalid file' => [new Mimetype('image/png'), 'tests/fixtures/invalid-image.png'],
'mismatch' => [new Mimetype('image/gif'), 'tests/fixtures/valid-image.png'],
'directory' => [new Mimetype('application/octet-stream'), __DIR__],
'boolean' => [new Mimetype('application/octet-stream'), true],
'array' => [new Mimetype('application/octet-stream'), [__FILE__]],
'integer' => [new Mimetype('application/octet-stream'), random_int(1, PHP_INT_MAX)],
'float' => [new Mimetype('application/octet-stream'), random_int(1, 9) / 10],
'null' => [new Mimetype('application/octet-stream'), null],
'resource' => [new Mimetype('application/octet-stream'), tmpfile()],
];
}
}
|
Java
|
UTF-8
| 547 | 3.09375 | 3 |
[] |
no_license
|
import java.util.Random;
public class Item {
private String symbol;
private int x;
private int y;
public Item (Map map) {
Random random = new Random();
do {
y = random.nextInt(map.GetSize());
x = random.nextInt(map.GetSize());
} while (!map.isEmptyCell(x, y));
}
public void SetSymbol(String symbol) {
this.symbol = symbol;
}
public String GetSymbol() {
return symbol;
}
public void SetXY(int x, int y) {
this.x = x;
this.y = y;
}
public int GetX() {
return x;
}
public int GetY() {
return y;
}
}
|
Java
|
UTF-8
| 82 | 1.757813 | 2 |
[
"Apache-2.0"
] |
permissive
|
package voss.nms.inventory.constants;
public enum PortMode {
IP,
VLAN,;
}
|
Markdown
|
UTF-8
| 1,166 | 2.984375 | 3 |
[] |
no_license
|
---
title: Connectivity check
table_of_contents: true
---
# Connectivity check
Connectivity checking is a NetworkManager functionality that allows
periodically testing whether the system can actually access the
internet or not. The network-manager snap allows configuring this
feature by using the following snap settings:
* **connectivity.interval**: it specifies the number of seconds between checks.
If set to 0, it disables connectivity check. Set to 300 by default.
* **connectivity.response**: This is the expected HTTP body response from the server
specified by connectivity.uri.
* **connectivity.uri**: The URI where NM is going to periodically access to check connectivity.
More details on how these options work can be found in the connectivity section of
the [NetworkManager.conf configuration file documentation](https://developer.gnome.org/NetworkManager/stable/NetworkManager.conf.html).
Some example commands on how to set a check every three minutes using the
Ubuntu connectivity check server are
```
$ snap set network-manager connectivity.uri=http://connectivity-check.ubuntu.com/
$ snap set network-manager connectivity.interval=180
```
|
Java
|
UTF-8
| 3,504 | 4.15625 | 4 |
[] |
no_license
|
package Exercises5;
// (a) Write a menu-driven program that provides three options:
// **The first option allows the user to enter a temperature
// in Celsius and displays the corresponding Fahrenheit temperature;
// **The second option allows the user to enter a temperature in
// Fahrenheit and displays the corresponding Celsius temperature
// **The third option allows the user to quit
// The formula that you need are as follows, where C represents
// a Celcius Temperature and F a Fahrenheit temperature:
// F = [(9C)/5] + 32
// C = [5(F -32)]/ 9
// (b) Adapt the above program so that the user is not allowed to
// enter a temperature below absolute zero; this is -273.15C or
// -459.67F
import java.awt.*;
import java.util.Scanner;
public class TempConverter {
private static Scanner kbd = new Scanner(System.in);
private static Scanner kbd2 = new Scanner(System.in);
public static void main(String[] args) {
int value;
String answer;
boolean anotherFlag = true;
do {
do {
drawMenu();
value = kbd.nextInt();
if (value > 3 || value < 1) {
System.out.println("Valor invalido\nIntenta de nuevo");
}
} while (value > 3 || value < 1);
switch (value) {
case 1:
int celcius = 0;
do {
System.out.println("Cยฐ ");
celcius = kbd.nextInt();
if (isValidC(celcius)){
System.out.println("Valor invalido");
}
} while (isValidC(celcius));
System.out.println(celcius + " Cยฐ = " + convertCF(celcius) + "Fยฐ");
break;
case 2:
int fhar = 0;
do {
System.out.println("Fยฐ ");
fhar = kbd.nextInt();
if (isValidC(fhar)){
System.out.println("Valor invalido");
}
} while (isValidF(fhar));
System.out.println(fhar + "Fยฐ = " + convertCF(fhar) + "Cยฐ");
break;
}
do {
System.out.println("Again?(Y|N)");
answer = kbd2.nextLine();
if (!answer.equalsIgnoreCase("n") && !answer.equalsIgnoreCase("y")) {
System.out.println("Valor invalido\nIntenta de nuevo");
}
} while (!answer.equalsIgnoreCase("n") && !answer.equalsIgnoreCase("y"));
if (answer.equalsIgnoreCase("n")) {
break;
} else if (answer.equalsIgnoreCase("y")) {
continue;
}
} while (anotherFlag);
}
// Imprime menu
static void drawMenu() {
System.out.println("1. Cยฐ to Fยฐ");
System.out.println("2. Fยฐ to Cยฐ");
System.out.println("3. Quit");
}
// Celcius to Fahrenheit
static double convertCF(double celcius) {
return ((9 * celcius) / 5) + 32;
}
// Fahrenheit to Celcius
static double convertFC(double fahr) {
return (fahr - 32) * ((double) 5 / (double) 9);
}
static boolean isValidC(double celcius) {
return celcius <= -273.15;
}
static boolean isValidF(double fhar) {
return fhar <= -459.67;
}
}
|
C++
|
UTF-8
| 7,035 | 2.953125 | 3 |
[] |
no_license
|
int cardgame::ai_best_card_wins_strategy (const int ai_attack_point, const int player_attack_point) { // 0
print("best card ai");
if (ai_attack_point > player_attack_point) return 3;
if (ai_attack_point < player_attack_point) return -2;
return -1; //draw
}
int cardgame::ai_min_loss_strategy (const int ai_attack_point, const int player_attack_point) { // 1
print("min loss ai");
if (ai_attack_point > player_attack_point) return 1;
if (ai_attack_point < player_attack_point) return -4;
return -1; //draw
}
int cardgame::ai_points_tally_strategy (const int ai_attack_point, const int player_attack_point) { // 2
print("tall points ai");
return (ai_attack_point - player_attack_point);
}
int cardgame::ai_loss_prevention_strategy (const int8_t life_ai, const int ai_attack_point, const int player_attack_point){ //3
print("ai loss prevent");
if (life_ai + ai_attack_point - player_attack_point > 0) return 1;
return 0;
}
int cardgame::ai_choose_card(const game& game_data) {
int available_strategies = 4;
if ( game_data.life_ai > 2) available_strategies --;
int strategy_idx = random(available_strategies);
//calc the score of each card of each card in ai hand
int choosen_card_idx = -1;
int choosen_card_score = std::numeric_limits<int>::min();
for (int i = 0; i < game_data.hand_ai.size(); i++) {
const auto ai_card_id = game_data.hand_ai[i];
const auto ai_card = card_dict.at(ai_card_id);
// ignore empty slot
if (ai_card.type == EMPTY) continue;
// calc total score for this cad relative to the player's hand
int card_score = calculate_ai_card_score(strategy_idx, game_data.life_ai, ai_card, game_data.hand_player);
// keep track of the card with the highest value
if (choosen_card_score < card_score) {
choosen_card_score = card_score;
choosen_card_idx = i;
}
}
return choosen_card_idx;
}
int cardgame::calculate_ai_card_score(const int strategy_idx, const uint8_t life_ai, const card& ai_card, vector<uint8_t> hand_player) {
int total = 0;
//int ai_card_attack_points = ai_card.attack_point;
if (strategy_idx == 0) {
for (int i = 0; i < hand_player.size(); i++) {
auto player_card = card_dict.at(hand_player[i]);
int player_card_attack_points = calculate_attack_point(player_card, ai_card);
int ai_card_attack_points = calculate_attack_point(ai_card, player_card);
total += ai_best_card_wins_strategy(ai_card_attack_points, player_card_attack_points);
}
}
if (strategy_idx == 1) {
for (int i = 0; i < hand_player.size(); i++) {
auto player_card = card_dict.at(hand_player[i]);
int player_card_attack_points = calculate_attack_point(player_card, ai_card);
int ai_card_attack_points = calculate_attack_point(ai_card, player_card);
total += ai_min_loss_strategy(ai_card_attack_points, player_card_attack_points);
}
}
if (strategy_idx == 2) {
for (int i = 0; i < hand_player.size(); i++) {
auto player_card = card_dict.at(hand_player[i]);
int player_card_attack_points = calculate_attack_point(player_card, ai_card);
int ai_card_attack_points = calculate_attack_point(ai_card, player_card);
total += ai_points_tally_strategy(ai_card_attack_points, player_card_attack_points);
}
}
if (strategy_idx == 3) {
for (int i = 0; i < hand_player.size(); i++) {
auto player_card = card_dict.at(hand_player[i]);
int player_card_attack_points = calculate_attack_point(player_card, ai_card);
int ai_card_attack_points = calculate_attack_point(ai_card, player_card);
total += ai_loss_prevention_strategy(life_ai, ai_card_attack_points, player_card_attack_points);
}
}
return total;
}
int cardgame::calculate_attack_point(const card& card1, const card& card2) {
int result = card1.attack_point;
//elemental compat handling bonus of 1?
if ((card1.type == FIRE && card2.type == WOOD) ||
(card1.type == WOOD && card2.type == WATER) ||
(card1.type == WATER && card2.type == FIRE)) {
result ++;
}
return result;
}
// resolve selected cards aka update the damage dealt
void cardgame::resolve_selected_cards(game& game_data) {
const auto player_card = card_dict.at(game_data.selected_card_player);
const auto ai_card = card_dict.at(game_data.selected_card_ai);
// VOID cards skipp all damage calculation
if (player_card.type == VOID || ai_card.type == VOID) return;
int player_attack_point = calculate_attack_point(player_card, ai_card);
int ai_attack_point = calculate_attack_point(ai_card, player_card);
// damage calculation
// deal damage ot ai if the player's card attack points are higher
// deal damage to player if the ai's AP are higher
if (player_attack_point > ai_attack_point) {
int diff = player_attack_point - ai_attack_point;
game_data.life_lost_ai = diff;
game_data.life_ai -= diff;
} else if (player_attack_point < ai_attack_point) {
int diff = ai_attack_point - player_attack_point;
game_data.life_lost_player = diff;
game_data.life_player -= diff;
}
}
void cardgame::update_game_status(user_info& user_data) { // passing by REFERENCE so can make mods directly on it.*****
game& game_data = user_data.game_data;
if (game_data.life_ai <= 0) {
// check ai's life, life_ai
game_data.status = PLAYER_WON;
} else if (game_data.life_player <= 0) {
// check player's life, life_player
game_data.status = PLAYER_LOST;
} else {
// check to make sure players still have cards
// if one of the players runs out of cards, the other has too.
const auto is_empty_slot = [&](const auto& id) {
return card_dict.at(id).type == EMPTY;
};
// bool player_finished == std::all_of(first, last, test); // runs test over the first to last element of vector
bool player_finished = std::all_of(game_data.hand_player.begin(), game_data.hand_player.end(), is_empty_slot); // runs test over the first to last element of vector
bool ai_finished = std::all_of(game_data.hand_ai.begin(), game_data.hand_ai.end(), is_empty_slot); // runs test over the first to last element of vector
if (player_finished || ai_finished) {
//compare life totals and see who won
if (game_data.life_player > game_data.life_ai) {
game_data.status = PLAYER_WON;
} else
game_data.status = PLAYER_LOST;
}
}
//update the player's win and lost count to match
if (game_data.status == PLAYER_WON) {
user_data.win_count++;
} else if (game_data.status == PLAYER_LOST) {
user_data.lost_count++;
}
}
|
Markdown
|
UTF-8
| 4,023 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
# 4ยช feira da 3ยช Semana do Advento
## 1ยช Leitura - Is 45,6b-8.18.21b-25
> Cรฉus, deixai cair orvalho das alturas.
**Leitura do Livro do Profeta Isaรญas 45,6b-8.18.21b-25**
6 Eu sou o Senhor, nรฃo hรก outro, 7 eu formei a luz e criei as trevas, crio o bem-estar e as condiรงรตes de mal-estar: sou o Senhor que faรงo todas estas coisas. 8 Cรฉus, deixai cair orvalho das alturas, e que as nuvens faรงam chover justiรงa; abra-se a terra e germine a salvaรงรฃo; brote igualmente a justiรงa: eu, o Senhor, a criei.' 18 Isto diz o Senhor que criou os cรฉus, o prรณprio Deus que fez a terra, a conformou e consolidou; nรฃo a criou para ficar vazia, formou-a para ser habitada: 'Sou eu o Senhor, e nรฃo hรก outro. 21b Quem vos fez ouvir os fatos passados e soube predizรช-los desde entรฃo? Acaso nรฃo sou eu o Senhor? E nรฃo hรก deus alรฉm de mim. Nรฃo hรก um Deus justo, e que salve, a nรฃo ser eu. 22 Povos de todos os confins da terra, voltai-vos para mim e sereis salvos, eu sou Deus e nรฃo hรก outro. 23 Juro por mim mesmo: de minha boca sai o que รฉ justo, a palavra que nรฃo volta atrรกs; todo joelho hรก de dobrar-se para mim, por mim hรก de jurar toda lรญngua, 24 dizendo: Somente no Senhor residem justiรงa e forรงa'. Comparecerรฃo perante ele, envergonhados, todos os que lhe resistem; 25 no Senhor serรก justificada e glorificada toda a descendรชncia de Israel. Palavra do Senhor.
## Salmo - Sl 84 (85), 9ab-10. 11-12. 13-14 (R. Cf Is 45,8)
`R. Que os cรฉus lรก do alto derramem o orvalho,que chova das nuvens o Justo esperado!`
9a Quero ouvir o que o Senhor irรก falar:*
รฉ a paz que ele vai anunciar;
9b a paz para o seu povo e seus amigos,*
para os que voltam ao Senhor seu coraรงรฃo.
10 Estรก perto a salvaรงรฃo dos que o temem,*
e a glรณria habitarรก em nossa terra. R.
11 A verdade e o amor se encontrarรฃo,*
a justiรงa e a paz se abraรงarรฃo;
12 da terra brotarรก a fidelidade,*
e a justiรงa olharรก dos altos cรฉus. R.
13 O Senhor nos darรก tudo o que รฉ bom,*
e a nossa terra nos darรก suas colheitas;
14 a justiรงa andarรก na sua frente*
e a salvaรงรฃo hรก de seguir os passos seus. R.
## Evangelho - Lc 7,19-23
> Ide contar a Joรฃo o que vistes e ouvistes.
**+ Proclamaรงรฃo do Evangelho de Jesus Cristo segundo Sรฃo Lucas 7,19-23**
Naquele tempo: Joรฃo convocou dois de seus discรญpulos,
19 e mandou-os perguntar ao Senhor:
'รs tu aquele que hรก de vir, ou devemos esperar outro?'
20 Eles foram ter com Jesus, e disseram:
'Joรฃo Batista nos mandou a ti para perguntar:
`รs tu aquele que hรก de vir, ou devemos esperar outro?''
21 Nessa mesma hora, Jesus curou de doenรงas, enfermidades
e espรญritos malignos a muitas pessoas,
e fez muitos cegos recuperarem a vista.
22 Entรฃo, Jesus lhes respondeu:
'Ide contar a Joรฃo o que vistes e ouvistes:
os cegos recuperam a vista,
os paralรญticos andam, os leprosos sรฃo purificados,
os surdos ouvem, os mortos ressuscitam,
e a Boa Nova รฉ anunciada aos pobres.
23 E feliz รฉ aquele
que nรฃo se escandaliza por causa de mim!'
Palavra da Salvaรงรฃo.
## Reflexรฃo - Lc 7, 19-23
O Antigo Testamento estรก no seu tรฉrmino e o Novo Testamento estรก no seu inรญcio. O Antigo Testamento estรก representado em Joรฃo Batista, o seu รบltimo profeta, o maior entre os nascidos de mulher, e o Novo Testamento estรก representado em Jesus Cristo, o Filho de Deus que se fez homem e veio a este mundo. O sinal da mudanรงa sรฃo os milagres que estรฃo acontecendo como cumprimento de todas as profecias feitas no Antigo Testamento, deixando de serem promessas para tornarem-se realidade. Estamos nos tempos messiรขnicos, Deus estรก cumprindo todas as suas promessas em relaรงรฃo ร sua realizaรงรฃo.
Veja mais no [Liturgia Diรกria - CNBB](http://liturgiadiaria.cnbb.org.br/app/user/user/UserView.php?ano=2016&mes=12&dia=14)
|
Java
|
UTF-8
| 502 | 3.203125 | 3 |
[] |
no_license
|
package ucankucuk.github.io.functionalInterface;
import java.util.function.Function;
public class FunctionalIntfExmpl {
public static void main(String[] args) {
Function<String, Integer> intFunc = x -> x.length();
System.out.println("Input length = " + intFunc.apply("ucankucuk"));
Function<String, String> strFunc = x -> x + " ADDED";
System.out.println(strFunc.apply("XXX"));
System.out.println(strFunc.andThen(intFunc).apply("ucankucuk"));
}
}
|
Python
|
UTF-8
| 2,733 | 2.65625 | 3 |
[] |
no_license
|
# coding=utf-8
import numpy as np
import cv2 as cv
import random
from matplotlib import pyplot as plt
__author__ = 'huangliang'
__version__ = 'v1.0'
def _nothing(x):
pass
def color_palette():
# ๅๅปบ็ฉบ็็ปๅธๅไธไธช็ชๅฃ
img = np.zeros((300,512,3), np.uint8)
cv.namedWindow('palette')
# ๅๅปบๆปๅจๆก
cv.createTrackbar('R', 'palette', 0, 255, _nothing)
cv.createTrackbar('G', 'palette', 0, 255, _nothing)
cv.createTrackbar('B', 'palette', 0, 255, _nothing)
# ๅๅปบๅผๅ
ณ
switch = '0: OFF \n1: ON'
cv.createTrackbar(switch, 'palette', 0, 1, _nothing)
while True:
cv.imshow('palette', img)
k = cv.waitKey(1) & 0xff
if k == 27: break
r = cv.getTrackbarPos('R', 'palette')
g = cv.getTrackbarPos('G', 'palette')
b = cv.getTrackbarPos('B', 'palette')
s = cv.getTrackbarPos(switch, 'palette')
img[:] = 0 if s == 0 else [b, g, r]
def click_to_draw_circle():
def nothing(x):
get_color_palette(palette)
def create_color_palette():
# ๅๅปบ็ฉบ็็ปๅธๅไธไธช็ชๅฃ
cv.namedWindow('palette')
# ๅๅปบๆปๅจๆก
cv.createTrackbar('R', 'palette', 18, 255, nothing)
cv.createTrackbar('G', 'palette', 211, 255, nothing)
cv.createTrackbar('B', 'palette', 146, 255, nothing)
# ๅๅปบๅผๅ
ณ
cv.createTrackbar('switch', 'palette', 0, 1, _nothing)
return None
def get_color_palette(img):
r = cv.getTrackbarPos('R', 'palette')
g = cv.getTrackbarPos('G', 'palette')
b = cv.getTrackbarPos('B', 'palette')
s = cv.getTrackbarPos('switch', 'palette')
img[:] = 0 if s == 0 else [b, g, r]
cv.imshow('palette', img)
ret = (0, 0, 0) if s == 0 else (b, g, r)
return ret
def draw_circle(event, x, y, flags, param):
if event == cv.EVENT_LBUTTONDOWN:
color = get_color_palette(palette)
radius = random.randint(10, 60)
cv.circle(img, (x, y), radius, color, -1)
img = np.zeros((600,800,3), np.uint8)
palette = np.zeros((200, 360, 3), np.uint8)
create_color_palette()
cv.namedWindow('image')
cv.setMouseCallback('image', draw_circle)
while True:
cv.imshow('image', img)
key = cv.waitKey(20)
if key == 27:
break
elif key == ord('s'):
cv.imwrite('hl_painting.jpg', img)
cv.destroyAllWindows()
print('---save done---')
cv.destroyAllWindows()
def main():
click_to_draw_circle()
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 230 | 2.265625 | 2 |
[] |
no_license
|
@Override
public CharBuffer slice() {
byteBuffer.limit(limit << 1);
byteBuffer.position(position << 1);
CharBuffer result = new CharToByteBufferAdapter(byteBuffer.slice());
byteBuffer.clear();
return result;
}
|
JavaScript
|
UTF-8
| 468 | 2.625 | 3 |
[] |
no_license
|
!function () {
var view = View('#Loading');
var controller = {
view: null,
init: function (view) {
this.view = view;
this.removeLoading();
},
removeLoading: function () {
//Loadingๅจ็ป็ปๆ
setTimeout(x => {
this.removeClassList(); //view.classList.remove('active')
}, 1000);
},
removeClassList: function () {
this.view.classList.remove('active');
}
};
controller.init(view);
}.call();
|
Python
|
UTF-8
| 5,767 | 2.84375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
"""
HappyBase utility module.
These functions are not part of the public API.
"""
import re
import asyncio
from functools import lru_cache
from typing import (
Dict,
List,
Tuple,
Any,
AnyStr,
Optional,
TypeVar,
Callable,
Iterable,
Iterator,
Union,
Coroutine,
)
from Hbase_thrift import TRowResult, TCell
T = TypeVar('T')
KTI = TypeVar('KTI')
VTI = TypeVar('VTI')
KTO = TypeVar('KTO')
VTO = TypeVar('VTO')
CAPITALS = re.compile('([A-Z])')
@lru_cache(maxsize=None)
def camel_to_snake_case(name: str) -> str:
"""Convert a CamelCased name to PEP8 style snake_case."""
return CAPITALS.sub(r'_\1', name).lower().lstrip('_')
@lru_cache(maxsize=None)
def snake_to_camel_case(name: str, initial: bool = False) -> str:
"""Convert a PEP8 style snake_case name to CamelCase."""
chunks = name.split('_')
converted = [s.capitalize() for s in chunks]
if initial:
return ''.join(converted)
else:
return chunks[0].lower() + ''.join(converted[1:])
def thrift_attrs(obj_or_cls) -> List[str]:
"""Obtain Thrift data type attribute names for an instance or class."""
return [v[1] for v in obj_or_cls.thrift_spec.values()]
def thrift_type_to_dict(obj: Any) -> Dict[str, Any]:
"""Convert a Thrift data type to a regular dictionary."""
return {
camel_to_snake_case(attr): getattr(obj, attr)
for attr in thrift_attrs(obj)
}
def ensure_bytes(value: AnyStr) -> bytes:
"""Convert text into bytes, and leaves bytes as-is."""
if isinstance(value, bytes):
return value
if isinstance(value, str):
return value.encode('utf-8')
raise TypeError(f"input must be str or bytes, got {type(value).__name__}")
def bytes_increment(b: bytes) -> Optional[bytes]:
"""
Increment and truncate a byte string (for sorting purposes)
This functions returns the shortest string that sorts after the given
string when compared using regular string comparison semantics.
This function increments the last byte that is smaller than ``0xFF``, and
drops everything after it. If the string only contains ``0xFF`` bytes,
`None` is returned.
"""
assert isinstance(b, bytes)
b = bytearray(b) # Used subset of its API is the same on Python 2 and 3.
for i in range(len(b) - 1, -1, -1):
if b[i] != 0xff:
b[i] += 1
return bytes(b[:i+1])
return None
def _id(x: T) -> T: return x
def map_dict(data: Dict[KTI, VTI],
keys: Callable[[KTI], KTO] = _id,
values: Callable[[VTI], VTO] = _id) -> Dict[KTO, VTO]:
"""
Dictionary mapping function, analogous to :py:func:`builtins.map`. Allows
applying a specific function independently to both the keys and values.
:param data: Dictionary to apply mapping to
:param keys: Optional function to apply to all keys
:param values: Optional function to apply to all values
:return: New dictionary with keys and values mapped
"""
return {keys(k): values(v) for k, v in data.items()}
def make_row(row: TRowResult,
include_ts: bool = False) -> Union[Dict[bytes, bytes],
Dict[bytes, Tuple[bytes, int]]]:
"""
Make a row dict for a given row result.
:param row: Row result from thrift client to convert a row dictionary
:param include_ts: Include timestamp with the values?
:return: Dictionary mapping columns to values for the row.
"""
cell_map = _get_cell_map(row).items()
if include_ts:
return {name: (cell.value, cell.timestamp) for name, cell in cell_map}
else:
return {name: cell.value for name, cell in cell_map}
def _get_cell_map(row: TRowResult) -> Dict[bytes, TCell]:
"""Convert a row result to dictionary mapping column names to cells."""
if row.sortedColumns is not None:
return {c.columnName: c.cell for c in row.sortedColumns}
elif row.columns is not None:
return row.columns
else: # pragma: no cover
raise RuntimeError("Neither columns nor sortedColumns is available!")
def iter_cells(cells: List[TCell],
include_ts: bool = False) -> Union[Iterator[bytes],
Iterator[Tuple[bytes, int]]]:
"""
Get the values of a list of cells.
:param cells: List of TCells to process
:param include_ts: Include timestamp with the values?
:return: Iterator of cell values or tuple of values and timestamps
"""
if include_ts:
return ((c.value, c.timestamp) for c in cells)
else:
return (c.value for c in cells)
def check_invalid_items(**kwargs: Tuple[T, Iterable[T]]):
"""
Check if a parameter's value is within a valid set of values. Multiple
parameters can be checked at once.
:param kwargs:
Parameter names mapped to tuples of actual value and possible values.
:raises ValueError: If a parameter value is not valid
"""
for key, (value, possible) in kwargs.items():
possible = set(possible)
if value not in possible:
raise ValueError(f"{key}={value} is not in: {possible}")
def run_coro(coro: Coroutine[None, None, T],
error: str = "Event Loop Running") -> T:
"""
Run a coroutine in the current event loop using
:py:meth:`asyncio.BaseEventLoop.run_until_complete`.
:param coro: Coroutine to run
:param error: Error message to use if the event loop is running
:returns: Result of the coroutine
:raises RuntimeError: If the event loop is already running
"""
loop = asyncio.get_event_loop()
if loop.is_running():
raise RuntimeError(error)
return loop.run_until_complete(coro)
|
TypeScript
|
UTF-8
| 1,368 | 2.78125 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import { Extension } from 'sourcegraph/module/client/extension'
import { ErrorLike, isErrorLike } from '../errors'
import { ExtensionManifest } from '../schema/extension.schema'
import * as GQL from '../schema/graphqlschema'
import { Settings } from '../settings'
/**
* Describes a configured extension.
*
* @template S the configuration subject type
* @template C the type of the extension's settings (overlaid on the base settings JSON Schema-derived type)
* @template RX the registry extension type
*/
export interface ConfiguredExtension<
RX extends Pick<GQL.IRegistryExtension, 'id' | 'url' | 'viewerCanAdminister'> = Pick<
GQL.IRegistryExtension,
'id' | 'url' | 'viewerCanAdminister'
>
> extends Extension {
/** The parsed extension manifest, null if there is none, or a parse error. */
manifest: ExtensionManifest | null | ErrorLike
/** The raw extension manifest (JSON), or null if there is none. */
rawManifest: string | null
/** The corresponding extension on the registry, if any. */
registryExtension?: RX
}
/** Reports whether the given extension is enabled in the settings. */
export function isExtensionEnabled(settings: Settings | ErrorLike | null, extensionID: string): boolean {
return !!settings && !isErrorLike(settings) && !!settings.extensions && !!settings.extensions[extensionID]
}
|
JavaScript
|
UTF-8
| 1,623 | 2.859375 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
class SearchForm extends Component {
constructor(props) {
super(props);
this.state = {
city: '',
returnedData: ''
}
this.handleTextInput = this.handleTextInput.bind(this)
this.handleFormSubmit = this.handleFormSubmit.bind(this)
}
handleTextInput(event) {
this.setState ({
city: event.target.value
})
}
handleFormSubmit(event) {
event.preventDefault()
fetch('https://api.citybik.es/v2/networks?fields=company,name,location/')
.then(response => response.json())
.then(data => {
this.setState({
returnedData: data
})
})
}
renderCity() {
const { returnedData } = this.state
console.log("this is returnedData: " + this.state);
return (
<div>
<h1>{returnedData.name}</h1>
<h3>{returnedData.company}</h3>
<h3>{returnedData.city}</h3>
<h3>{returnedData.country}</h3>
</div>
)
}
render() {
return (
<div>
<form onSubmit={this.handleFormSubmit}>
<label>
Enter City
<input type="text" name="" onChange={this.handleTextInput} />
</label>
<input type="submit" value="Submit" />
</form>
<h2>Bike Sharing Locations</h2>
{this.renderCity()}
</div>
);
}
}
export default SearchForm;
|
C++
|
UTF-8
| 1,977 | 2.75 | 3 |
[] |
no_license
|
#ifndef ONIONLETTER_H
#define ONIONLETTER_H
#include "OnionBase.h"
class OnionLetter
{
public:
static int numInstances;
OnionLetter();
~OnionLetter();
void addCurve(std::vector<glm::vec2>& curve, GLfloat resolution, GLfloat thickness, bool connected);
void addCurve(GLfloat x0, GLfloat y0,
GLfloat x1, GLfloat y1,
GLfloat x2, GLfloat y2,
GLfloat x3, GLfloat y3,
GLfloat resolution,
GLfloat thickness,
bool connected);
void addCurve(std::vector<glm::vec2>& leftCurve, std::vector<glm::vec2>& rightCurve, GLfloat resolution);
void addCurve(GLfloat xL0, GLfloat yL0,
GLfloat xL1, GLfloat yL1,
GLfloat xL2, GLfloat yL2,
GLfloat xL3, GLfloat yL3,
GLfloat xR0, GLfloat yR0,
GLfloat xR1, GLfloat yR1,
GLfloat xR2, GLfloat yR2,
GLfloat xR3, GLfloat yR3,
GLfloat resolution);
void addCurve();
int newCurve();
GLfloat* getSegment(unsigned int segmentIndex, int stopIndex = -1);
GLfloat* getSegment(unsigned int segmentIndex, int stopIndex, glm::mat4 trans);
unsigned int segmentSize(unsigned int segmentIndex);
#pragma warning( suppress : 4267 )
unsigned int numSegments() { return segments.size(); };
unsigned int numVertices();
void printVertices();
GLfloat getWidth() { return width; };
private:
std::vector<GLfloat*> segments;
std::vector<unsigned int> sizes;
GLfloat* returnValue;
GLfloat width;
GLfloat angleDifference(GLfloat low, GLfloat high);
GLfloat angleMidpoint(GLfloat low, GLfloat high);
GLfloat clampAngle(GLfloat angle);
};
#endif // ONIONLETTER_H
|
Python
|
UTF-8
| 607 | 3.40625 | 3 |
[] |
no_license
|
class Vehiculo():
def __init__(self,color, modelo, placa, nro_asientos):
self.color = color
self.modelo = modelo
self.placa = placa
self.nroasientos = nro_asientos
def desplazarse(self):
print("El vehiculo se esta desplazando")
def subirpersona(self):
print("La persona ha subido")
def __str__(self):
return "color: {}, modelo: {}, placa: {},nro_asientos{}".format(self.color,
self.modelo, self.placa,self.nro_asientos)
vehiculo_1 = Vehiculo("Negro", "1997", "ADF123", 4)
vehiculo_1.desplazarse()
vehiculo_1.subirpersona()
|
JavaScript
|
UTF-8
| 3,852 | 3.828125 | 4 |
[] |
no_license
|
/**
้้กบๅบๆฐๆฎๆบๆ --- ๆ
ๆ ็ปๆๅ
ๅซไธ็ณปๅ็ถๅญๅ
ณ็ณป็่็น๏ผๆฏไธช่็น้ฝๆไธไธช็ถ่็น
ไปฅๅ0ไธชๆ่
ๅคไธชๅญ่็น
ๆ ้กถ้จ็่็นๅซๅๆ น่็น
่็นๅไธบๅ
้จ่็นๅๅค้จ่็น๏ผ่ณๅฐๆไธไธชๅญๅ
็ด ็่็น็งฐไธบๅ
้จ่็น๏ผๆฒกๆๅญๅ
็ด ็
่็น็งฐไธบๅค้จ่็นๆ่
ๅถ่็น๏ผ
ไธไธช่็นๅฏไปฅๆ็ฅๅ
ๅๅไปฃ๏ผ็ฅๅ
ๅ
ๆฌ็ถ่็นใ็ฅ็ถ่็นใๆพ็ฅ็ถ่็น
ๅญๆ ๆฏ็ฑ่็นๅๅฎ็ๅไปฃๆๆ๏ผ
่็น็ไธไธชๅฑๆงๆฏๆทฑๅบฆ๏ผ่็น็ๆทฑๅบฆๅๅณไบๅฎ็็ฅๅ
่็น็ๆฐ้๏ผ
ๆ ็้ซๅบฆๅๅณไบ่็นๆทฑๅบฆ็ๆๅคงๅผ๏ผๆ น่็นๅจ็ฌฌ0ๅฑ๏ผ
ไบๅๆ ็่็นๆๅคๅช่ฝๆไธคไธชๅญ่็น๏ผไธไธชๆฏๅทฆไพงๅญ่็น๏ผๅฆไธไธชๆฏๅณไพงๅญ่็น--ๆๅฉไบ
ๆไปฌๅๆๆด้ซๆ็ๅใไปๆ ไธญๆๅ
ฅใๆฅๆพๅๅ ้ค่็น็็ฎๆณ๏ผ
ไบๅๆ็ดขๆ bstๆฏไบๅๆ ็ไธ็ง๏ผๅทฆไพง่็นๅญๅจๆฏ็ถ่็นๅฐ็ๅผ๏ผๅณไพง่็นๅญๅจๆฏ็ถ่็น
ๅคงๆ่
็ญไบ็ถ่็น็ๅผใ
ๆ ็่็นไนๅซๅ้ฎใ
*/
function BinarySearchTree() {
var Node = function (key) {
this.key = key
this.left = null
this.right = null
}
var insertNode = function (node, newNode) {
if (newNode.key < node.key) {
if (node.left === null) {
node.left = newNode
} else {
insertNode(node.left, newNode)
}
} else {
if (node.right === null) {
node.right = newNode
} else {
insertNode(node.right, newNode)
}
}
}
var root = null
this.insert = function (key) {
var newNode = new Node(key)
if (root === null) {
root = newNode
} else {
insertNode(root, newNode)
}
}
this.inOrderTraverseNode = function(callback) {
inOrderTraverseNode(root,callback)
}
this.preOrderTraverseNode = function(callback) {
preOrderTraverseNode(root,callback)
}
this.postOrderTraverseNode = function(callback) {
postOrderTraverseNode(root,callback)
}
// ไธญๅบ
var inOrderTraverseNode = function(node,callback) {
if(node !== null) {
inOrderTraverseNode(node.left,callback)
callback(node.key)
inOrderTraverseNode(node.right,callback)
}
}
// ๅ
ๅบ
var preOrderTraverseNode = function(node,callback) {
if(node !== null) {
callback(node.key)
preOrderTraverseNode(node.left,callback)
preOrderTraverseNode(node.right,callback)
}
}
// ๅๅบ
var postOrderTraverseNode = function(node,callback) {
if(node !== null) {
postOrderTraverseNode(node.left,callback)
postOrderTraverseNode(node.right,callback)
callback(node.key)
}
}
}
var tree = new BinarySearchTree()
tree.insert(11)
tree.insert(7)
tree.insert(15)
tree.insert(5)
tree.insert(3)
tree.insert(9)
tree.insert(8)
tree.insert(10)
tree.insert(13)
tree.insert(12)
tree.insert(14)
tree.insert(20)
tree.insert(18)
tree.insert(25)
tree.insert(6)
/**
* ๆ ็้ๅ
*
* ไธญๅบ้ๅ
* ไธญๅบ้ๅๆฏไปฅไธ่ก้กบๅบ่ฎฟ้ฎbstๆๆ่็น็้ๅๆนๆณ๏ผไปๆๅฐๅฐๆๅคง็้กบๅบ่ฎฟ้ฎ
* ๆๆ็่็นใๅบ็จ-ๆ ็bstๆ ็ๆๅบ๏ผ
*
* ๅ
ๅบ้ๅ
* ๅ
ๅบ้ๅๆฏไปฅไผๅ
ไบๅไปฃ่็น็้กบๅบ่ฎฟ้ฎๆฏไธช่็น็๏ผๅบ็จ-ๆๅฐไธไธช็ปๆๅๆๆกฃใ
*
* ๅๅบ้ๅ
* ๅๅบ้ๅๆฏๅ
่ฎฟ้ฎ่็น็ๅไปฃ่็น๏ผๅ่ฎฟ้ฎ่็นๆฌ่บซใๅบ็จ--่ฎก็ฎไธไธช็ฎๅฝๅๅฎ
* ็ๅญ็ฎๅฝไธญๆๆๆไปถๆๅ ็ฉบ้ดๅคงๅฐ
*
*/
function printNode(value) {
console.log(value)
}
// tree.inOrderTraverseNode(printNode)
// tree.preOrderTraverseNode(printNode)
tree.postOrderTraverseNode(printNode)
|
C++
|
UTF-8
| 832 | 2.546875 | 3 |
[] |
no_license
|
#ifndef cpu_h
#define cpu_h
#include <ucontext.h>
#include <iostream>
#include "traits.h"
__BEGIN_API
class CPU
{
public:
class Context
{
private:
static const unsigned int STACK_SIZE = Traits<CPU>::STACK_SIZE;
public:
Context() { _stack = 0; } //Construtor
Context(void (* func)(Tn ...), Tn ... an); //Modelo 2 Construtor //implementar
~Context(); //Destrutor //implementar
void save(); //implementar
void load(); //implementar
private:
char *_stack;
public:
ucontext_t _context; //tipo contexto da biblioteca ucontext.h
};
public:
static void switch_context(Context *from, Context *to); //implementar, mรฉtodo da CPU
};
__END_API
#endif
|
C++
|
UTF-8
| 9,509 | 2.5625 | 3 |
[] |
no_license
|
#include "SoyDecklink.h"
#include "SoyTypes.h" // Platform::IsOkay
#include "SoyCfString.h"
// include the API source
#include "DecklinkSdk/Mac/include/DeckLinkAPIDispatch.cpp"
/*
The DeckLink API can be accessed from a sandboxed applications if the following requirements are met:
Application is built against Mac OS X 10.7 or later
Ensure Enable App sandboxing is ticked in your applications Xcode project,
Ensure you have selected a valid code signing identity,
Insert the following property into your applications entitlements file: Refer to the Sandboxed Signal Generator target in the SignalGenerator sample application in the SDK.
key
com.apple.security.temporaryexception.mach-lookup.globalname
value
com.blackmagic-design.desktopvideo. DeckLinkHardwareXPCService
Further information can be found in the App Sandbox Design Guide available on Apples Mac Developer Library website
*/
namespace Decklink
{
TContext& GetContext();
std::string GetSerial(IDeckLink& Device,size_t Index);
std::shared_ptr<TContext> gContext;
}
std::ostream& operator<<(std::ostream &out,const DecklinkString& in)
{
#if defined(TARGET_OSX)
out << Soy::GetString(in);
#else
out << in;
#endif
return out;
}
std::shared_ptr<TMediaExtractor> Decklink::AllocExtractor(const TMediaExtractorParams& Params)
{
// let this return null if no match
try
{
std::shared_ptr<TMediaExtractor> Extractor( new TExtractor(Params) );
return Extractor;
}
catch(std::exception& e)
{
std::Debug << e.what() << std::endl;
return nullptr;
}
}
bool MatchSerial(const std::string& Serial,const std::string& Match)
{
if ( Match == "*" )
return true;
if ( Soy::StringContains( Serial, Match, false ) )
return true;
return false;
}
void Decklink::EnumDevices(std::function<void(const std::string&)> AppendName)
{
auto Filter = [&](Soy::AutoReleasePtr<IDeckLink>& Input,const std::string& Serial)
{
AppendName( Serial );
};
auto& Context = GetContext();
Context.EnumDevices( Filter );
}
Decklink::TContext& Decklink::GetContext()
{
if ( !gContext )
gContext.reset( new TContext );
return *gContext;
}
Decklink::TContext::TContext()
{
}
Decklink::TContext::~TContext()
{
}
Soy::AutoReleasePtr<IDeckLinkIterator> Decklink::TContext::GetIterator()
{
// gr: previously, for windows implementation, we created one at the start of the context
// on OSX a second traversal of the same iterator found nothing.
// need to create and dispose
Soy::AutoReleasePtr<IDeckLinkIterator> Iterator;
#if defined(TARGET_WINDOWS)
// gr: judging from the samples, when this is missing, it's because the drivers are not installed. (verified by me)
auto Result = CoCreateInstance( CLSID_CDeckLinkIterator, nullptr, CLSCTX_ALL, IID_IDeckLinkIterator, (void**)&mIterator.mObject );
Platform::IsOkay( Result, "No decklink driver installed.");
#else
Iterator.Set( CreateDeckLinkIteratorInstance(), true );
#endif
if ( !Iterator )
throw Soy::AssertException("Decklink iterator is null");
return Iterator;
}
std::string Decklink::GetSerial(IDeckLink& Device,size_t Index)
{
// gr: argh overflow worries
DecklinkString DisplayName = nullptr;
DecklinkString ModelName = nullptr;
std::stringstream Serial;
auto Result = Device.GetDisplayName( &DisplayName );
if ( Result == S_OK && DisplayName )
{
Serial << DisplayName;
return Serial.str();
}
Result = Device.GetModelName( &ModelName );
if ( Result == S_OK && ModelName )
{
Serial << ModelName;
return Serial.str();
}
// no serial...
Serial << Index;
return Serial.str();
}
void Decklink::TContext::EnumDevices(std::function<void(Soy::AutoReleasePtr<IDeckLink>&,const std::string&)> EnumDevice)
{
auto Iterator = GetIterator();
Soy::Assert( Iterator!=nullptr, "Iterator expected" );
IDeckLink* CurrentDevice = nullptr;
size_t CurrentDeviceIndex = 0;
while ( true )
{
try
{
auto Result = Iterator->Next( &CurrentDevice );
if ( CurrentDevice == nullptr )
break;
Platform::IsOkay( Result, "Enumerating devices");
Soy::AutoReleasePtr<IDeckLink> Device( CurrentDevice, false );
// check it's an input
Soy::AutoReleasePtr<IDeckLinkInput> DeviceInput;
Result = Device->QueryInterface( IID_IDeckLinkInput, (void**)&DeviceInput.mObject );
if ( Result != S_OK )
continue;
auto Serial = GetSerial( *Device, CurrentDeviceIndex );
EnumDevice( Device, Serial );
}
catch(std::exception& e)
{
std::Debug << "Error enumerating device; " << e.what() << std::endl;
break;
}
}
}
Soy::AutoReleasePtr<IDeckLink> Decklink::TContext::GetDevice(const std::string& MatchSerial)
{
Soy::AutoReleasePtr<IDeckLink> MatchingDevice;
auto Filter = [&](Soy::AutoReleasePtr<IDeckLink>& Input,const std::string& Serial)
{
if ( !::MatchSerial( Serial, MatchSerial ) )
return;
MatchingDevice = Input;
};
EnumDevices( Filter );
if ( !MatchingDevice )
{
std::stringstream Error;
Error << "No decklink devices matching " << MatchSerial;
throw Soy::AssertException( Error.str() );
}
return MatchingDevice;
}
Decklink::TExtractor::TExtractor(const TMediaExtractorParams& Params) :
TMediaExtractor ( Params ),
mRefCount ( 1 )
{
mDevice = GetContext().GetDevice( Params.mFilename );
StartCapture();
Start();
}
void Decklink::TExtractor::StartCapture()
{
Soy::AutoReleasePtr<IDeckLinkInput> DeviceInput;
auto Result = mDevice->QueryInterface( IID_IDeckLinkInput, (void**)&DeviceInput.mObject );
if ( Result != S_OK )
throw Soy::AssertException("Failed to get decklink input");
// get modes
Array<IDeckLinkDisplayMode*> modeList;
{
Soy::AutoReleasePtr<IDeckLinkDisplayModeIterator> displayModeIterator;
Result = DeviceInput->GetDisplayModeIterator(&displayModeIterator.mObject);
if ( Result != S_OK )
throw Soy::AssertException("Failed to get display mode iterator");
// needs release?
IDeckLinkDisplayMode* displayMode = NULL;
while (displayModeIterator->Next(&displayMode) == S_OK)
modeList.PushBack(displayMode);
}
// Enable input video mode detection if the device supports it
//BMDVideoInputFlags videoInputFlags = supportFormatDetection ? bmdVideoInputEnableFormatDetection : bmdVideoInputFlagDefault;
BMDVideoInputFlags videoInputFlags = bmdVideoInputFlagDefault;
// Set the screen preview
DeviceInput->SetScreenPreviewCallback(this);
// Set capture callback
DeviceInput->SetCallback(this);
BufferArray<_BMDPixelFormat,2> PixelFormats;
PixelFormats.PushBack(bmdFormat8BitBGRA);
PixelFormats.PushBack(bmdFormat8BitYUV);
auto GetCompatibleVideoMode = [&](_BMDPixelFormat Format)
{
for ( int i=0; i<modeList.GetSize(); i++ )
{
auto* VideoMode = modeList[i];
// Set the video input mode
//auto PixelFormat = bmdFormat10BitYUV;
auto PixelFormat = bmdFormat8BitBGRA;
Result = DeviceInput->EnableVideoInput(VideoMode->GetDisplayMode(), PixelFormat, videoInputFlags);
if ( Result != S_OK)
{
continue;
//throw Soy::AssertException("unable to select the video mode. Perhaps device is currently in-use");
}
return VideoMode;
}
throw Soy::AssertException("Failed to get video mode");
};
_BMDPixelFormat PixelFormat;
IDeckLinkDisplayMode* VideoMode = nullptr;
for ( int pm=0; pm<PixelFormats.GetSize(); pm++ )
{
try
{
VideoMode = GetCompatibleVideoMode( PixelFormats[pm] );
PixelFormat = PixelFormats[pm];
break;
}
catch(std::exception& e)
{
}
}
if ( !VideoMode )
throw Soy::AssertException("Failed to get video mode");
// Start the capture
Result = DeviceInput->StartStreams();
if ( Result != S_OK)
throw Soy::AssertException("Failed to start capture");
}
void Decklink::TExtractor::GetStreams(ArrayBridge<TStreamMeta>&& Streams)
{
/*
TStreamMeta Meta;
Meta.mStreamIndex = 0;
Meta.mCodec = SoyMediaFormat::RGB;
Streams.PushBack( Meta );
*/
}
std::shared_ptr<TMediaPacket> Decklink::TExtractor::ReadNextPacket()
{
// OnPacketExtracted( Packet.mTimecode, Packet.mMeta.mStreamIndex );
return nullptr;
}
HRESULT Decklink::TExtractor::DrawFrame (/* in */ IDeckLinkVideoFrame *theFrame)
{
std::Debug << __func__ << std::endl;
return S_OK;
}
HRESULT Decklink::TExtractor::VideoInputFormatChanged (/* in */ BMDVideoInputFormatChangedEvents notificationEvents, /* in */ IDeckLinkDisplayMode *newDisplayMode, /* in */ BMDDetectedVideoInputFormatFlags detectedSignalFlags)
{
std::Debug << __func__ << std::endl;
return S_OK;
}
HRESULT Decklink::TExtractor::VideoInputFrameArrived (/* in */ IDeckLinkVideoInputFrame* videoFrame, /* in */ IDeckLinkAudioInputPacket* audioPacket)
{
std::Debug << __func__ << std::endl;
return S_OK;
}
HRESULT Decklink::TExtractor::QueryInterface (REFIID iid, LPVOID *ppv)
{
CFUUIDBytes iunknown;
HRESULT result = E_NOINTERFACE;
// Initialise the return result
*ppv = NULL;
// Obtain the IUnknown interface and compare it the provided REFIID
iunknown = CFUUIDGetUUIDBytes(IUnknownUUID);
if (memcmp(&iid, &iunknown, sizeof(REFIID)) == 0)
{
*ppv = this;
AddRef();
result = S_OK;
}
else if (memcmp(&iid, &IID_IDeckLinkDeviceNotificationCallback, sizeof(REFIID)) == 0)
{
*ppv = (IDeckLinkDeviceNotificationCallback*)this;
AddRef();
result = S_OK;
}
return result;
}
ULONG Decklink::TExtractor::AddRef (void)
{
return ++mRefCount;
}
ULONG Decklink::TExtractor::Release (void)
{
auto NewValue = --mRefCount;
if ( NewValue == 0 )
{
delete this;
return 0;
}
return NewValue;
}
|
C#
|
UTF-8
| 3,558 | 2.59375 | 3 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using TwitterUtils;
namespace TwitterSentimentAnalysisApp.Controllers
{
[RoutePrefix("api/sentiment")]
public class TwitterSentimentAnalysisController : ApiController
{
// POST api/sentiment/predict
[Route("predict")]
[HttpPost]
public async Task<string> PredictTweet(PredictTweetModel model)
{
var result = await this.PredictTweetsAsync(new List<string> { model.Tweet });
return result;
}
// POST api/sentiment/study
[Route("study")]
[HttpPost]
public async Task<string> StudyTermAsync(StudyTermModel model)
{
// Get tweets of the term
var twitterSearcher = new TwitterSearcher();
var tweets = await twitterSearcher.GetTweetsAsync(model.Term, 100).ConfigureAwait(false);
// Analyze Tweets
var result = await this.PredictTweetsAsync(tweets);
return result;
}
// POST api/sentiment/compare
[Route("compare")]
[HttpPost]
public async Task<List<string>> CompareTerms(CompareTermsModel model)
{
// Get tweets of the term
var twitterSearcher = new TwitterSearcher();
var results = new List<string>();
foreach(var term in model.Terms)
{
var result = await this.StudyTermAsync(new StudyTermModel { Term = term });
results.Add(result);
}
return results;
}
private async Task<string> PredictTweetsAsync(IEnumerable<string> tweets)
{
using (var client = new HttpClient())
{
var values = tweets.Select(t => new string[] {"0", t }).ToArray();
var scoreRequest = new
{
Inputs = new Dictionary<string, StringTable>()
{
{ "input1", new StringTable { ColumnNames = new string[] {"sentiment_label", "tweet_text"}, Values = values } }
},
GlobalParameters = new Dictionary<string, string>() { }
};
const string apiKey = "8ffKLuBmU1UPp0QClqTTmUbaxbLGZqitJMGvxwBw6xr/3UAHB/Cmh+Druo6BAuyFt0KfF/0YF4Huqw82L6kgkg==";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/206c1d97815f414caa21cd657c1f3119/services/3d3a0b4d5af34e5a91d0b0f250754d10/execute?api-version=2.0&details=true");
var response = await client.PostAsJsonAsync("", scoreRequest).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return result;
}
}
}
public class PredictTweetModel
{
public string Tweet { get; set; }
}
public class StudyTermModel
{
public string Term { get; set; }
}
public class CompareTermsModel
{
public string[] Terms { get; set; }
}
public class StringTable
{
public string[] ColumnNames { get; set; }
public string[][] Values { get; set; }
}
}
|
Java
|
UTF-8
| 6,680 | 2.015625 | 2 |
[] |
no_license
|
package com.example.nguyenhuutu.convenientmenu.manage_menu;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import com.example.nguyenhuutu.convenientmenu.Const;
import com.example.nguyenhuutu.convenientmenu.Fragment.Fragment_Drink;
import com.example.nguyenhuutu.convenientmenu.Fragment.Fragment_Food;
import com.example.nguyenhuutu.convenientmenu.Fragment.PagerAdapterRestaurant;
import com.example.nguyenhuutu.convenientmenu.R;
import com.example.nguyenhuutu.convenientmenu.manage_menu.add_dish.AddDish;
import com.example.nguyenhuutu.convenientmenu.helper.Helper;
import com.example.nguyenhuutu.convenientmenu.helper.UserSession;
public class Manage_Menu extends Fragment {
ViewPager viewpager;
PagerAdapterRestaurant pagerAdapterRestaurant;
Fragment_Food food;
Fragment_Drink drink;
ImageButton imgAdd;
@SuppressLint("ValidFragment")
public Manage_Menu()
{
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_manage__menu, container, false);
// get restAccount
UserSession rest = Helper.getLoginedUser(getActivity());
String restAccount = rest.getUsername();
food = new Fragment_Food(restAccount);
drink = new Fragment_Drink(restAccount);
imgAdd = view.findViewById(R.id.imgAdd);
imgAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent addDishIntent = new Intent(getActivity(), AddDish.class);
startActivityForResult(addDishIntent, Const.ADD_DISH);
}
});
// Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbarManage);
/*setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);*/
/*toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onDestroy();
}
});*/
viewpager = (ViewPager) view.findViewById(R.id.view_pager_menu);
final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabMenu);
pagerAdapterRestaurant = new PagerAdapterRestaurant(getChildFragmentManager());
pagerAdapterRestaurant.AddFragment(food, "Mรณn ฤn");
pagerAdapterRestaurant.AddFragment(drink, "Thแปฉc uแปng");
viewpager.setOffscreenPageLimit(2);
viewpager.setAdapter(pagerAdapterRestaurant);
tabLayout.setupWithViewPager(viewpager);
EditText search_Dish = (EditText) view.findViewById(R.id.search_Dish);
search_Dish.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (tabLayout.getTabAt(0).isSelected()) {
Fragment_Food.adapter.filter(s);
} else {
Fragment_Drink.adapter.filter(s);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
// ImageView imagePopupMenu = (ImageView) view.findViewById(R.id.imgAdd);
// imagePopupMenu.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// //Thรชm mรณn mแปi
// }
// });
return view;
}
public void updateFoodList(String _dishId, int action, boolean _changeDishType) {
if (action == Const.ADD_DISH) {
food.addDishIntoList(_dishId);
}
else if (action == Const.EDIT_DISH) {
if (_changeDishType == true) {
drink.removeDishInList(_dishId);
food.addDishIntoList(_dishId);
// drink.notifyDataChanged();
}
else {
food.updateDishInList(_dishId);
}
}
// food.notifyDataChanged();
}
public void updateDrinkList(String _dishId, int action, boolean _changeDishType) {
if (action == Const.ADD_DISH) {
drink.addDishIntoList(_dishId);
}
else if (action == Const.EDIT_DISH) {
if (_changeDishType == true) {
food.removeDishInList(_dishId);
drink.addDishIntoList(_dishId);
// food.notifyDataChanged();
}
else {
drink.updateDishInList(_dishId);
}
}
// drink.notifyDataChanged();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Const.ADD_DISH) {
if (data != null && data.getExtras() != null && data.getExtras().containsKey("isFood")) {
if (data.getExtras().getBoolean("isFood") == true) {
updateFoodList(data.getExtras().get("dishId").toString(), Const.ADD_DISH, false);
}
else{
updateDrinkList(data.getExtras().get("dishId").toString(), Const.ADD_DISH, false);
}
}
}
else if (requestCode == Const.EDIT_DISH){
if (data != null && data.getExtras() != null && data.getExtras().containsKey("isFood")) {
if (data.getExtras().getBoolean("isFood") == true) {
updateFoodList(data.getExtras().get("dishId").toString(), Const.EDIT_DISH, data.getExtras().getBoolean("changeDishType"));
}
else{
updateDrinkList(data.getExtras().get("dishId").toString(), Const.EDIT_DISH, data.getExtras().getBoolean("changeDishType"));
}
}
}
}
}
|
Java
|
UTF-8
| 511 | 3.125 | 3 |
[] |
no_license
|
package com.company;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("ะะฒะตะดะธัะต ะบะพะปะธัะตััะฒะพ ัะธัะตะป ะฒ ะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััะธ: ");
int count = sc.nextInt();
for( int i = 0; i < count; i++ ){
int a = sc.nextInt();
if( a > 10 && a < 20){
System.out.println(a);
}
}
}
}
|
TypeScript
|
UTF-8
| 3,288 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
export module GOOGLE_MAP_HELPER {
export let AUTO_COMPLETECOMPLETE_TYPE = {
ADDRESS: 'address',
ESTABLISHMENT: 'establishment',
GEOCODE: 'geocode'
};
export let PLACE_TYPE = {
STREET_NUMBER: 'street_number',
ROUTE: 'route',
SUBLOCALITY_LEVEL_1: 'sublocality_level_1',
ADMINISTRATIVE_AREA_LEVEL_2: 'administrative_area_level_2',
ADMINISTRATIVE_AREA_LEVEL_1: 'administrative_area_level_1',
COUNTRY: 'country',
POSTAL_CODE: 'postal_code'
};
export function GetGoolePlaceInfo(place: any): GooglePlaceInfo {
let googlePlaceInfo = new GooglePlaceInfo();
googlePlaceInfo.id = place.place_id;
googlePlaceInfo.name = place.name;
googlePlaceInfo.url = place.url;
if (place.geometry !== undefined && place.geometry !== null) {
googlePlaceInfo.latitude = place.geometry.location.lat();
googlePlaceInfo.longitude = place.geometry.location.lng();
}
if (place.address_components !== undefined && place.address_components !== null) {
for (let i = 0; i < place.address_components.length; i++) {
let addressComponent = place.address_components[i];
switch (addressComponent.types[0]) {
case PLACE_TYPE.STREET_NUMBER: googlePlaceInfo.street_number = addressComponent.short_name; break;
case PLACE_TYPE.ROUTE: googlePlaceInfo.street_name = addressComponent.short_name; break;
case PLACE_TYPE.SUBLOCALITY_LEVEL_1: googlePlaceInfo.ward = addressComponent.short_name; break;
case PLACE_TYPE.ADMINISTRATIVE_AREA_LEVEL_2: googlePlaceInfo.district = addressComponent.short_name; break;
case PLACE_TYPE.ADMINISTRATIVE_AREA_LEVEL_1: googlePlaceInfo.city = addressComponent.short_name; break;
case PLACE_TYPE.COUNTRY: googlePlaceInfo.country = addressComponent.short_name; break;
case PLACE_TYPE.POSTAL_CODE: googlePlaceInfo.postal_code = addressComponent.short_name; break;
}
}
}
googlePlaceInfo.formatted_address = place.formatted_address;
return googlePlaceInfo;
}
export class GooglePlaceInfo {
public id: string;
public street_number: string;
public street_name: string;
public ward: string;
public district: string;
public city: string;
public country: string;
public postal_code: string;
public latitude: number;
public longitude: number;
public url: string;
public name: string;
//Use For Exactly google API
public formatted_address: string;
public get full_address(): string {
let address = '';
if (this.street_number !== '') {
address += this.street_number + ' ';
}
if (this.street_name !== '') {
address += this.street_name;
}
if (this.ward !== '') {
address += ', ' + this.ward + ', ';
}
if (this.district !== '') {
address += this.district + ', ' + this.city;
}
return address;
}
constructor() {
this.name = '';
this.street_number = '';
this.street_name = '';
this.ward = '';
this.district = '';
this.city = '';
this.country = '';
this.postal_code = '';
this.latitude = 0;
this.longitude = 0;
this.url = '';
this.formatted_address = '';
}
}
}
|
TypeScript
|
UTF-8
| 4,083 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
import {ObservableValue} from "./observablevalue";
import {ComputedValue} from "../core/computedvalue";
import {ValueMode, AsStructure} from "./modifiers";
import {Lambda, invariant, assertPropertyConfigurable, isPlainObject} from "../utils/utils";
import {SimpleEventEmitter} from "../utils/simpleeventemitter";
import {getNextId} from "../core/globalstate";
import {throwingComputedValueSetter} from "../api/computeddecorator";
export interface IObjectChange<T, R> {
name: string;
object: R;
type: string;
oldValue?: T;
}
const ObservableObjectMarker = {};
export interface IObservableObjectAdministration {
type: Object;
target: any;
name: string;
id: number;
mode: ValueMode;
values: {[key: string]: ObservableValue<any>|ComputedValue<any>};
events: SimpleEventEmitter;
}
export interface IIsObservableObject {
$mobx: IObservableObjectAdministration;
}
export function asObservableObject(target, name: string, mode: ValueMode = ValueMode.Recursive): IObservableObjectAdministration {
if (target.$mobx) {
if (target.$mobx.type !== ObservableObjectMarker)
throw new Error("The given object is observable but not an observable object");
return target.$mobx;
}
if (!isPlainObject(target))
name = target.constructor.name;
if (!name)
name = "ObservableObject";
const adm: IObservableObjectAdministration = {
type: ObservableObjectMarker,
values: {},
events: undefined,
id: getNextId(),
target, name, mode
};
Object.defineProperty(target, "$mobx", {
enumerable: false,
configurable: false,
writable: false,
value: adm
});
return adm;
}
export function setObservableObjectProperty(adm: IObservableObjectAdministration, propName: string, value) {
if (adm.values[propName])
adm.target[propName] = value; // the property setter will make 'value' reactive if needed.
else
defineObservableProperty(adm, propName, value);
}
function defineObservableProperty(adm: IObservableObjectAdministration, propName: string, value) {
assertPropertyConfigurable(adm.target, propName);
let observable: ComputedValue<any>|ObservableValue<any>;
let name = `${adm.name}@${adm.id} / Prop "${propName}"`;
let isComputed = true;
if (typeof value === "function" && value.length === 0)
observable = new ComputedValue(value, adm.target, false, name);
else if (value instanceof AsStructure && typeof value.value === "function" && value.value.length === 0)
observable = new ComputedValue(value.value, adm.target, true, name);
else {
isComputed = false;
observable = new ObservableValue(value, adm.mode, name);
}
adm.values[propName] = observable;
Object.defineProperty(adm.target, propName, {
configurable: true,
enumerable: !isComputed,
get: function() {
return observable.get();
},
set: isComputed
? throwingComputedValueSetter
: function(newValue) {
const oldValue = (observable as any).value;
if (observable.set(newValue) && adm.events !== undefined) {
adm.events.emit(<IObjectChange<any, any>> {
type: "update",
object: this,
name: propName,
oldValue
});
}
}
});
if (adm.events !== undefined) {
adm.events.emit(<IObjectChange<any, any>> {
type: "add",
object: adm.target,
name: propName
});
};
}
/**
* Observes this object. Triggers for the events 'add', 'update' and 'delete'.
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe
* for callback details
*/
export function observeObservableObject(object: IIsObservableObject, callback: (changes: IObjectChange<any, any>) => void, fireImmediately?: boolean): Lambda {
invariant(isObservableObject(object), "Expected observable object");
invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable objects.");
const adm = object.$mobx;
if (adm.events === undefined)
adm.events = new SimpleEventEmitter();
return object.$mobx.events.on(callback);
}
export function isObservableObject(thing): boolean {
return thing && thing.$mobx && thing.$mobx.type === ObservableObjectMarker;
}
|
Python
|
UTF-8
| 526 | 4.65625 | 5 |
[] |
no_license
|
"""
Bubble Sort
"""
def bubbleSort():
arr = [3, 1, 5, 8, 11, 10]
n = len(arr)
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print("Bubble Sort")
printArray(arr)
def printArray(arr):
for i in range(len(arr)):
print("%d " % arr[i])
print('\n')
if __name__ == "__main__":
print("Unsorted Array : ", [3, 1, 5, 8, 11, 10])
bubbleSort()
|
Java
|
UTF-8
| 781 | 2.171875 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classes;
import interfaces.IDatabase;
import interfaces.IFileArchive;
import interfaces.IType;
/**
*
* @author vfgya_000
*/
public class Type implements IType{
@Override
public IDatabase database() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public IFileArchive fileArchive() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
Python
|
UTF-8
| 1,076 | 3.140625 | 3 |
[] |
no_license
|
import boto3
def Stack_choice():
global Stack_choosen
while True:
print("\n1. Document Service - WS")
print("2. Document Service - Consumer")
Stack_choosen = input("Enter your Choice: ")
try:
int(Stack_choosen)
except ValueError:
print("This is not a number")
continue
if int(Stack_choosen) in range(1,3):
print(Stack_choosen +" is choosen")
CF_choice()
break
else:
print("Invalid Choice")
def CF_choice():
while True:
print("\n1. Create Stack")
print("2. Update Stack")
print("3. Delete Stack")
CF_choosen = input("Enter your Choice: ")
try:
int(CF_choosen)
except ValueError:
print("This is not a number")
continue
if int(CF_choosen) in range(1,4):
print(CF_choosen +" is choosen")
break
else:
print("Invalid Choice")
if int(CF_choosen) == 1:
Create_Stack()
if int(CF_choosen) == 2:
Update_Stack()
if int(CF_choosen) == 3:
Delete_Stack()
def Create_Stack()
client = boto3.client('cloudformation')
def main():
Stack_choosen = 0
Stack_choice()
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 1,922 | 2.046875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* 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.jbpm.process.instance.context;
import java.io.Serializable;
import org.jbpm.process.core.Context;
import org.jbpm.process.instance.ContextInstance;
import org.jbpm.process.instance.ContextInstanceContainer;
import org.jbpm.process.instance.ProcessInstance;
public abstract class AbstractContextInstance implements ContextInstance, Serializable {
private long contextId;
private ContextInstanceContainer contextInstanceContainer;
private ProcessInstance processInstance;
public long getContextId() {
return contextId;
}
public void setContextId(long contextId) {
this.contextId = contextId;
}
public ContextInstanceContainer getContextInstanceContainer() {
return contextInstanceContainer;
}
public void setContextInstanceContainer(ContextInstanceContainer contextInstanceContainer) {
this.contextInstanceContainer = contextInstanceContainer;
}
public Context getContext() {
return getContextInstanceContainer().getContextContainer().getContext(getContextType(), getContextId());
}
public ProcessInstance getProcessInstance() {
return processInstance;
}
public void setProcessInstance(ProcessInstance processInstance) {
this.processInstance = processInstance;
}
}
|
C++
|
UTF-8
| 3,945 | 2.640625 | 3 |
[] |
no_license
|
#include <AccelStepper.h>
#define HOME_BUTTON 8
#define FLIP_DIR_BUTTON 9
#define PAUSE_RUN_SWITCH 10
#define MAN_AUTO_SWITCH 11
#define VELOCITY_POT A0
#define DISTANCE_POT A1
#define MOTOR_DIR 2
#define MOTOR_STEP 3
#define MAX_DISTANCE 15325
#define MAX_DV 1
#define MAX_SPEED 500
#define MIN_SPEED 0.1
int stepCounter = 0;
int stepping = false;
int distance = MAX_DISTANCE;
unsigned long lastFlipDebounceTime = 0;
unsigned long lastHomeDebounceTime = 0;
unsigned long debounceDelay = 1;
// Direction Variables
int flipDirState;
int lastFlipDirState = LOW;
boolean inReverse = false;
// Home Button Variables
int homeState;
int lastHomeState = LOW;
boolean autoMode = true;
boolean isOff = true;
static float current_speed = 0.0;
static int analog_read_counter = 1000;
static char sign = 1;
static int analog_value = 0;
AccelStepper stepper(1, 3, 2);
void setup()
{
// Set up the controls
pinMode(HOME_BUTTON, INPUT);
pinMode(FLIP_DIR_BUTTON, INPUT);
pinMode(PAUSE_RUN_SWITCH, INPUT);
pinMode(MAN_AUTO_SWITCH, INPUT);
pinMode(VELOCITY_POT, INPUT);
pinMode(DISTANCE_POT, INPUT);
digitalWrite(HOME_BUTTON, HIGH);
digitalWrite(FLIP_DIR_BUTTON, HIGH);
digitalWrite(PAUSE_RUN_SWITCH, HIGH);
digitalWrite(MAN_AUTO_SWITCH, HIGH);
// Set up the motor
pinMode(MOTOR_DIR, OUTPUT);
pinMode(MOTOR_STEP, OUTPUT);
digitalWrite(MOTOR_DIR, LOW);
digitalWrite(MOTOR_STEP, LOW);
Serial.begin(115200);
}
//helper function to flip direction
void flipDirection(boolean dir) {
inReverse = dir;
digitalWrite(MOTOR_DIR, inReverse);
}
/* TO DO: WRITE ONE FUCTION TO DEBOUNCE BUTTONS */
// Simple debounce to toggle the flip direction pushbutton
void updateDirection() {
int reading = digitalRead(FLIP_DIR_BUTTON);
if (reading != lastFlipDirState) {
lastFlipDebounceTime = millis();
}
if ((millis() - lastFlipDebounceTime) > debounceDelay) {
if (reading != flipDirState) {
flipDirState = reading;
if (flipDirState == LOW) {
flipDirection(!inReverse);
}
}
}
lastFlipDirState = reading;
}
void updateHomeState() {
int reading = digitalRead(HOME_BUTTON);
if (reading != lastHomeState) {
lastHomeDebounceTime = millis();
}
if ((millis() - lastHomeDebounceTime) > debounceDelay) {
if (reading != homeState) {
homeState = reading;
if (homeState == LOW) {
stepCounter = 0;
flipDirection(false);
delay(1000); // Force a pause as user feedback
}
}
}
lastHomeState = reading;
}
void updateDistance() {
distance = map(analogRead(DISTANCE_POT), 0, 1024, 0, MAX_DISTANCE);
}
void readVelocity() {
static float current_speed = 0.0;
static int analog_read_counter = 1000;
static char sign = 1;
static int analog_value = 0;
if (analog_read_counter > 0) {
analog_read_counter--;
} else {
analog_read_counter = 3000;
// now read the pot (from 0 to 1023)
analog_value = analogRead(VELOCITY_POT);
stepper.runSpeed();
current_speed = sign * ((analog_value / 1023.0) * (MAX_SPEED - MIN_SPEED)) + MIN_SPEED;
stepper.setSpeed(current_speed);
}
}
void loop()
{
updateDirection();
updateHomeState();
updateDistance();
// SWITCHES
isOff = digitalRead(PAUSE_RUN_SWITCH);
autoMode = digitalRead(MAN_AUTO_SWITCH);
// POTS
readVelocity();
if (autoMode == LOW) {
//Serial.println("Running Manual");
} else if (autoMode == HIGH) {
//Serial.println("Running Auto");
}
if (isOff == LOW) {
stepping = true;
} else if (isOff == HIGH) {
stepping = false;
}
if (stepping == true) {
stepper.runSpeed();
if (!inReverse) {
stepCounter += 1;
} else {
stepCounter -= 1;
}
Serial.print("step count = "); Serial.print(stepCounter); Serial.print(" || distance = "); Serial.println(distance);
if (stepCounter >= distance || stepCounter <= 0) {
flipDirection(!inReverse);
}
}
}
|
Python
|
UTF-8
| 209 | 2.828125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# -*- coding: utf-8 -*-
class CharacterTokenizer(object):
'''
Character Tokenizer
'''
def __init__(self):
self.vocab = []
def encode(self, sentence):
return list(sentence)
|
C
|
UTF-8
| 519 | 3.421875 | 3 |
[] |
no_license
|
#include<stdio.h>
struct node{
int val;
struct node*next;
};
typedef struct node node;
print_recursive(node *head)
{
if(head==NULL)
return;
print_recursive(head->next);
printf("%d ",head->val);
}
node *addnode(int value)
{
node *xx;
xx=(node *)malloc(sizeof(node));
xx->val=value;
xx->next=NULL;
return xx;
}
int main()
{
node *head;
head=addnode(5);
head->next=addnode(3);
head->next->next=addnode(4);
head->next->next->next=addnode(6);
head->next->next->next->next=addnode(14);
print_recursive(head);
return 0;
}
|
Java
|
UTF-8
| 2,499 | 2.21875 | 2 |
[] |
no_license
|
package api.barrigarest;
import static io.restassured.RestAssured.given;
import java.util.HashMap;
import java.util.Map;
import org.hamcrest.Matchers;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.WebDriver;
import com.deby.util.GenerateDataMass;
import api.barrigarest.core.BaseTest;
import api.barrigarest.core.Constantes;
import funcionais.util.DataUtils;
import funcionais.util.Util;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CRUDConta extends BaseTest{
static GerarToken token = new GerarToken();
private static WebDriver driver;
GenerateDataMass mock = new GenerateDataMass(driver);
@BeforeClass
public static void inicio() {
token.gerarToken();
}
@Test
public void t01_deveIncluirContaSucesso() {
Util.CONTA_ID = given()
// .header("Authorization", "JWT "+ Util.obterToken) tirei pq coloquei no GerarToken para todos os testes
// .body("{\"nome\":\"Silas Marques 3\"}")
.body("{\"nome\":\""+Util.CONTA_NAME+ "\"}")
.when()
.post("/contas")
.then()
.statusCode(201)
.extract().path("id")
;
System.out.print("##############: " + Util.CONTA_ID);
}
@Test
public void t02_deveAlterarConta() {
given()
// .body("{\"nome\":\"Silas Marques Alterado\"}")
.body("{\"nome\":\"" +Util.CONTA_NAME_ALTERADO+ "\"}")
.when()
.put("/contas/"+Util.CONTA_ID)
.then()
.body("nome", Matchers.is(Util.CONTA_NAME_ALTERADO))
;
}
@Test
public void t03_DeveInserirMovimentacao() {
Movimentacao mov = getMovimentacaoValida();
int i = 0;
while(i<=2){
i = i + 1;
mov.setValor(200f +i);
given()
.body(mov)
.when()
.post("/transacoes")
.then()
.log().all()
.statusCode(201)
;
}
}
//-------------------------------------------------------------------------------------------------
private Movimentacao getMovimentacaoValida() {
Movimentacao mov = new Movimentacao();
mov.setConta_id(Util.CONTA_ID);
// mov.setUsuario_id(usuario_id);
mov.setDescricao("Descriรงรฃo da Movimentaรงรฃo pelo Util");
mov.setEnvolvido("Envolvido na movimentaรงรฃo pelo Util");
mov.setTipo("REC");
mov.setData_transacao(DataUtils.getDataDiferencaDias(-1));
mov.setData_pagamento(DataUtils.getDataDiferencaDias(5));
mov.setValor(100f);
mov.setStatus(true);
return mov;
}
}
|
JavaScript
|
UTF-8
| 1,299 | 2.71875 | 3 |
[] |
no_license
|
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/VV1JmMYceJw
// instance mode by Naoto Hieda
var afinn;
var s = function (sketch) {
sketch.preload = function () {
afinn = sketch.loadJSON('afinn111.json');
}
sketch.setup = function () {
sketch.noCanvas();
console.log(afinn);
var txt = sketch.select('#txt');
txt.input(typing);
function typing() {
var textinput = txt.value();
var words = textinput.split(/\W/);
console.log(words);
var scoredwords = [];
var totalScore = 0;
for (var i = 0; i < words.length; i++) {
var word = words[i].toLowerCase();
if (afinn.hasOwnProperty(word)) {
var score = afinn[word];
console.log(word, score);
totalScore += Number(score);
scoredwords.push(word + ': ' + score + ' ');
}
}
var scorePar = sketch.select('#scoreP');
scorePar.html('score: ' + totalScore);
var comp = sketch.select('#comparativeP');
comp.html('comparative: ' + totalScore / words.length);
var wordlist = sketch.select('#wordlistP');
wordlist.html(scoredwords);
//console.log(txt.value());
}
}
sketch.draw = function () {
}
};
var myp5 = new p5(s);
|
Python
|
UTF-8
| 277 | 3.625 | 4 |
[] |
no_license
|
# Greatest Magnitude Solution
#
# To find the greatest magnitude (the greatest distance from 0), I combine max() and abs()
# I call abs() on each num, and find the maximum resulting value using max()
def max_magnitude(nums):
return max(abs(num) for num in nums)
|
Rust
|
UTF-8
| 491 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
use UCSChar;
pub trait CharExtend {
fn to_char_vec(&self) -> Vec<char>;
fn to_u16_vec(&self) -> Vec<u16>;
fn to_u32_vec(&self) -> Vec<u32>;
}
impl CharExtend for str {
fn to_char_vec(&self) -> Vec<char> {
self.chars().map(|c| c).collect()
}
fn to_u16_vec(&self) -> Vec<u16> {
self.encode_utf16().map(|scalar| u16::from_scalar(scalar )).collect()
}
fn to_u32_vec(&self) -> Vec<u32> {
self.chars().map(|c| c as u32).collect()
}
}
|
Swift
|
UTF-8
| 3,439 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
//
// SearchViewController.swift
// dumble-music
//
// Created by Olayemi Abimbola on 12/09/2021.
//
import UIKit
class SearchViewController: UIViewController{
let tableCellId = String(describing: SearchTableViewCell.self)
// let tableHeaderId =
let searchbar: UISearchBar = {
let searchbar = UISearchBar()
searchbar.placeholder = "Search"
searchbar.barTintColor = #colorLiteral(red: 0.09631500393, green: 0.09575008601, blue: 0.09675414115, alpha: 1)
searchbar.tintColor = .red
searchbar.searchTextField.textColor = .white
searchbar.searchTextField.leftView?.tintColor = .white
return searchbar
}()
let tableView = UITableView()
override func viewDidLoad(){
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
tableView.backgroundColor = .black
navigationController?.isNavigationBarHidden = true
tableView.register(UINib(nibName: tableCellId, bundle: nil), forCellReuseIdentifier: tableCellId)
let stackView = UIStackView(arrangedSubviews: [searchbar, tableView])
stackView.axis = .vertical
stackView.spacing = 6
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
// stackView.backgroundColor = .black
}
}
extension SearchViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: tableCellId, for:indexPath) as? SearchTableViewCell else{
fatalError("Omo nah wetin you dey write")
}
let accessoryImage = UIImage(systemName: "ellipsis")
let accessoryView = UIImageView(image: accessoryImage)
accessoryView.tintColor = .white
cell.accessoryView = accessoryView
cell.backgroundColor = .black
return cell
}
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let alert = UIAlertController(title: "another one", message: "What do you mean", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
let action1 = UIAlertAction(title: "yes", style: .cancel, handler: nil)
alert.addAction(action1)
let action2 = UIAlertAction(title: "ney", style: .destructive , handler: nil)
alert.addAction(action2)
present(alert, animated: true, completion: nil)
}
}
extension SearchViewController: UITableViewDelegate{
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return 400
// }
}
|
Java
|
UTF-8
| 802 | 1.921875 | 2 |
[] |
no_license
|
package pl.softwaremill.jozijug.joziawsdemo;
import pl.softwaremill.jozijug.joziawsdemo.impl.sdb.AwsAccessKeys;
import javax.inject.Inject;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* User: szimano
*/
@WebListener
public class Bootstrap implements ServletContextListener {
@Inject
private QueueListener queueListener;
@Inject
private AwsAccessKeys awsAccessKeys;
@Override
public void contextInitialized(ServletContextEvent sce) {
queueListener.start();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
queueListener.stop();
}
}
|
Java
|
UTF-8
| 675 | 2.796875 | 3 |
[] |
no_license
|
package com.design.factory.factory;
import com.design.factory.Vehicle;
import com.design.factory.VehicleFactory;
/**
* @author Zhang Yu
*/
public class CarFactory extends VehicleFactory {
@Override
protected Vehicle createVehicle(String item) {
switch (item) {
case "large":
return new LargeCar();
case "small":
return new SmallCar();
default:
return null;
}
}
public static void main(String[] args) {
VehicleFactory vehicleFactory = new CarFactory();
Vehicle largeCar = vehicleFactory.create("large");
largeCar.product();
}
}
|
Swift
|
UTF-8
| 405 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
//
// ExpressionStatement.swift
// swiftparser
//
// Created by Nuno Silva on 22/06/2021.
//
import Foundation
extension Parser {
func expressionStatement() throws -> StatementProtocol {
let expression = try self.expression()
_ = try self.consume(tokenType: .semicolon, message: "Expected `;' after expression.")
return ExpressionStatement(expression: expression)
}
}
|
Java
|
UTF-8
| 1,145 | 2.125 | 2 |
[] |
no_license
|
package com.blog.entity;
import java.util.List;
/**
* @author lvconl
* ็ฑป่ฏดๆ๏ผ่ฏ่ฎบๅ้กต็ธๅ
ณๅฎไฝ็ฑป
* */
public class CommentPage {
private int currentPage;
private int pageSize;
private int totalCount;
private int totalPage;
private List<Comment> comments;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<Comment> getComment() {
return comments;
}
public void setComment(List<Comment> comments) {
this.comments = comments;
}
}
|
Python
|
UTF-8
| 10,280 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
# use json in Python 2.7, fallback to simplejson for Python 2.5
try:
import json
except ImportError:
import simplejson as json
import badges
import exercise_models
# All badges awarded for completing some subset of exercises inherit from
# ExerciseCompletionBadge
class ExerciseCompletionBadge(badges.Badge):
def __init__(self):
super(ExerciseCompletionBadge, self).__init__()
self.is_goal = True
def is_satisfied_by(self, *args, **kwargs):
user_data = kwargs.get("user_data", None)
if user_data is None:
return False
if len(self.exercise_names_required) <= 0:
return False
for exercise_name in self.exercise_names_required:
if not user_data.is_proficient_at(exercise_name):
return False
return True
def goal_objectives(self):
if self.exercise_names_required:
return json.dumps(self.exercise_names_required)
return json.dumps([])
def extended_description(self):
badges = []
total_len = 0
for exercise_name in self.exercise_names_required:
long_name = exercise_models.Exercise.to_display_name(
exercise_name)
short_name = exercise_models.Exercise.to_short_name(exercise_name)
display_name = long_name if (total_len < 80) else short_name
badges.append(display_name)
total_len += len(display_name)
s_exercises = ", ".join(badges)
return "Bereik bekwaamheid in %s" % s_exercises
class ChallengeCompletionBadge(ExerciseCompletionBadge):
def __init__(self):
super(ChallengeCompletionBadge, self).__init__()
self.is_goal = False
def extended_description(self):
s_exercises = ""
for exercise_name in self.exercise_names_required:
if len(s_exercises) > 0:
s_exercises += ", "
s_exercises += exercise_models.Exercise.to_display_name(
exercise_name)
return "Maak de %s" % s_exercises
@property
def compact_icon_src(self):
return self.icon_src
class LevelOneArithmeticianBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'addition_1', 'subtraction_1', 'multiplication_1', 'division_1']
self.description = "Pupil rekenaar"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 100
class LevelTwoArithmeticianBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'addition_4', 'subtraction_4', 'multiplication_4', 'division_4']
self.description = "Ontwikkelde rekenaar"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 500
class LevelThreeArithmeticianBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'multiplying_decimals', 'dividing_decimals',
'multiplying_fractions', 'dividing_fractions']
self.description = "Gevorderde rekenaar"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 750
class TopLevelArithmeticianBadge(badges.RetiredBadge,
ChallengeCompletionBadge):
def __init__(self):
ChallengeCompletionBadge.__init__(self)
self.exercise_names_required = ['arithmetic_challenge']
self.description = "Meester rekenaar"
self.badge_category = badges.BadgeCategory.MASTER
self.points = 10000
@property
def icon_src(self):
return "/images/badges/Arithmetic.png"
class LevelOneTrigonometricianBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'angles_2', 'distance_formula', 'pythagorean_theorem_1']
self.description = "Pupil in trigoniometrie"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 100
class LevelTwoTrigonometricianBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'pythagorean_theorem_2', 'trigonometry_1']
self.description = "Ontwikkeld in trigoniometrie"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 500
class LevelThreeTrigonometricianBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'trigonometry_2', 'graphs_of_sine_and_cosine',
'inverse_trig_functions', 'trig_identities_1']
self.description = "Gevorderd in trigoniometrie"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 750
class TopLevelTrigonometricianBadge(badges.RetiredBadge,
ChallengeCompletionBadge):
def __init__(self):
ChallengeCompletionBadge.__init__(self)
self.exercise_names_required = ['trigonometry_challenge']
self.description = "Meester in trigoniometrie"
self.badge_category = badges.BadgeCategory.MASTER
self.points = 10000
@property
def icon_src(self):
return "/images/badges/Geometry-Trig.png"
class LevelOnePrealgebraistBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'exponents_1', 'adding_and_subtracting_negative_numbers',
'adding_and_subtracting_fractions']
self.description = "Pupil in Pre-algebra"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 100
class LevelTwoPrealgebraistBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'exponents_2', 'multiplying_and_dividing_negative_numbers',
'multiplying_fractions', 'dividing_fractions']
self.description = "Ontwikkeld in Pre-algebra"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 500
class LevelThreePrealgebraistBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'exponents_3', 'order_of_operations', 'ordering_numbers',
'scientific_notation', 'units', 'simplifying_radicals']
self.description = "Gevorderd in Pre-algebra"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 750
class TopLevelPrealgebraistBadge(badges.RetiredBadge,
ChallengeCompletionBadge):
def __init__(self):
ChallengeCompletionBadge.__init__(self)
self.exercise_names_required = ['pre-algebra_challenge']
self.description = "Meester in Pre-algebra"
self.badge_category = badges.BadgeCategory.MASTER
self.points = 10000
@property
def icon_src(self):
return "/images/badges/Pre-Algebra.png"
class LevelOneAlgebraistBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'exponents_3', 'exponent_rules', 'logarithms_1',
'linear_equations_1', 'percentage_word_problems_1', 'functions_1']
self.description = "Pupil in Algebra"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 100
class LevelTwoAlgebraistBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'linear_equations_2', 'percentage_word_problems_2',
'functions_2', 'domain_of_a_function', 'even_and_odd_functions',
'shifting_and_reflecting_functions']
self.description = "Ontwikkeld in Algebra"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 500
class LevelThreeAlgebraistBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'linear_equations_3', 'systems_of_equations',
'multiplying_expressions_1', 'even_and_odd_functions',
'inverses_of_functions', 'slope_of_a_line', 'midpoint_formula',
'line_relationships', 'functions_3']
self.description = "Gevorderd in Algebra"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 750
class LevelFourAlgebraistBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'linear_equations_4', 'linear_inequalities',
'average_word_problems', 'equation_of_a_line',
'solving_quadratics_by_factoring', 'quadratic_equation',
'solving_for_a_variable', 'expressions_with_unknown_variables']
self.description = "Geavanceerd in Algebra"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 1000
class LevelFiveAlgebraistBadge(ExerciseCompletionBadge):
def __init__(self):
ExerciseCompletionBadge.__init__(self)
self.exercise_names_required = [
'new_definitions_1', 'new_definitions_2',
'expressions_with_unknown_variables_2',
'absolute_value_equations', 'radical_equations',
'rate_problems_1']
self.description = "Vergevorderd in Algebra"
self.badge_category = badges.BadgeCategory.SILVER
self.points = 1000
class TopLevelAlgebraistBadge(badges.RetiredBadge, ChallengeCompletionBadge):
def __init__(self):
ChallengeCompletionBadge.__init__(self)
self.exercise_names_required = ['algebra_challenge']
self.description = "Meester of Algebra"
self.badge_category = badges.BadgeCategory.MASTER
self.points = 10000
@property
def icon_src(self):
return "/images/badges/Algebra.png"
|
PHP
|
UTF-8
| 1,871 | 3.328125 | 3 |
[] |
no_license
|
<?php
namespace App\Modules\Time;
class TimeConverter
{
public $days;
public $hours;
public $minutes;
public function getDays()
{
return $this->days;
}
public function getHours()
{
return $this->hours;
}
public function getMinutes()
{
return $this->minutes;
}
public function clear()
{
$this->days = 0;
$this->hours = 0;
$this->minutes = 0;
}
public function dhmToSeconds($days, $hours, $minutes){
if(!$days || !$hours || !$minutes){
return false;
}
$secondsInADay = 86400;
$secondsInAHour = 3600;
$secondsInAMinute = 60;
$daysToSeconds = $days * $secondsInADay;
$hoursToSeconds = $hours * $secondsInAHour;
$minutesToSeconds = $minutes * $secondsInAMinute;
return ($daysToSeconds + $hoursToSeconds + $minutesToSeconds);
}
public function secondsToDhm($inputSeconds){
if(!$inputSeconds){
return false;
}
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($inputSeconds / $secondsInADay);
// extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
// $remainingSeconds = $minuteSeconds % $secondsInAMinute;
// $seconds = ceil($remainingSeconds);
$this->days = (int) $days;
$this->hours = (int) $hours;
$this->minutes = (int) $minutes;
}
}
|
Shell
|
UTF-8
| 497 | 3.265625 | 3 |
[] |
no_license
|
#!/bin/sh
set -e
log_dir=/var/log/redis-cluster
lock_file=/data/cluster.lock
mkdir -p $log_dir
# Initialize configs
for p in 6379
do
conf_path=/redis-$p.conf
data_dir=/data/redis-$p
mkdir -p $data_dir
cp /redis.conf $conf_path
echo "
port $p
dir $data_dir" >> $conf_path
echo "
[program:redis-$p]
command=redis-server $conf_path
autorestart=unexpected
stdout_logfile=$log_dir/$p.log" >> /supervisord.conf
done
# Start Redis servers
supervisord
sleep 3
tail -f $log_dir/*.log
|
Shell
|
UTF-8
| 1,580 | 2.84375 | 3 |
[] |
no_license
|
#!/bin/bash
#
# Werite by: Jeon.sungwook
# Create Date : 2015-06-02
# Update Date : 2015-06-02
#
# OS : CentOS-7-x86_64 1503-01
# Node : controller
# Text : OPENSTACK INSTALLATION GUIDE FOR RED HAT ENTERPRISE LINUX 7, CENTOS 7, AND FEDORA 21 - KILO
#
# Perform script for for the chapter 2. Basic environment
#
# This script is to be installed and run on OpenStack Kilo
#
# Set environment and declare global variables
# ============================================================================================
# =========================================================================
# ๊ธฐ๋ณธ์ ์ผ๋ก OS Setup ๋ฐ Network Setup์ด ์๋ฃ๋์ด์ผ๋ง ํ๋ค.
# =========================================================================
# Load Env global variables
. ./kilo-perform-vars.common.sh
# 3.5 Create OpenStack client environment scripts
# To create the scripts
mkdir ~student/env
cat > ~student/env/admin-openrc.sh << EOF
export OS_PROJECT_DOMAIN_ID=default
export OS_USER_DOMAIN_ID=default
export OS_PROJECT_NAME=admin
export OS_TENANT_NAME=admin
export OS_USERNAME=admin
export OS_PASSWORD=pass_for_admin
export OS_AUTH_URL=http://controller:35357/v3
EOF
cat > ~student/env/demo-openrc.sh << EOF
export OS_PROJECT_DOMAIN_ID=default
export OS_USER_DOMAIN_ID=default
export OS_PROJECT_NAME=demo
export OS_TENANT_NAME=demo
export OS_USERNAME=demo
export OS_PASSWORD=pass_for_demo
export OS_AUTH_URL=http://controller:5000/v3
EOF
chown -R student:student ~student/env
# To load client environment scripts
source ~student/env/admin-openrc.sh
openstack token issue
|
PHP
|
UTF-8
| 1,299 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Lodge\Postcode;
class GoogleApi
{
/**
* Google API key.
*
* @var string
*/
protected $apiKey;
/**
* GoogleApi constructor.
* @param null $apiKey
*/
public function __construct($apiKey = null)
{
$this->apiKey = $apiKey;
}
/**
* Sets the Google API key.
*
* @param string $key
* @return $this
*/
public function setApiKey($key)
{
$this->apiKey = $key;
return $this;
}
/**
* Calls the Google API.
*
* @param string $url
* @return \stdClass
* @throws ServiceUnavailableException
*/
public function fetch($url)
{
if ($this->apiKey) {
$url .= '&key='.$this->apiKey;
}
try {
$json = json_decode(file_get_contents($url));
} catch(\Exception $e) {
throw new ServiceUnavailableException;
}
$this->checkApiError($json);
return $json;
}
/**
* @param \stdClass $json
* @throws ServiceUnavailableException
*/
private function checkApiError($json)
{
if (property_exists($json, 'error_message')) {
throw new ServiceUnavailableException($json->error_message);
}
}
}
|
Java
|
UTF-8
| 4,349 | 1.914063 | 2 |
[] |
no_license
|
package org.apache.camel.component.cxf;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.namespace.QName;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.ExchangePattern;
import org.apache.camel.component.cxf.spring.CxfEndpointBean;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.spring.SpringCamelContext;
import org.apache.cxf.configuration.spring.ConfigurerImpl;
import org.apache.cxf.message.Message;
/**
*
* @version $Revision: 583092 $
*/
public class CxfEndpoint extends DefaultEndpoint<CxfExchange> {
private final CxfComponent component;
private final String address;
private String wsdlURL;
private String serviceClass;
private CxfBinding binding;
private String portName;
private String serviceName;
private String dataFormat;
private String beanId;
private boolean isSpringContextEndpoint;
private boolean inOut = true;
private ConfigurerImpl configurer;
private CxfEndpointBean cxfEndpointBean;
public CxfEndpoint(String uri, String address, CxfComponent component) {
super(uri, component);
this.component = component;
this.address = address;
if (address.startsWith(CxfConstants.SPRING_CONTEXT_ENDPOINT)) {
isSpringContextEndpoint = true;
beanId = address.substring(CxfConstants.SPRING_CONTEXT_ENDPOINT.length());
beanId = beanId.substring(2);
}
SpringCamelContext context = (SpringCamelContext) this.getContext();
configurer = new ConfigurerImpl(context.getApplicationContext());
cxfEndpointBean = (CxfEndpointBean) context.getApplicationContext().getBean(beanId);
assert(cxfEndpointBean != null);
}
}
public Producer<CxfExchange> createProducer() throws Exception {
return new CxfProducer(this);
}
public Consumer<CxfExchange> createConsumer(Processor processor) throws Exception {
return new CxfConsumer(this, processor);
}
public CxfExchange createExchange() {
return new CxfExchange(getContext(), getExchangePattern(), getBinding());
}
public CxfExchange createExchange(ExchangePattern pattern) {
return new CxfExchange(getContext(), pattern, getBinding());
}
public CxfExchange createExchange(Message inMessage) {
return new CxfExchange(getContext(), getExchangePattern(), getBinding(), inMessage);
}
public String getDataFormat() {
return dataFormat;
}
public void setDataFormat(String format) {
dataFormat = format;
}
public boolean isSpringContextEndpoint() {
return isSpringContextEndpoint;
}
public String getAddress() {
return address;
}
public String getWsdlURL() {
return wsdlURL;
}
public void setWsdlURL(String url) {
wsdlURL = url;
}
public String getServiceClass() {
return serviceClass;
}
public void setServiceClass(String className) {
serviceClass = className;
}
public void setPortName(String port) {
portName = port;
}
public void setServiceName(String service) {
serviceName = service;
}
public String getPortName(){
return portName;
}
public String getServiceName() {
return serviceName;
}
public CxfBinding getBinding() {
if (binding == null) {
binding = new CxfBinding();
}
return binding;
}
public void setBinding(CxfBinding binding) {
this.binding = binding;
}
public boolean isInOut() {
return inOut;
}
public void setInOut(boolean inOut) {
this.inOut = inOut;
}
public CxfComponent getComponent() {
return component;
}
public boolean isSingleton() {
return true;
}
public String getBeanId() {
return beanId;
}
public CxfEndpointBean getCxfEndpointBean() {
return cxfEndpointBean;
}
public void configure(Object beanInstance) {
configurer.configureBean(beanId, beanInstance);
}
}
|
Python
|
UTF-8
| 1,276 | 2.515625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
import sys, wx
sys.path.append('../../')
from skimage.draw import line
from sciwx.app.canvasapp import CanvasApp
from sciapp.action import Tool, ImageTool
class Pencil(ImageTool):
title = 'Pencil'
para = {'pc':(255,0,0)}
view = [('color', 'pc','pen', 'color')]
def __init__(self):
self.status = False
self.oldp = (0,0)
def mouse_down(self, ips, x, y, btn, **key):
self.status = True
self.oldp = (y, x)
def mouse_up(self, ips, x, y, btn, **key):
self.status = False
def mouse_move(self, ips, x, y, btn, **key):
if not self.status:return
se = self.oldp + (y,x)
rs,cs = line(*[int(i) for i in se])
rs.clip(0, ips.shape[1], out=rs)
cs.clip(0, ips.shape[0], out=cs)
ips.img[rs,cs] = self.para['pc']
self.oldp = (y, x)
key['canvas'].update()
def mouse_wheel(self, ips, x, y, d, **key):pass
if __name__=='__main__':
from skimage.data import camera, astronaut
from skimage.io import imread
app = wx.App()
cf = CanvasApp(None, autofit=False)
cf.set_img(astronaut())
bar = cf.add_toolbar()
bar.add_tool('M', ImageTool)
bar.add_tool('P', Pencil)
cf.Show()
app.MainLoop()
|
JavaScript
|
UTF-8
| 3,770 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
$(() => {
const socket = io();
const audio = new Audio('bubble.mp3');
let focused = true;
let currentUser = null;
let unreadMessages = 0;
let connectedUsersCount = 0;
$('form').submit(() => {
const textbox = $('#text-box');
const msg = textbox.val();
if (msg) {
socket.emit('chat message', msg);
textbox.val('');
}
textbox.focus();
return false;
});
socket.on('set user', (user) => {
currentUser = user;
});
socket.on('update online users', (count) => {
connectedUsersCount = count;
$('#top-title').text(`Bate-Papo (${count})`);
});
socket.on('user connected', (user) => {
appendMessage(user, `${user.username}, entrou na sala.`, 'bounce-in-left', 'font-bold-n-italic');
});
socket.on('user disconnected', (user) => {
appendMessage(user, `${user.username}, saiu da sala.`, 'bounce-in-left', 'font-bold-n-italic');
});
socket.on('chat message', (data) => {
const { user, msg } = data;
appendMessage(user, msg);
});
function appendMessage(user, msg, anim, style) {
const li = $('<li>', {
"class": 'message-item ' + (anim ? anim : 'swing-in-bottom-fwd'),
});
const avatarInfo = $('<div>', {
"class": 'avatar-info',
});
const messageArea = $('<div>', {
"class": 'message-item-area',
});
const avatarImage = $('<img>', {
"class": 'avatar-image',
src: `./static/${user.username.toLowerCase().replace(/(\W|\d)*/g, '')}.png`,
});
const avatarName = $('<p>', {
"class": 'avatar-name',
text: user.username,
});
avatarInfo.append(avatarImage);
avatarInfo.append(avatarName);
li.append(avatarInfo);
const urlsPattern = /\bhttps?:\/\/\S+/gi;
const urls = msg.match(urlsPattern);
// console.log(urls);
if (urls) {
const message = $('<p>', {
"class": 'message-item-text' + (style ? ' ' + style : ''),
});
// replace urls in msg text with a href tags
const hyperlinkedMessage = msg.replace(urlsPattern, (matched) => {
const href = $('<a>', {
"class": 'message-item-link' + (style ? ' ' + style : ''),
href: matched,
text: matched,
target: '_blank',
})
return href.prop('outerHTML');
});
// console.log(hyperlinkedMessage);
message.append(hyperlinkedMessage);
messageArea.append(message);
const ytb = urls.find(url => url.includes('youtu'));
// console.log(ytb);
if (ytb) {
function getId(url) {
var ytbUrlPattern = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var matches = url.match(ytbUrlPattern);
if (matches && matches[2].length == 11) {
return matches[2];
}
else {
return undefined;
}
}
const videoId = getId(ytb);
// console.log(videoId);
if (videoId) {
const video = $('<iframe>', {
"class": 'youtube-view',
title: 'YouTube video player',
type: 'text/html',
width: '560px',
height: '315px',
src: `https://www.youtube.com/embed/${videoId}`,
frameborder: '0',
});
// Add youtube video to message area
messageArea.append(video);
}
}
}
else {
const message = $('<p>', {
"class": 'message-item-text' + (style ? ' ' + style : ''),
text: msg,
});
messageArea.append(message);
}
li.append(messageArea);
$('#message-list').append(li);
let scrollbar = $('#scrollbar');
scrollbar.scrollTop(1e4);
if (!focused) {
if (audio.paused) {
audio.play();
}
if (unreadMessages++ == 0) {
document.title = 'Xit-Xat - ' + msg;
}
else {
document.title = `Xit - Xat - (${unreadMessages}) Novas mensagens...`
}
}
}
$(window).focus(function () {
focused = true;
unreadMessages = 0;
document.title = 'Xit-Xat';
});
$(window).blur(function () {
focused = false;
});
});
|
Markdown
|
UTF-8
| 858 | 3.171875 | 3 |
[] |
no_license
|
# Waline Example
This directory is a brief example of a [Waline](https://waline.js.org/) app that can be deployed with Vercel and zero configuration.
## Deploy Your Own
Deploy your own Waline project with Vercel.
[](https://vercel.com/import/project?template=https://github.com/walinejs/waline/tree/master/example)
### How We Created This Example
```js
//index.js
const Waline = require('@waline/vercel');
module.exports = Waline();
//vercel.json
{
"builds": [
{
"src": "index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "index.js"
}
]
}
```
### Deploying From Your Terminal
You can deploy your new Waline project with a single command from your terminal using [Vercel CLI](https://vercel.com/download):
```shell
$ vercel
```
|
Python
|
UTF-8
| 1,534 | 2.859375 | 3 |
[] |
no_license
|
#https://www.acmicpc.net/problem/9376
import sys
from collections import deque
t = int(sys.stdin.readline())
for _ in range(t):
n, m = map(int,sys.stdin.readline().split())
a = [['.'] + list(sys.stdin.readline().rstrip()) + ['.'] for _ in range(n)]
a.insert(0,['.']*(m+2))
a.append(['.']*(m+2))
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def bfs(i,j):
d = [[-1] * (m+2) for _ in range(n+2)]
d[i][j] = 0
q = deque()
q.append((i,j))
while q:
x,y = q.popleft()
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
if 0 <= nx < n+2 and 0 <= ny < m+2 and d[nx][ny] == -1 and a[nx][ny] != '*':
if a[nx][ny] == '#':
d[nx][ny] = d[x][y] + 1
q.append((nx,ny))
else:
d[nx][ny] = d[x][y]
q.appendleft((nx,ny))
return d
prisoner = []
for i in range(n + 2):
for j in range(m + 2):
if a[i][j] == '$':
prisoner.append((i, j))
answer = 100 * 100
d0 = bfs(0, 0)
d1 = bfs(prisoner[0][0],prisoner[0][1])
d2 = bfs(prisoner[1][0],prisoner[1][1])
for i in range(n + 2):
for j in range(m + 2):
if a[i][j] == '*':
continue
k = d0[i][j]+d1[i][j]+d2[i][j]
if a[i][j] == '#':
k -= 2
answer = min(answer, k)
print(answer)
|
Python
|
UTF-8
| 417 | 2.890625 | 3 |
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
u_0 = [0.1,0.2,0.3,0.4,0.5]
tau = np.linspace(-1,1,100)
plt.figure(2)
for ind,i in enumerate(u_0):
u = np.array((tau**2+i**2)**0.5)
A = (u**2 + 2)/(u*(u**2 + 4)**0.5)
s = str(i)
plt.plot(tau,A,label='u_0='+s)
plt.legend()
plt.title('Family of single lens light curves')
plt.xlabel('$(t-t_0)/t_E$')
plt.ylabel('$Magnification,\; A(u)$')
plt.show()
|
PHP
|
UTF-8
| 630 | 2.546875 | 3 |
[] |
no_license
|
<?php
/**
* User: sasik
* Date: 5/17/16
* Time: 11:11 AM
*/
namespace App\Builder;
use App\Storage\FileStorage;
use App\Storage\IStorage;
use App\Storage\RedisStorage;
class StorageBuilder
{
/**
* @param string $file
* @return FileStorage
*/
public static function buildFileStorage($file = 'default.save')
{
return new FileStorage($file);
}
public static function buildRedisStorage()
{
$attributes = [
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
];
return new RedisStorage($attributes);
}
}
|
C++
|
UTF-8
| 577 | 2.859375 | 3 |
[] |
no_license
|
#pragma once
#include "point3d.h"
class vector3d {
public:
vector3d();
vector3d(point3d desti);
vector3d(point3d origin, point3d tip);
vector3d(point3d vec, double length);
~vector3d();
point3d getTip() const;
void setLength(double l);
double getLength() const;
vector3d operator*(double d) const;
vector3d operator*(vector3d v) const;
vector3d operator+(vector3d v)const;
vector3d operator-(vector3d v)const;
bool operator<(double d) const;
double dot(vector3d v) const;
vector3d rotate(vector3d v) const;
private:
double length;
point3d unitaryVector;
};
|
Java
|
UTF-8
| 124 | 1.601563 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
package org.beigesoft.uml.ui;
import java.io.File;
public interface IEditorDiagramUml {
void openDiagram(File file);
}
|
PHP
|
UTF-8
| 1,804 | 2.828125 | 3 |
[] |
no_license
|
<?php
// Require AWS
require 'vendor/autoload.php';
use Aws\S3\S3Client;
// Instantiate the S3 client using your credential profile
$clientParams = array();
$s3Client = S3Client::factory($clientParams);
// Verify bucket exists
function checkBucketExists($s3Client, $inputBucket)
{
$listBuckets = $s3Client->listBuckets();
//print_r($listBuckets);
$exists = false;
foreach($listBuckets['Buckets'] as $bucket){
if($bucket['Name'] == $inputBucket){
$exists = true;
break;
}
}
return $exists;
};
// Destination
$destinationBucket = 'dpelusotestbucket';
$directoryToUpload = 'ExampleBucket/';
$checkDestinationBucket = checkBucketExists($s3Client, $destinationBucket);
if($checkDestinationBucket === true){
// Check if directory exists
if(!file_exists($directoryToUpload)) throw new \Exception('Directory "'.$directoryToUploadd.'" not found');
// Get all files within that directory, removing . and .. directories
$files = array_diff(scandir($directoryToUpload), array('..', '.'));
print_r($files);
// Upload files
foreach($files as $file)
{
$absolutePath = realpath($directoryToUpload.$file);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$result = $s3Client->putObject(array(
'Bucket' => $destinationBucket,
'Key' => $file,
'SourceFile' => $absolutePath,
'ContentType' => finfo_file($finfo, $directoryToUpload.$file),
'ACL' => 'public-read',
'StorageClass' => 'REDUCED_REDUNDANCY',
'Metadata' => array()
));
echo $result['ObjectURL'].'<hr>';
}
} else {
throw new \Exception('Bucket "'.$destinationBucket.'" not found');
}
echo 'No errors?';
|
Java
|
UTF-8
| 468 | 1.84375 | 2 |
[] |
no_license
|
package com.emily.framework.quartz.config;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
* @program: spring-parent
* @description:
* @create: 2020/09/30
*/
@Configuration
@Conditional(EmilyCondition.class)
public class BeanB {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
Java
|
UTF-8
| 593 | 2.40625 | 2 |
[] |
no_license
|
package com.pokerface.pokerapi.util;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.Arrays;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class InvalidSortMethod extends RuntimeException {
private String attempt;
private String[] methods;
public InvalidSortMethod(String attempt, String ...methods) {
super("the sort method \'" + attempt + "\' is not a valid sort method. valid methods: " + Arrays.toString(methods));
this.attempt = attempt;
this.methods = methods;
}
}
|
PHP
|
UTF-8
| 221 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace MVC\Router;
interface RouterInterface {
public function addRoute(RouteInterface $route);
public function removeRoute(String $name);
public function getMatch(String $name): RouteInterface;
}
|
Java
|
UTF-8
| 458 | 1.53125 | 2 |
[] |
no_license
|
package com.xiaobobo.crowdfunding.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobobo.crowdfunding.dao.MessageMapper;
import org.springframework.stereotype.Service;
import com.xiaobobo.crowdfunding.entity.Message;
import com.xiaobobo.crowdfunding.service.MessageService;
@Service("messageService")
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {
}
|
Markdown
|
UTF-8
| 6,970 | 3.875 | 4 |
[] |
no_license
|
## 2. ์๋ฐ ๋ฐ์ดํฐ ํ์
, ๋ณ์ ๊ทธ๋ฆฌ๊ณ ๋ฐฐ์ด
##### ๋ชฉํ : ์๋ฐ์ ํ๋ฆฌ๋ฏธํฐ๋ธ ํ์
, ๋ณ์ ๊ทธ๋ฆฌ๊ณ ๋ฐฐ์ด์ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ์ตํ๋๋ค.
##### ํ์ตํ ๊ฒ
- ํ๋ฆฌ๋ฏธํฐ๋ธ ํ์
์ข
๋ฅ์ ๊ฐ์ ๋ฒ์ ๊ทธ๋ฆฌ๊ณ ๊ธฐ๋ณธ ๊ฐ
- ํ๋ฆฌ๋ฏธํฐ๋ธ ํ์
๊ณผ ๋ ํผ๋ฐ์ค ํ์
- ๋ฆฌํฐ๋ด
- ๋ณ์ ์ ์ธ ๋ฐ ์ด๊ธฐํํ๋ ๋ฐฉ๋ฒ
- ๋ณ์์ ์ค์ฝํ์ ๋ผ์ดํํ์
- ํ์
๋ณํ, ์บ์คํ
๊ทธ๋ฆฌ๊ณ ํ์
ํ๋ก๋ชจ์
- 1์ฐจ ๋ฐ 2์ฐจ ๋ฐฐ์ด ์ ์ธํ๊ธฐ
- ํ์
์ถ๋ก , var
---
</br>
#### 2-1. ํ๋ฆฌ๋ฏธํฐ๋ธ ํ์
์ข
๋ฅ์ ๊ฐ์ ๋ฒ์ ๊ทธ๋ฆฌ๊ณ ๊ธฐ๋ณธ ๊ฐ
---
> Primitive type of Java : boolean, byte, short, int, long, float, double, char
| ์๋ฃํ | ๊ธฐ๋ณธ๊ฐ | ์ ์ฅ ๊ฐ๋ฅํ ๊ฐ์ ๋ฒ์ | ํฌ๊ธฐ (byte) |
| :---------: | :------: | :---------------------------: | :---------: |
| **boolean** | false | false,true | 1 |
| **char** | '\u0000' | '\u0000' ~ '\uffff' (0~65535) | 2 |
| **byte** | 0 | -128 ~ 127 | 1 |
| **short** | 0 | -2^15 ~ 2^15-1 | 2 |
| **int** | 0 | -2^31 ~ 2^31-1 | 4 |
| **long** | 0L | -2^63 ~ 2^63-1 | 8 |
| **float** | 0.0f | 1.4E-45 ~ 3.4E38 | 4 |
| **double** | 0.0 | 4.9E-324 ~ 1.8E308 | 8 |
</br>
#### 2-2. ํ๋ฆฌ๋ฏธํฐ๋ธ ํ์
๊ณผ ๋ ํผ๋ฐ์ค ํ์
---
> Primitive type (๊ธฐ๋ณธํ ๋ณ์) : ์ค์ ๊ฐ(data)์ ์ ์ฅํ๋ค.
- JVM Runtime Data Area์ Stack ๋ฉ๋ชจ๋ฆฌ์ ์ ์ฅ๋๋ค.
- ๋
ผ๋ฆฌํ (boolean) : true/false์ ๊ฐ์ผ๋ก, ์กฐ๊ฑด์๊ณผ ๋
ผ๋ฆฌ์ ๊ณ์ฐ์ ์ฌ์ฉํ๋ค.
- ๋ฌธ์ํ (char) : ๋ฌธ์๋ฅผ ์ ์ฅํ๋๋ฐ ์ฌ์ฉ๋๋ฉฐ, ๋ณ์์ ํ๋์ ๋ฌธ์๋ง ์ ์ฅํ ์ ์๋ค.
- ์ ์ํ (byte, short, **int**, long) : ์ ์๋ฅผ ์ ์ฅํ๋ฉฐ, ์ฃผ๋ก int๋ฅผ ์ฌ์ฉํ๋ค.
- ์ค์ํ (float, **double**) : ์ค์๋ฅผ ์ ์ฅํ๋ฉฐ, ์ฃผ๋ก double์ ์ฌ์ฉํ๋ค.
</br>
> Reference type(์ฐธ์กฐํ ๋ณ์) : ๊ฐ์ด ์ ์ฅ๋์ด ์๋ ์ฃผ์(memory address)๋ฅผ ์ ์ฅํ๋ค.
- Heap ๋ฉ๋ชจ๋ฆฌ์ ์ ์ฅ๋๋ค.
- `Java.lang.Object`๋ฅผ ์์๋ฐ์ ๊ฐ์ผ๋ก ๊ธฐ๋ณธํ์ด ์๋๋ฉด ๋ชจ๋ ์ฐธ์กฐํ ๋ณ์์ด๋ค.
- ์ฐธ์กฐํ ๋ณ์๋ฅผ ์ ์ธํ ๋ ๋ณ์์ ํ์
์ผ๋ก ํด๋์ค์ ์ด๋ฆ์ ์ฌ์ฉํ๋ฏ๋ก, ํด๋์ค์ ์ด๋ฆ์ด ์ฐธ์กฐ๋ณ์์ ํ์
์ด ๋๋ค.
```java
// ClassName name;
Date today = new Date();
```
</br>
*cf. ์ ์ ๋ณ์(static)์ ์ธ์คํด์ค ๋ณ์๋ Heap ๋ฉ๋ชจ๋ฆฌ์ ์ ์ฅ๋๋ค.*
</br>
#### 2-3. ๋ฆฌํฐ๋ด
---
> literal : ๊ทธ ์์ฒด๋ก ๊ฐ์ ์๋ฏธํ๋ ๊ฒ
```java
// ๋ณ์ ๋ฆฌํฐ๋ด
int year = 2021;
```
- long ํ์
์ ๋ฆฌํฐ๋ด์ ์ ๋ฏธ์ฌ 'L'์ ๋ถ์ธ๋ค.
- float ํ์
์ ๋ฆฌํฐ๋ด์ ์ ๋ฏธ์ฌ 'f'๋ฅผ ๋ถ์ธ๋ค.
```java
// ์ ์ 26์ ํํํ๋ ์ฌ๋ฌ ๋ฐฉ๋ฒ
int num = 26; // 10์ง๋ฒ. ์ผ๋ฐ์ ์ธ ํํ
int octNum = 032; // 0์ผ๋ก ์์ํ๋ฉด 8์ง๋ฒ.
int hexNum = 0x1a; // 0x๋ก ์์ํ๋ฉด 16์ง๋ฒ.
int binNum = 0b11010; // 0b๋ก ์์ํ๋ฉด 2์ง๋ฒ.
long longNum = 26L; // long ํ์
.
```
</br>
*cf. ํ์
์ ๋ถ์ผ์น*
*๋ฆฌํฐ๋ด์ ํ์
์ ์ ์ฅ๋ ๋ณ์์ ํ์
๊ณผ ์ผ์นํ๋ ๊ฒ์ด ์ผ๋ฐ์ ์ด์ง๋ง,*
*ํ์
์ด ๋ฌ๋ผ๋ ์ ์ฅ๋ฒ์๊ฐ **๋์ ํ์
์ ์ข์ ํ์
์ ๊ฐ์ ์ ์ฅํ๋ ๊ฒ**์ด ํ์ฉ๋๋ค.*
```java
int i = 'A'; // ๋ฌธ์ 'A'์ ์ ๋์ฝ๋์ธ 65๊ฐ ๋ณ์ i์ ์ ์ฅ๋๋ค.
long l = 123; // int๋ณด๋ค longํ์
์ด ๋ ๋ฒ์๊ฐ ๋์ผ๋ฏ๋ก ๊ฐ๋ฅํ๋ค.
double d = 3.14f; // float๋ณด๋ค doubleํ์
์ด ๋ ๋ฒ์๊ฐ ๋์ผ๋ฏ๋ก ๊ฐ๋ฅํ๋ค.
```
</br>
#### 2-4. ๋ณ์ ์ ์ธ ๋ฐ ์ด๊ธฐํํ๋ ๋ฐฉ๋ฒ
---
```java
// ๋ณ์ ์ ์ธ. ์ ์ฅ๊ณต๊ฐ์ ํ๋ณดํ๋ค.
int num;
// ์ด๊ธฐํ. ์ ์ธ๋ ์ ์ฅ๊ณต๊ฐ์ ์ํ๋ ๊ฐ์ ์ ์ฅํ๋ค.
num = 7;
// ๋ณ์ ์ ์ธ๊ณผ ์ด๊ธฐํ๋ฅผ ๋์์ ํ ์ ์๋ค.
int num = 7;
```
</br>
#### 2-5. ๋ณ์์ ์ค์ฝํ์ ๋ผ์ดํํ์
---
> ์ค์ฝํ(Scope) : ์ ์ธํ ๋ณ์๋ฅผ ์ฌ์ฉํ ์ ์๋ ์์ญ์ ๋ฒ์๋ฅผ ๋ปํ๋ค.
>
> ๋ผ์ดํํ์(Life time) : ๋ณ์๊ฐ ๋ฉ๋ชจ๋ฆฌ์ ์ธ์ ๊น์ง ์กด์ฌํ๋ ๊ฐ๋ฅผ ์๋ฏธํ๋ค.
1. **Instance Variable** : ํด๋์ค ์์ญ์ ์ ์ธ๋๋ ๋ณ์
- Scope - `static` ๋ฉ์๋๋ฅผ ์ ์ธํ ํด๋์ค ์ ์ฒด
- Life time - ํด๋์ค๋ฅผ instanceํํ ๊ฐ์ฒด๊ฐ ๋ฉ๋ชจ๋ฆฌ์์ ์ฌ๋ผ์ง ๋
2. **Class Variables** : `static`์ผ๋ก ํด๋์ค ์์์ ์ ์ธ๋ ๋ณ์
- Scope - ํด๋์ค ์ ์ฒด
- Life time - ํ๋ก๊ทธ๋จ ์ข
๋ฃ์
3. **Local Variables** : ์ง์ญ๋ณ์.
- Scope - ๋ณ์๊ฐ ์ ์ธ๋ block `{ }` ๋ด๋ถ
- Life time - ์ ์ธ๋ ๋ฉ์๋์ ์ข
๋ฃ์ ํจ๊ป ์๋ฉธ๋๋ค. ๋ฐ๋ณต๋ฌธ ๋ํ ์ ์ธ๋ block์ ๋ฒ์ด๋๊ฒ ๋๋ค๋ฉด ์๋ฉธ๋๋ค.
</br>
#### 2-6. ํ์
๋ณํ, ์บ์คํ
๊ทธ๋ฆฌ๊ณ ํ์
ํ๋ก๋ชจ์
---
> ํ์
๋ณํ : ๋ณ์๋ ๋ฆฌํฐ๋ด์ ํ์
์ ๋ค๋ฅธ ํ์
์ผ๋ก ๋ณํํ๋ ๊ฒ
>
> Primitive type ๋ณ์๋ `boolean`์ ์ ์ธํ๊ณ ์๋ก ํ๋ณํ์ด ๊ฐ๋ฅํ๋ค.
- **Type casting** : ํฌ๊ธฐ๊ฐ ๋ ํฐ ์๋ฃํ์ ๋ ์์ ์๋ฃํ์ผ๋ก ๋ณํํ๋ค.
์ด ๊ฒฝ์ฐ, ๋ฐ์ดํฐ ์์ค์ด ์ฌ ์ ์๋ค๋ ์ ์ ์ ์ํ์ฌ์ผ ํ๋ค.
``` java
int a = 10000;
byte b = (byte) a; //ํํ๋ฒ์๋ฅผ ๋ฒ์ด๋๋ ์บ์คํ
์ผ๋ก ๋ฐ์ดํฐ์ ๋ณํ์ ์ค๋ค.
System.out.println(b); // 16
```
- **Type promotion** : ํฌ๊ธฐ๊ฐ ๋ ์์ ์๋ฃํ์ ๋ ํฐ ์๋ฃํ์ ๋์
ํ๋ ๊ฒ์ ์๋ฏธํ๋ค.
```java
byte a = 10;
int b = a;
System.out.println(b); // 10 ๐
```
</br>
*cf. Reference type์์๋ **์์๊ด๊ณ**์ ์์ ๋ ํ๋ณํ์ด ๊ฐ๋ฅํ๋ค.*
- Upcast : subclass -> superclass (์๋ ํ๋ณํ)
- ์ด ๋ ๊ฐ์ฒด ๋ด์ ๋ชจ๋ ๋ฉค๋ฒ(๋ณ์, ๋ฉ์๋)๊ฐ ์๋, ๋ถ๋ชจ์ ๋ฉค๋ฒ์๋ง ์ ๊ทผ์ด ๊ฐ๋ฅํ๋ค.
- Downcast : superclass -> subclass
- ๋ช
์์ ์ผ๋ก ํ์
์ ์ง์ ํด์ผ ์บ์คํ
ํ ์ ์๋ค.
- **์ค๋ฅ ๋ฐ์์ ์ํ์ด ์๋ค.**
</br>
#### 2-7. 1์ฐจ ๋ฐ 2์ฐจ ๋ฐฐ์ด ์ ์ธํ๊ธฐ
---
> ๋ฐฐ์ด(Array) : ๋์ผํ type์ ๋ฐ์ดํฐ๋ฅผ ์ฐ์๋ ๊ณต๊ฐ์ ์ ์ฅํ๋ ์๋ฃ๊ตฌ์กฐ
**1์ฐจ ๋ฐฐ์ด ์ ์ธํ๊ธฐ**
```java
// ํ์
[] Array์ด๋ฆ = new ํ์
[๊ธธ์ด];
int[] numArray = new int[10];
// ํ์
[] Array์ด๋ฆ = {Elements};
int[] newArray = {1,2,3}; //์ ์ธ๊ณผ ๋์์ ์ด๊ธฐํ๋ฅผ ์์ผ์ฃผ์ด์ผ ํ๋ค.
```
**2์ฐจ ๋ฐฐ์ด ์ ์ธํ๊ธฐ**
```java
int[][] array = new int[3][4];
```
</br>
#### 2-8. ํ์
์ถ๋ก , var
---
> ๋ฉ์๋ ํธ์ถ ๋ฐ ์ ์ธ, variable์ด๋ object ์ ์ธ์ ํตํด ์ค์ ํ์
์ ์ถ๋ก ํ ์ ์๋ค.
- ํ์
์ถ๋ก ์ผ๋ก Generic ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ๋ ํ์
์ ๋ช
์ํ์ง ์๊ณ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
```java
List<String> newList = new ArrayList<>();
```
- `var`๋ผ๋ type keyword๋ฅผ ์ฌ์ฉํ์ฌ ์ค์ ํ์
์ ์ถ๋ก ํ ์ ์๋ค.
```java
var a = 5;
var list = new ArrayList<String>();
```
|
Markdown
|
UTF-8
| 711 | 3.296875 | 3 |
[] |
no_license
|
# Introduction ๅ่จ
This module is written for the learners with Mathematic background.
Before start to read the contents later, you need to understand all the concepts inside the basic part.
In the following tutorials, Iโm going to use some mathematical concepts as examples to continue explaining `gm`.
---
ๆฌๆจกๅๆฏไธไธบๆฐๅญฆ่ๆฏ็ๆๅ็ผๅ็ใ
ๅจๅผๅง้
่ฏปไนๅ็ๅ
ๅฎนไนๅ๏ผๆจ้่ฆไบ่งฃๅบ็ก้จๅไธญ็ๆๆๆฆๅฟตใ
ๅจๆฌๆ็จไธญ๏ผๆๅฐ็จไธไบๆฐๅญฆๆฆๅฟต็ๅฎไน็ไพๅญๆฅ็ปง็ปญๆๆ`gm`ใ
# Content --- ็ฎๅฝ
1. [class.= defined by default for each class]()
# REMARK --- ๆณจๆไบ้กน
* [differnce between class and set]()
[Return --- ่ฟๅ](Home)
|
JavaScript
|
UTF-8
| 3,339 | 3.03125 | 3 |
[] |
no_license
|
//= require snake
(function(root) {
var SnakeUI = root.SnakeUI = (root.SnakeUI || {});
var View = SnakeUI.View = function(htmlEl, max_x, max_y) {
this.$el = htmlEl;
this.length = max_x;
this.width = max_y;
};
var handleKeyEvent = function(event) {
switch(event.keyCode) {
case 37:
event.preventDefault();
this.board.snake.turn('W');
break;
case 38:
event.preventDefault();
this.board.snake.turn('N');
break;
case 39:
event.preventDefault();
this.board.snake.turn('E');
break;
case 40:
event.preventDefault();
this.board.snake.turn('S');
break;
// default:
// alert("WTF");
}
};
View.prototype.buildGrid = function() {
for(var y = 0; y < this.width; y++) {
for(var x = 0; x < this.length; x++) {
this.$el.append("\<li data-id=\"[" + y + ", " + x + "]\">\<\/li>");
}
}
};
View.prototype.cleanUpSnake = function() {
var removeCoord = _.last(this.board.snake.segments);
var x = removeCoord.x;
var y = removeCoord.y;
return [removeCoord, (y * this.width) + x + 1];
};
View.prototype.render = function() {
var that = this;
this.board.snake.segments.forEach(function(segment) {
var x = segment.x;
var y = segment.y;
var index = (y * that.width) + x + 1;
that.$el.find('li:nth-child(' + index + ')').addClass('snake');
// console.log(that.board.snake.segments);
});
this.board.apples.forEach(function(apple) {
var x = apple.position.x;
var y = apple.position.y;
var index = (y * that.width) + x + 1;
that.$el.find('li:nth-child(' + index + ')').addClass('apple');
});
// var gridArray = this.board.render();
// var str = ""
// gridArray.forEach(function(row) {
// str += '<pre>'
// str += row.join(" ");
// str += '</pre><br>'
// })
//
// this.$el.html(str);
};
// var x = Math.floor(index / 3);
// var y = index%3;
View.prototype.step = function() {
//stash in variable here.
var cleanSnakeArr = this.cleanUpSnake();
var removeIndex = cleanSnakeArr[1];
var removeCoord = cleanSnakeArr[0];
var lookForApple = this.board.snake.segments[0];
var that = this;
var shouldRemoveIndex = true;
this.board.apples.forEach(function(apple) {
if (lookForApple.equals(apple)) {
var index = (apple.y * that.width) + apple.x + 1;
that.$el.find('li:nth-child(' + index + ')').removeClass('apple');
that.board.apples.splice(that.board.apples.indexOf(apple), 1);
that.board.growMySnake(removeCoord);
shouldRemoveIndex = false;
}
})
this.board.snake.move();
if (shouldRemoveIndex) {
this.$el.find('li:nth-child(' + removeIndex + ')').removeClass('snake');
}
//clean up here
this.render();
}
View.prototype.start = function() {
this.buildGrid();
this.board = new SnakeGame.Board(20);
var that = this;
$(function() { //handleKeyEvent(event).bind(this)
$(document).on('keydown', handleKeyEvent.bind(that));
});
//interval with #step.
this.timerId = setInterval(function() {
that.step();
},150);
};
})(this);
|
Shell
|
UTF-8
| 282 | 2.53125 | 3 |
[] |
no_license
|
#!/bin/sh
set -e -x
COMMIT=`git rev-parse HEAD`
COMMIT_ABBREV=`git rev-parse --short HEAD`
COMMIT_TIME=`git log -1 --format=%cd`
CI=true \
REACT_APP_GIT_SHA=${COMMIT} \
REACT_APP_GIT_SHA_ABBREV=${COMMIT_ABBREV} \
REACT_APP_COMMIT_TIME=${COMMIT_TIME} \
npm run build
|
JavaScript
|
UTF-8
| 573 | 3.84375 | 4 |
[] |
no_license
|
// 2.) getItemsByBrand(array, brand)
// Create a function called getItemsByBrand that
// takes an item array returns a new array of all items
// of a specified brand.
// Test this function by searching for Sony, Cannon, Nikon and Panasonic.
var data = require("./products.json")
var getItemsByBrand = function (array, brand) {
var newArray = [];
for (var i=0; i < array.length; i++) {
if (array[i]["product"]["brand"] === brand) {
newArray.push(array[i]["product"]["title"]);
}
}
return (newArray);
}
console.log(getItemsByBrand(data["items"], "Sony"));
|
Java
|
UTF-8
| 3,126 | 3.765625 | 4 |
[] |
no_license
|
/**
* A fully static class offering some simple utility
* random functions. It allows the generating of random
* values between a minimum and maximum value.
*
* This is meant as a small utility class for times when you
* need a one off random number between a given range.
* It is designed to save the time and trouble of either using
* the greenfoot.Greenfoot.getRandomNumber method or
* the java.util.Random class.
*
* All of the random static methods take a minimum and
* maximum value. The value they return is from the minimum
* (inclusive) to the maximum (exclusive).
*
* The Random class can also be seeded to a pre-set value,
* however for complex random code the java.util.Random
* class might be a better option.
*
* As default this Random class will seed to the current time
* when the class is loaded.
*
* @author Joseph Lenton
* @version 27/07/2008
*/
public final class Random
{
private static java.util.Random rand = new java.util.Random(System.currentTimeMillis());
/**
* Sets the starting seed value for this Random class.
* This is the value used when calculating more random
* numbers, and by seeding to a specific number you can
* generate the same series of random number.
* @param seed The long value to seed this too.
*/
public static void seed(long seed)
{
rand.setSeed(seed);
}
/**
* @param minimum The minimun random number, inclusively.
* @param maximum The maximum random number, exclusively.
* @return A number greater or equal to minimum, less then maximum.
*/
public static double random(double minimum, double maximum)
{
if(maximum-minimum != 0) {
return rand.nextDouble()*(maximum-minimum) + minimum;
}
else {
return 0.0;
}
}
/**
* @param minimum The minimun random number, inclusively.
* @param maximum The maximum random number, exclusively.
* @return A number greater or equal to minimum, less then maximum.
*/
public static float random(float minimum, float maximum)
{
if(maximum-minimum != 0) {
return rand.nextFloat()*(maximum-minimum) + minimum;
}
else {
return 0;
}
}
/**
* @param minimum The minimun random number, inclusively.
* @param maximum The maximum random number, exclusively.
* @return A number greater or equal to minimum, less then maximum.
*/
public static int random(int minimum, int maximum)
{
if(maximum-minimum != 0) {
return rand.nextInt(maximum-minimum)+minimum;
}
else {
return 0;
}
}
/**
* @return Randomly returns either a True or False.
*/
public static boolean randomBoolean()
{
return rand.nextBoolean();
}
/**
* @return A random double value between 0 and 1.
*/
public static double randomDouble() {
return rand.nextDouble();
}
/**
* Cannot use it's constructor.
*/
private Random() { }
}
|
Java
|
UTF-8
| 866 | 2.25 | 2 |
[] |
no_license
|
package com.algaworks.algafood.api.assembler;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;
import com.algaworks.algafood.api.dto.FormasPagamentoDTO;
import com.algaworks.algafood.domain.model.FormasPagamento;
@Component
public class FormasPagamentoDTOAssembler {
private ModelMapper modelMapper;
public FormasPagamentoDTOAssembler(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
}
public FormasPagamentoDTO toDTO(FormasPagamento formasPagamento) {
return modelMapper.map(formasPagamento, FormasPagamentoDTO.class);
}
public List<FormasPagamentoDTO> toCollectionDTO(List<FormasPagamento> formasPagamentos) {
return formasPagamentos.stream()
.map(formasPagamento -> toDTO(formasPagamento))
.collect(Collectors.toList());
}
}
|
Python
|
UTF-8
| 801 | 3.484375 | 3 |
[] |
no_license
|
# A starter program for Python with Tkinter
from tkinter import * # import Tkinter library
from tkinter.ttk import *
from ttkthemes import ThemedTk
window = ThemedTk(theme = "arc") # Create the application window
window.title("Hello")
window.geometry('500x500')
combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, "Text")
combo.current(1) #set the selected item
combo.grid(column=0, row=0)
lbl = Label(window, text="Welcome", font=("Arial Bold",10))
lbl.grid(column=0, row=0)
txt = Entry(window, width=10)
txt.grid(column=1, row=0)
def clicked():
lbl.configure(text=txt.get() +" clicked the button!")
lbl.configure(text=res)
txt.focus()
btn = Button(window, text="Click Me", command=clicked)
btn.grid(column=2, row=0)
window.mainloop() # Keep the window open
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.