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
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 1,632
| 3.78125
| 4
|
[] |
no_license
|
using System;
namespace Лаба_4_2._2_
{
class Program
{
static void Main(string[] args)
{
Bird b = new Bird();
b.DisplayInfo();
b.HightFly();
Owl o = new Owl();
o.DisplayInfo();
Dog d = new Dog();
d.DisplayInfo();
}
}
public abstract class Animal
{
public string Name { get; set; }
public int Age { get; set; }
public string Sound { get; set; }
public int Speed { get; set; }
public abstract void HightFly();
public Animal(string name, int age, string sound, int speed)
{
Name = name;
Age = age;
Sound = sound;
Speed = speed;
}
public void DisplayInfo()
{
Console.WriteLine($"Имя: {Name}\nВозраст: {Age}\nЗвук: {Sound}\nСкорость: {Speed}\n");
}
}
public class Bird : Animal
{
public Bird() : base("Bird", 7, "Кря", 50) { }
public override void HightFly()
{
Console.WriteLine("Висота польоту птаха: 70");
}
}
public class Dog : Animal
{
public Dog() : base("Dog", 10, "Гаф", 30) { }
public override void HightFly()
{
Console.WriteLine("Только бегает");
}
}
public class Owl : Animal
{
public Owl() : base("Owl", 20, "Угу", 40) { }
public override void HightFly()
{
Console.WriteLine("30");
}
}
}
|
Python
|
UTF-8
| 1,820
| 3.484375
| 3
|
[] |
no_license
|
import unittest
from calc import Calc
class calcClassTest(unittest.TestCase):
##test Add function
def test_addFunc(self):
add = Calc()
self.assertEqual(add.add(10,5), 15)
self.assertEqual(add.add(20,10), 30)
##test Subtract function
def test_subtractFunc(self):
add = Calc()
self.assertEqual(add.subtract(10,5), 5)
self.assertEqual(add.subtract(20,10), 10)
self.assertEqual(add.subtract(15,3), 12)
##test Divide function
def test_divideFunc(self):
add = Calc()
self.assertEqual(add.divide(10,5), 2)
self.assertEqual(add.divide(20,10), 2)
self.assertEqual(add.divide(50, 5), 10)
##test multiply function
def test_multiplyFunc(self):
add = Calc()
self.assertEqual(add.multiply(10,5), 50)
self.assertEqual(add.multiply(20,10), 200)
self.assertEqual(add.multiply(50, 5), 250)
##test power function
def test_powerFunc(self):
add = Calc()
self.assertEqual(add.power(10,2), 100)
self.assertEqual(add.power(3,4), 81)
self.assertEqual(add.power(2, -3), 0.125)
##test squareroot function
def test_sqrtFunc(self):
add = Calc()
self.assertEqual(add.sqrt(81), 9)
self.assertEqual(add.sqrt(4), 2)
self.assertEqual(add.sqrt(10000), 100)
##input must be integers. Lets test that
def test_inputs(self):
func = Calc()
with self.assertRaises(ValueError):
func.add([234], 5)
func.subtract(364, {"name":"John"})
func.divide(352, 0)
func.divide([748,3782,493], {"1":"2"})
func.sqrt(-5)
func.sqrt({0,2,3,4,5})
func.power([4,6], [7,6])
if __name__ == "__main__":
unittest.main(exit=False)
|
C
|
UTF-8
| 1,127
| 4
| 4
|
[] |
no_license
|
#include "binary_trees.h"
/**
* binary_tree_size - function that size of a tree
* @tree: pointer to a tree
* Return: size of the tree
*/
size_t binary_tree_size(const binary_tree_t *tree)
{
size_t count = 0;
if (!tree)
return (0);
count = binary_tree_size(tree->left) + 1 + binary_tree_size(tree->right);
return (count);
}
/**
* is_complete - check if tree is complete
* @root: node to check
* @index: index for count
* @size: size of nodes
* Return: 1 if is complete 0 if not
*/
int is_complete(binary_tree_t *root, size_t index, size_t size)
{
if (root == NULL)
return (1);
if (index >= size)
return (0);
return (is_complete(root->left, 2 * index + 1, size) &&
is_complete(root->right, 2 * index + 2, size));
}
/**
* binary_tree_is_complete - function that checks if tree is complete
* @tree: node to check
* Return: 1 if is complete or 0 if not
*/
int binary_tree_is_complete(const binary_tree_t *tree)
{
size_t size, index = 0;
if (!tree)
return (0);
size = binary_tree_size((binary_tree_t *)tree);
if (is_complete((binary_tree_t *)tree, index, size))
return (1);
return (0);
}
|
C++
|
UTF-8
| 575
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
#include<iostream>
using namespace std;
int simple(int p, int r, int t){
int ans;
ans = (p*r*t)/100 + p;
return ans;
}
int main(){
int p,t,age,r;
cout<<"Enter amount of fixed deposite: ";
cin>>p;
cout<<"Enter time in year: ";
cin>>t;
cout<<"Enter Depositor's age: ";
cin>>age;
if(age>=18 && age<=60){
r = 10;
cout<<"You have return of your FD is: "<<simple(p,r,t);
}else if(age>60){
r = 12;
cout<<"You have return of your FD is: "<<simple(p,r,t);
}else{
cout<<"Minor age: ";
}
}
|
C#
|
UTF-8
| 3,159
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
/* oio * 6/23/2014 * Time: 7:10 AM
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using NAudio.Wave;
namespace AvUtil.Core
{
/// <summary>
/// This class isn't quite working or implemented yet.
/// Once it is, will become a part of the common-sound library (gen.snd.common).
/// </summary>
class AggrigationCalculator
{
long SampleSize, SampleCount, WaveLength, MaximumSamples;
public List<FloatPoint> Points = new List<FloatPoint>();
/// <summary>
/// What data is actually aggrigated.
/// </summary>
[Flags] public enum AggrigationMode
{
Mono = 0,
Left = 1,
Right = 2,
Stereo = Left | Right
}
public static FloatPoint DefaultWindowSize {
get { return new FloatPoint(1920, 1080); }
}
public FloatPoint WindowSize {
get { return windowSize; } set { windowSize = value; }
} FloatPoint windowSize = null;
public FloatPoint WindowRatio {
get { return windowRatio; }
set { windowRatio = value; }
} FloatPoint windowRatio = null;
WaveFormat WaveInfo { get; set; }
public FloatPoint[] GetSpline() { throw new NotImplementedException(); }
#region Range(...), Merge(...) (Unused)
public FloatPoint Range(FloatPoint range)
{
var z = DefaultWindowSize / range;
return z % FloatPoint.One >= new FloatPoint(0.5f) ? z + 1 : z;
}
public static FloatPoint Merge(int count, Func<FloatPoint, FloatPoint> f, params FloatPoint[] block)
{
var Avg = FloatPoint.Empty;
for (int r = 0; r < block.Length; r += 1) if (f != null) Avg = f(Avg);
return Avg;
}
#endregion
#region 16 bit Frame Aggrigator
public static FloatPoint MinMax16Mono(FloatPoint a, FloatPoint b)
{
return new FloatPoint(Math.Max(a.X, b.X), Math.Min(a.Y, b.Y));
}
public static FloatPoint[] MinMax16(List<FloatPoint> points, int channels)
{
var Accum = new FloatPoint[channels];
for (int i = 0; i < points.Count; i += channels) Accum[i] = FloatPoint.Empty;
for (int i = 0; i < points.Count; i += channels) for (int j = i; j < channels; j++)
Accum[j] = MinMax16Mono(points[i + j], Accum[i + j]);
return Accum;
}
#endregion
public List<FloatPoint> GetInt16(int width, int chanels, params byte[] buffer)
{
throw new NotImplementedException();
}
public AggrigationCalculator(WaveFormat info, long waveLength)
{
Load(info, waveLength);
}
static int GetFrameCount(int window, int hours, int minutes, int seconds, int channels = 2, int bytes = 2, int rate = 44100, float round = 0f)
{
long samples = channels * bytes * rate * ( Convert.ToInt64(hours)*60*60 + minutes*60 + seconds );
return Convert.ToInt32(samples / window);
}
public AggrigationCalculator Load(WaveFormat info, long waveLength)
{
WaveInfo = info;
WaveLength = waveLength;
// note via bitspersample, 16bit is 2 bytes, hence the 2 in place of 16-bit.
int bytesPerSample = WaveInfo.BitsPerSample >> 1;
SampleSize = WaveInfo.Channels * (WaveInfo.BitsPerSample / 8) * WaveInfo.SampleRate;
SampleCount = waveLength / SampleSize;
MaximumSamples = SampleSize * 3600;
// hr
return this;
}
}
}
|
C#
|
UTF-8
| 3,227
| 3.109375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TheWayShop_2._0.Models;
namespace TheWayShop_2._0.DB
{
public class AppDbInitializer
{
public static void Initial(AppDbContext context)
{
if (!context.CategoryItems.Any())
{
context.CategoryItems.AddRange(CategoryItems.Select(c => c.Value));
}
if (!context.Category.Any())
{
context.Category.AddRange(Categories.Select(c => c.Value));
}
if (!context.Thing.Any())
{
context.AddRange(
new Thing
{
name = "shirt",
description = "a very great shirt",
img = "~/images/shirt-img.jpg",
color = "brown",
size = "L",
price = 250,
categoryId = 1,
category = Categories["Top"]
},
new Thing
{
name = "shoes",
description = "a very great men shoes",
img = "~/images/shoes-img.jpg",
color = "black",
size ="S",
price = 890,
categoryId = 2,
category = Categories["Bottom"]
}
);
}
context.SaveChanges();
}
private static Dictionary<string, Category> category;
public static Dictionary<string, Category> Categories
{
get
{
if (category == null)
{
var list = new Category[]
{
new Category{name="Top",description="Cloth for top",categoryItemId=1,categoryItem=CategoryItems["Shirts"]},
new Category{name="Bottom",description="Cloth for bottom",categoryItemId=2,categoryItem=CategoryItems["Shoes"]}
};
category = new Dictionary<string, Category>();
foreach (Category el in list)
category.Add(el.name, el);
}
return category;
}
}
private static Dictionary<string, CategoryItem> categoryItem;
public static Dictionary<string, CategoryItem> CategoryItems
{
get
{
if (categoryItem == null)
{
var list = new CategoryItem[]
{
new CategoryItem{name="Shirts",description="Very nice shirts"},
new CategoryItem{name="Shoes",description="Very nice shoes"}
};
categoryItem = new Dictionary<string, CategoryItem>();
foreach (CategoryItem el in list)
categoryItem.Add(el.name, el);
}
return categoryItem;
}
}
}
}
|
PHP
|
UTF-8
| 4,367
| 3.34375
| 3
|
[] |
no_license
|
<?php
//Declaracion de la clase BaseDatos
class BaseDatos
{
//Variables de la clase
private $host="localhost";
private $db="mathDice";
private $user="js_cmd";
private $pass="js_cmd";
private $conexion;
//CREAMOS EL CONSTRUCTOR
function __construct() {
$this->conexion = new mysqli($this->host, $this->user, $this->pass, $this->db);
}
//Metodo para chequear la conexion
function comprobarConexion(){
if ($this->conexion->connect_errno) {
echo "Fallo al conectar a MySQL: (" . $this->conexion->connect_errno . ") " . $this->conexion->connect_error;
}
}
//Metodo para registrar un usuario
function registrarUsuario($nombre,$apellidos,$email,$edad,$puntos,$passW)
{
$consulta ="INSERT INTO usuario (nombre,apellidos,email,edad,puntos,password) VALUES ('$nombre','$apellidos','$email',$edad,$puntos,'$passW')";
if($this->conexion->query($consulta))
{
}else{
echo "Falló la creación de la tabla: (" . $this->conexion->errno . ")// " . $this->conexion->error."<br>";
}
}
function comprobarUsuario($nombre,$passW)
{
$consulta ="SELECT * from usuario where nombre = '$nombre' and password = '$passW'";
//echo $consulta;
if($resultado= $this->conexion->query($consulta)){
if ( $resultado->num_rows!=0 ) {
while($fila= $resultado->fetch_assoc())
{
return $fila ;
}//Fin While
$resultado->close();
}else
{
$error="No se encuentra el usuario";
}//Fin segundo if
header("Location: ../index.php?error=$error");$conexion->close();
}else
{
}//Fin primer if
}
//Metodo para actualizar valores de un usuario, pero manteniendo la contraseña
function UpdateUsuario($id,$nombre,$apellidos,$email,$edad)
{
$consulta="UPDATE usuario set nombre='$nombre', apellidos='$apellidos',email='$email',edad='$edad' where id='$id' ";
if($this->conexion->query($consulta))
{
}else
{
echo "Falló la creación de la tabla: (" . $this->conexion->errno . ")// " . $this->conexion->error."<br>";
}
}
//Metodo para actualizar valores de un usuario, pero cambiando la contraseña
function UpdatePasswordUsuario($id,$nombre,$apellidos,$email,$edad,$passW)
{
$consulta="UPDATE usuario set nombre='$nombre', apellidos='$apellidos',email='$email',edad='$edad',password='$passW' where id='$id' ";
if($this->conexion->query($consulta))
{
}else
{
echo "Falló la creación de la tabla: (" . $this->conexion->errno . ")// " . $this->conexion->error."<br>";
}
}
//Actualizar puntos
function UpdateMark($id)
{
$contador=5;
$prevconsulta="SELECT puntos FROM usuario where id='$id' ";
if($resultado= $this->conexion->query($prevconsulta)){
if ( $resultado->num_rows!=0 ) {
while($fila= $resultado->fetch_assoc())
{
$contador+=$fila["puntos"] ;
}
$resultado->close();
}else
{
}
}
$consulta="UPDATE usuario set puntos='$contador' where id='$id' ";
if($this->conexion->query($consulta))
{
}else
{
echo "Falló la creación de la tabla: (" . $this->conexion->errno . ")// " . $this->conexion->error."<br>";
}
}
//Obtener valores segun el parametro
function executeQuery($param,$id)
{
$consulta ="SELECT $param from usuario where id='$id'";
if($resultado= $this->conexion->query($consulta)){
if ( $resultado->num_rows!=0 ) {
while($fila= $resultado->fetch_assoc())
{
return $fila["$param"] ;
}//return $resultado->fetch_row();
$resultado->close();
}else
{
}
$conexion->close();
}
}
}
?>
|
Python
|
UTF-8
| 97
| 2.8125
| 3
|
[] |
no_license
|
#maxsplit
import re
st="programinglanguage"
result=re.split(r"m",st,maxsplit=1)
print(result)
|
SQL
|
UTF-8
| 203
| 3.171875
| 3
|
[] |
no_license
|
-- name: GetWriteUpsByTags :many
SELECT write_ups.*
FROM write_ups
INNER JOIN write_up_tags
ON write_ups.id = write_up_tags.write_up_id
WHERE write_up_tags.tag_id = $1
ORDER BY write_up.created_at DESC;
|
Java
|
UTF-8
| 266
| 2.625
| 3
|
[] |
no_license
|
package Assignment;
import java.util.Scanner;
public class TestCalculator {
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.sum(100, 50);
c1.sub(100, 50);
c1.mul(100, 50);
c1.div(100, 50);
}
}
|
PHP
|
UTF-8
| 194
| 4.125
| 4
|
[] |
no_license
|
<!-- ans - 5 palindrome -->
<?php
$num = 222;
$rev = strrev($num);
if ($num == $rev) {
echo " <b>$num</b> it is a palindrome";
} else {
echo " <b>$num</b> it is not palindrome";
}
?>
|
C++
|
UTF-8
| 2,014
| 2.796875
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFER_SIZE 40
int main(int argc, char *argv[])
{
int client_sockfd;
int len;
struct sockaddr_in remote_addr; // 服务器端网络地址结构体
char buf[BUFFER_SIZE]; // 数据传送的缓冲区
memset(&remote_addr,0,sizeof(remote_addr)); // 数据初始化--清零
remote_addr.sin_family=AF_INET; // 设置为IP通信
remote_addr.sin_addr.s_addr=inet_addr("127.0.0.1");// 服务器IP地址
remote_addr.sin_port=htons(8000); // 服务器端口号
// 创建客户端套接字--IPv4协议,面向连接通信,TCP协议
if((client_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("client socket creation failed");
exit(EXIT_FAILURE);
}
//设置IP地址可重用
int reuse = 1;
setsockopt(client_sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
// 将套接字绑定到服务器的网络地址上
if(connect(client_sockfd,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr))<0)
{
perror("connect to server failed");
exit(EXIT_FAILURE);
}
// 循环监听服务器请求
while(1)
{
printf("Please input the message:");
scanf("%s",buf);
// exit
if(strcmp(buf,"exit")==0)
{
break;
}
send(client_sockfd,buf,BUFFER_SIZE,0);
// 接收服务器端信息
len=recv(client_sockfd,buf,BUFFER_SIZE,0);
printf("receive from server:%s/n",buf);
if(len<0)
{
perror("receive from server failed");
exit(EXIT_FAILURE);
}
}
close(client_sockfd);// 关闭套接字
return 0;
}
|
Python
|
UTF-8
| 1,386
| 2.703125
| 3
|
[] |
no_license
|
import argparse
import dns.message
import dns.exception
import base64
import requests
import urllib3
# verification is lame
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def get_doh(resolver, query):
headers = {"accept": "application/dns-message", 'host': resolver}
msg = dns.message.make_query(query, dns.rdatatype.from_text('TXT')).to_wire()
msg = base64.urlsafe_b64encode(msg).decode('utf-8').strip("=")
payload = {"dns": msg}
url = "https://{}/dns-query".format(resolver)
try:
res = requests.get(url, params=payload, headers=headers, timeout=3, verify=False)
ans = dns.message.from_wire(res.content)
if len(ans.answer) > 0:
return True
except Exception as e:
print(e)
return False
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="")
parser.add_argument('input', help="Input file of doh resolver domains", type=argparse.FileType('r'))
parser.add_argument('output', help="Output file of responding doh resolver domains", type=argparse.FileType('w'))
args = parser.parse_args()
domains = args.input.readlines()
domains = list(set(domains)) # remove dupes
for d in domains:
d = d.strip()
works = get_doh(d, 'example.com')
print(f"{d} {works}")
if works:
args.output.write(d + '\n')
|
Markdown
|
UTF-8
| 1,360
| 2.984375
| 3
|
[] |
no_license
|
- # Git Workflow
The git workflow is called Gitflow and consists of how the developer works with the different branches, the branches are spaces or environments where you can code and you can create as many as you need.
The branches defined in this workflow are:

**Master** - Its the main branch, the one that is in production, and the users interact with
**Develop** - It’s a copy of the main branch but it’s a safe space to test releases and features
**Releases** - The purpose of this is to prepare to develop to merge with master
**Features** - This branch is for features and can be as small or big as needed
**Hotfix** - This branch is for bug fixes that merge directly to master and develop
Github complements this workflow with features like “Pull request”, which enables other developers to check the code before merging to master. You can add comments, approve, deny or ask for changes. GitHub has a history of all of these activities. Github understands tags, saves and preserve all the versions
- https://www.youtube.com/watch?v=aJnFGMclhU8
- http://book.git-scm.com/book/en/v2/Git-Branching-Branching-Workflows
- https://www.youtube.com/watch?v=Lj_jAFwofLs
- https://www.youtube.com/watch?v=1SXpE08hvGs
|
Python
|
UTF-8
| 366
| 4.28125
| 4
|
[] |
no_license
|
"""
Lab 9: calculate the average of a list of numbers
"""
# nums = [5, 0, 8, 3, 4, 1, 6]
nums = []
while True:
num_str = input('enter a number (or \'done\' if done): ')
if num_str == 'done':
break
else:
nums.append(float(num_str))
total = 0
for num in nums:
total += num
average = total/len(nums)
print('average: ' + str(average))
|
C#
|
UTF-8
| 4,564
| 2.8125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
namespace Shelland.ImagingLibrary.Commands.Effects
{
public class OffsetAntialiasCommand : IImageProcessing
{
private Bitmap _srcBitmap = null;
private Shelland.ImagingLibrary.Commands.SharedEffects.FloatPoint[,] _point = null;
public OffsetAntialiasCommand() { }
public OffsetAntialiasCommand(Bitmap srcBitmap, Shelland.ImagingLibrary.Commands.SharedEffects.FloatPoint[,] point)
{
_srcBitmap = srcBitmap;
_point = point;
}
public System.Drawing.Bitmap ProcessImage(Bitmap srcBitmap)
{
Bitmap bSrc = (Bitmap)_srcBitmap.Clone();
// GDI+ still lies to us - the return format is BGR, NOT RGB.
BitmapData bmData = _srcBitmap.LockBits(new Rectangle(0, 0, _srcBitmap.Width, _srcBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
BitmapData bmSrc = bSrc.LockBits(new Rectangle(0, 0, bSrc.Width, bSrc.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int scanline = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
System.IntPtr SrcScan0 = bmSrc.Scan0;
unsafe
{
byte* p = (byte*)(void*)Scan0;
byte* pSrc = (byte*)(void*)SrcScan0;
int nOffset = bmData.Stride - _srcBitmap.Width * 3;
int nWidth = _srcBitmap.Width;
int nHeight = _srcBitmap.Height;
double xOffset, yOffset;
double fraction_x, fraction_y, one_minus_x, one_minus_y;
int ceil_x, ceil_y, floor_x, floor_y;
Byte p1, p2;
for (int y = 0; y < nHeight; ++y)
{
for (int x = 0; x < nWidth; ++x)
{
xOffset = _point[x, y].X;
yOffset = _point[x, y].Y;
// Setup
floor_x = (int)Math.Floor(xOffset);
floor_y = (int)Math.Floor(yOffset);
ceil_x = floor_x + 1;
ceil_y = floor_y + 1;
fraction_x = xOffset - floor_x;
fraction_y = yOffset - floor_y;
one_minus_x = 1.0 - fraction_x;
one_minus_y = 1.0 - fraction_y;
if (floor_y >= 0 && ceil_y < nHeight && floor_x >= 0 && ceil_x < nWidth)
{
// Blue
p1 = (Byte)(one_minus_x * (double)(pSrc[floor_y * scanline + floor_x * 3]) +
fraction_x * (double)(pSrc[floor_y * scanline + ceil_x * 3]));
p2 = (Byte)(one_minus_x * (double)(pSrc[ceil_y * scanline + floor_x * 3]) +
fraction_x * (double)(pSrc[ceil_y * scanline + 3 * ceil_x]));
p[x * 3 + y * scanline] = (Byte)(one_minus_y * (double)(p1) + fraction_y * (double)(p2));
// Green
p1 = (Byte)(one_minus_x * (double)(pSrc[floor_y * scanline + floor_x * 3 + 1]) +
fraction_x * (double)(pSrc[floor_y * scanline + ceil_x * 3 + 1]));
p2 = (Byte)(one_minus_x * (double)(pSrc[ceil_y * scanline + floor_x * 3 + 1]) +
fraction_x * (double)(pSrc[ceil_y * scanline + 3 * ceil_x + 1]));
p[x * 3 + y * scanline + 1] = (Byte)(one_minus_y * (double)(p1) + fraction_y * (double)(p2));
// Red
p1 = (Byte)(one_minus_x * (double)(pSrc[floor_y * scanline + floor_x * 3 + 2]) +
fraction_x * (double)(pSrc[floor_y * scanline + ceil_x * 3 + 2]));
p2 = (Byte)(one_minus_x * (double)(pSrc[ceil_y * scanline + floor_x * 3 + 2]) +
fraction_x * (double)(pSrc[ceil_y * scanline + 3 * ceil_x + 2]));
p[x * 3 + y * scanline + 2] = (Byte)(one_minus_y * (double)(p1) + fraction_y * (double)(p2));
}
}
}
}
_srcBitmap.UnlockBits(bmData);
bSrc.UnlockBits(bmSrc);
return _srcBitmap;
}
}
}
|
Markdown
|
UTF-8
| 10,634
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
---
title: Getting Started with Microservices using Go, gRPC and Kubernetes
author: tin-rabzelj
tags:
- Go
- Kubernetes
- Docker
- gRPC
description: This article aims to provide a simple introduction to building microservices in Go, using gRPC, and deploying them to a Kubernetes cluster. It shows how to set up two containerized, scalable services, talking to each other using request/response mechanism.
cover:
path: ./cover.jpg
---
This article aims to provide a simple introduction to building microservices in Go, using gRPC, and deploying them to a Kubernetes cluster. It shows how to set up two containerized, scalable services, talking to each other using request/response mechanism.
One microservice will be responsible for calculating the greatest common divisor (GCD) of two integers. That's not something that requires building a separate service, but it will serve as an introductory example just fine. The other will serve a public REST API, and depend on first service when needed.
# Prerequisites
The best way to get a running Kubernetes cluster for development, at least for now, is to use Minikube.
Install [Minikube](https://github.com/kubernetes/minikube), [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/), [Docker](https://docs.docker.com/engine/installation/) and Protocol Buffers [compiler](https://github.com/google/protobuf).
Run Minikube. Certain commands will require root privileges.
```bash {commandLine}
minikube start [--vm-driver=<driver>]
kubectl cluster-info
```
To speed up the development, set docker to reuse Docker daemon running inside the Minikube virtual machine.
```bash {commandLine}
eval $(minikube docker-env)
```
This way, you don't have to push images to a Docker registry. For running your apps on [Google Container Engine](https://cloud.google.com/container-engine/) you'd use [Container Registry](https://cloud.google.com/container-registry/) or set up a [private container registry](https://github.com/kubernetes/kubernetes/tree/master/cluster/addons/registry) inside the cluster.
# Defining communication protocol
Services will interact synchronously, which means a client calls a service and waits for the response. One of the popular frameworks, that provides this functionality, is gRPC. To use it, you need to write definitions for message types and services in Protocol Buffer's [interface definition language](https://developers.google.com/protocol-buffers/docs/proto3) and compile them.
Create `gcd.proto` file inside `pb` directory, which is located inside your project's root directory.
```protobuf
syntax = "proto3";
package pb;
message GCDRequest {
uint64 a = 1;
uint64 b = 2;
}
message GCDResponse {
uint64 result = 1;
}
service GCDService {
rpc Compute (GCDRequest) returns (GCDResponse) {}
}
```
Navigate to the `pb` directory and run the following command.
```bash {commandLine}
protoc -I . --go_out=plugins=grpc:. ./*.proto
```
Compilation should produce `gcd.pb.go` file.
# Greatest common divisor service
The GCD service will use auto-generated code to serve a RPC endpoint which calculates the GCD.
Create `main.go` file inside `gcd` directory. Make sure you import correct packages.
```go
package main
import (
"log"
"net"
// Change this for your own project
"github.com/tinrab/kubernetes-go-grpc-tutorial/pb"
context "golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
```
In the `main` function, register a server type which will handle requests. Then start the gRPC server.
```go
type server struct{}
func main() {
lis, err := net.Listen("tcp", ":3000")
if err != nil {
log.Fatalf("Failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGCDServiceServer(s, &server{})
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("Failed to serve: %v", err)
}
}
```
Declare the `Compute` handler function. This makes the `server` type conform to the auto-generated `pb.GCDServiceServer` interface.
```go
func (s *server) Compute(ctx context.Context, r *pb.GCDRequest) (*pb.GCDResponse, error) {
a, b := r.A, r.B
for b != 0 {
a, b = b, a%b
}
return &pb.GCDResponse{Result: a}, nil
}
```
# Frontend API service
Frontend service uses [gin](https://github.com/gin-gonic/gin) web framework to serve a REST API and calls the GCD service for the actual calculation.
Create a client to communicate with the GCD service inside `main` function. Because Kubernetes (v1.3+) has a built-in DNS service, you can refer to the GCD service with the name "gcd-service", defined later on.
```go
func main() {
conn, err := grpc.Dial("gcd-service:3000", grpc.WithInsecure())
if err != nil {
log.Fatalf("Dial failed: %v", err)
}
gcdClient := pb.NewGCDServiceClient(conn)
}
```
After that, declare a handler for `/gcd/:a/:b` endpoint which reads parameters `A` and `B`, and then calls the GCD service.
```go
r := gin.Default()
r.GET("/gcd/:a/:b", func(c *gin.Context) {
// Parse parameters
a, err := strconv.ParseUint(c.Param("a"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid parameter A"})
return
}
b, err := strconv.ParseUint(c.Param("b"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid parameter B"})
return
}
// Call GCD service
req := &pb.GCDRequest{A: a, B: b}
if res, err := gcdClient.Compute(c, req); err == nil {
c.JSON(http.StatusOK, gin.H{
"result": fmt.Sprint(res.Result),
})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
})
```
Run the server.
```go
if err := r.Run(":3000"); err != nil {
log.Fatalf("Failed to run server: %v", err)
}
```
# Building Docker images
Now that your services are ready, you need to containerize them. Create Dockerfiles, one for each service, inside your project's root directory. Dockerfiles can't be located in a subdirectory, because Docker's `COPY` command can't copy files from the parent directory, which is needed in this example.
Create `Dockerfile.api`.
```dockerfile
FROM golang:1.9.1
# Change this path!
WORKDIR /go/src/github.com/tinrab/kubernetes-go-grpc-tutorial/api
COPY api .
COPY pb ../pb
RUN go get -v ./...
RUN go install -v ./...
EXPOSE 3000
CMD [ "api" ]
```
And the `Dockerfile.gcd`.
```dockerfile
FROM golang:1.9.1
WORKDIR /go/src/github.com/tinrab/kubernetes-go-grpc-tutorial/gcd
COPY gcd .
COPY pb ../pb
RUN go get -v ./...
RUN go install -v ./...
EXPOSE 3000
CMD [ "gcd" ]
```
Build both images. If you switched to Minikube's Docker daemon, they will become available inside the VM.
```bash {commandLine}
docker build -t local/gcd -f Dockerfile.gcd .
docker build -t local/api -f Dockerfile.api .
```
# Deploying to Kubernetes cluster
For each service, you'll need to configure two Kubernetes objects—a [deployment](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) and a [service](https://kubernetes.io/docs/concepts/services-networking/service/).
Explained simply, **deployments** manage sets of pods to keep the "desired state" of the cluster. **Pods** are collections of containers. Because they are created and destroyed dynamically, **services** are needed to provide fixed addresses by which to access them. Which pods are targeted by which services, is determined by label selectors.
Configuration files below are fairly standard. The important parts to keep note of are the ports, names of Docker images built earlier, and labels. Also, `imagePullPolicy` is set to `Never` to ensure Kubernetes uses images built locally.
Create `gcd.yaml` file. It declares a deployment and a service in the same file. Another practice is to separate them into `gcd-deployment.yaml` and `gcd-service.yaml`.
```yaml
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: gcd-deployment
labels:
app: gcd
spec:
selector:
matchLabels:
app: gcd
replicas: 3
template:
metadata:
labels:
app: gcd
spec:
containers:
- name: gcd
image: local/gcd
imagePullPolicy: Never
ports:
- name: gcd-service
containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
name: gcd-service
spec:
selector:
app: gcd
ports:
- port: 3000
targetPort: gcd-service
```
Create `api.yaml` file. The service type is set to `NodePort`, which makes this service accessible outside of the cluster. For the GCD service, this is set to a default value of `ClusterIP`, which means a "cluster-internal" IP address.
```yaml
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: api-deployment
labels:
app: api
spec:
selector:
matchLabels:
app: api
replicas: 1
template:
metadata:
labels:
app: api
spec:
containers:
- name: api
image: local/api
imagePullPolicy: Never
ports:
- name: api-service
containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
name: api-service
spec:
type: NodePort
selector:
app: api
ports:
- port: 3000
targetPort: api-service
```
To create these resources inside the cluster, run the following commands.
```bash {commandLine}
kubectl create -f api.yaml
kubectl create -f gcd.yaml
```
Check if all pods are running. By specifying `-w` flag, you can watch for changes.
```bash {commandLine:2-6}
kubectl get pods -w
NAME READY STATUS RESTARTS AGE
api-deployment-778049682-3vd0z 1/1 Running 0 3s
gcd-deployment-544390878-0zgc8 1/1 Running 0 2s
gcd-deployment-544390878-p78g0 1/1 Running 0 2s
gcd-deployment-544390878-r26nx 1/1 Running 0 2s
```
As set in the configuration files, API service runs on a single pod and the GCD service runs on 3.
Get the URL of the API service.
```bash {commandLine}
minikube service api-service --url
```
Finally, try it out.
```bash {commandLine}
curl http://192.168.99.100:32602/gcd/294/462
```
# Conclusion
This article showed how to get a simple stateless application running on a Kubernetes cluster. Future posts will demonstrate more thorough and interesting examples of building applications with Go and Kubernetes.
Until then, learn more about [concepts](https://kubernetes.io/docs/concepts/) of Kubernetes and find out how to perform specific [tasks](https://kubernetes.io/docs/tasks/).
Entire source code is available on [GitHub](https://github.com/tinrab/kubernetes-go-grpc-tutorial).
|
Java
|
UTF-8
| 3,368
| 2.078125
| 2
|
[] |
no_license
|
package com.e_prescription;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class addvoice extends AppCompatActivity {
TextView txt;
ImageButton img;
private ConstraintLayout mLayout;
private TextToSpeech mytts;
private SpeechRecognizer mySpeechRecognizer;
private static final int REQUEST_CODE_SPEECH_INPUT=1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addvoice);
mLayout = findViewById(R.id.linearLayout);
txt=findViewById(R.id.text);
img=findViewById(R.id.voice);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
speak();
mLayout.addView(createNewTextView(txt.getText().toString()));
}
});
TextView textView = new TextView(this);
textView.setText("New text");
}
private void processResult(String msg)
{
msg=msg.toLowerCase();
txt.setText(msg);
}
private void speak(){
Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hi speak something");
try{
startActivityForResult(i,REQUEST_CODE_SPEECH_INPUT);
}catch(Exception e){
Toast.makeText(this,""+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
private TextView createNewTextView(String text) {
// final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final ConstraintLayout.LayoutParams lparams= new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,ConstraintLayout.LayoutParams.MATCH_CONSTRAINT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText(text);
return textView;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case REQUEST_CODE_SPEECH_INPUT:{
if (resultCode==RESULT_OK&&null!=data)
{
ArrayList<String> result=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txt.setText(result.get(0));
}
break;
}
}
}
}
|
Markdown
|
UTF-8
| 2,143
| 3.34375
| 3
|
[] |
no_license
|
```html
<div id="demo" class="carousel slide" data-ride="carousel">
<!-- 指示符 -->
<ul class="carousel-indicators">
<li data-target="#demo" data-slide-to="0" class="active"></li>
<li data-target="#demo" data-slide-to="1"></li>
<li data-target="#demo" data-slide-to="2"></li>
</ul>
<!-- 轮播图片 -->
<div class="carousel-inner">
<div class="carousel-item active">
<img src="https://static.runoob.com/images/mix/img_fjords_wide.jpg">
</div>
<div class="carousel-item">
<img src="https://static.runoob.com/images/mix/img_nature_wide.jpg">
</div>
<div class="carousel-item">
<img src="https://static.runoob.com/images/mix/img_mountains_wide.jpg">
</div>
</div>
<!-- 左右切换按钮 -->
<a class="carousel-control-prev" href="#demo" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#demo" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
</div>
```
### 轮播图片上添加描述
在每个 `<div class="carousel-item">` 内添加 `<div class="carousel-caption">` 来设置轮播图片的描述文本:
```html
<div class="carousel-item">
<img src="https://static.runoob.com/images/mix/img_fjords_wide.jpg">
<div class="carousel-caption">
<h3>第一张图片描述标题</h3>
<p>描述文字!</p>
</div>
</div>
```
|类|描述|
|-:|-|
.carousel|创建一个轮播
.carousel-indicators|为轮播添加一个指示符,就是轮播图底下的一个个小点,轮播的过程可以显示目前是第几张图。
.carousel-inner|添加要切换的图片
.carousel-item|指定每个图片的内容
.carousel-control-prev|添加左侧的按钮,点击会返回上一张。
.carousel-control-next|添加右侧按钮,点击会切换到下一张。
.carousel-control-prev-icon|与 .carousel-control-prev 一起使用,设置左侧的按钮
.carousel-control-next-icon|与 .carousel-control-next 一起使用,设置右侧的按钮
.slide|切换图片的过渡和动画效果,如果你不需要这样的效果,可以删除这个类。
|||
|
JavaScript
|
UTF-8
| 659
| 2.609375
| 3
|
[] |
no_license
|
$(document).ready(function () {
var route;
var m = document.getElementById('mainMenu').getElementsByTagName('li');
var len = m.length;
for (var i = 0; i < len; i++) {
route = '{{ env.route }}';
if (route.toLowerCase() == '/' && m[i].children[0].innerHTML.toLowerCase() == 'home') {
$(m[i]).addClass('active');
break;
}
if (route.toLowerCase().indexOf(m[i].children[0].innerHTML.toLowerCase()) >= 0) {
$(m[i]).addClass('active');
break;
}
$(m[i]).removeClass('active');
}
});
|
PHP
|
UTF-8
| 627
| 2.703125
| 3
|
[] |
no_license
|
<?php declare(strict_types=1);
namespace Navplan\System\Domain\Service;
interface IHttpService {
function getRequestMethod(): string;
function getGetArgs(): array;
function getPostArgs(): array;
function getCallbackArg(string $key = "callback");
function hasGetArg(string $key): bool;
function hasPostArg(string $key): bool;
function sendHeader(string $header);
function sendPayload(string $data);
function sendArrayResponse(array $data, ?string $callbackKey = NULL, ?bool $jsonNumericCheck = FALSE);
function sendStringResponse(string $data, ?string $callbackKey = NULL);
}
|
C#
|
UTF-8
| 1,759
| 2.796875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Data;
namespace Repository.EntityFramework
{
public class Repository<TEntity> : Repository<Context, TEntity>
where TEntity : class, IEntity
{
protected Repository(Context context)
: base(context)
{
}
}
public class Repository<TContext, TEntity> : IRepository<TEntity, int>
where TContext : Context
where TEntity : class, IEntity
{
protected readonly IDbSet<TEntity> DbSet;
protected TContext DbContext { get; private set; }
protected Repository(TContext context)
{
DbContext = context;
DbSet = context.Set<TEntity>();
}
public IQueryable<TEntity> AsQueryable()
{
return DbSet.AsNoTracking();
}
public IEnumerable<TEntity> GetAll()
{
return DbSet;
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return DbSet.Where(predicate).AsQueryable().AsNoTracking();
}
public TEntity FindById(int id)
{
return DbSet.Single(t => t.ID == id);
}
public void Add(TEntity entity)
{
DbSet.Add(entity);
}
public void Remove(TEntity entity)
{
DbSet.Remove(entity);
}
public void Attach(TEntity entity)
{
DbSet.Attach(entity);
}
public IContext Context { get { return DbContext; } }
}
}
|
Java
|
UTF-8
| 3,493
| 1.757813
| 2
|
[
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-unknown"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.paimon.format.orc;
import org.apache.paimon.format.FileFormat;
import org.apache.paimon.format.FileStatsExtractorTestBase;
import org.apache.paimon.format.orc.filter.OrcFileStatsExtractor;
import org.apache.paimon.options.Options;
import org.apache.paimon.types.ArrayType;
import org.apache.paimon.types.BigIntType;
import org.apache.paimon.types.BinaryType;
import org.apache.paimon.types.BooleanType;
import org.apache.paimon.types.CharType;
import org.apache.paimon.types.DateType;
import org.apache.paimon.types.DecimalType;
import org.apache.paimon.types.DoubleType;
import org.apache.paimon.types.FloatType;
import org.apache.paimon.types.IntType;
import org.apache.paimon.types.LocalZonedTimestampType;
import org.apache.paimon.types.MapType;
import org.apache.paimon.types.MultisetType;
import org.apache.paimon.types.RowType;
import org.apache.paimon.types.SmallIntType;
import org.apache.paimon.types.TimeType;
import org.apache.paimon.types.TimestampType;
import org.apache.paimon.types.TinyIntType;
import org.apache.paimon.types.VarBinaryType;
import org.apache.paimon.types.VarCharType;
/** Tests for {@link OrcFileStatsExtractor}. */
public class OrcFileStatsExtractorTest extends FileStatsExtractorTestBase {
@Override
protected FileFormat createFormat() {
return FileFormat.fromIdentifier("orc", new Options());
}
@Override
protected RowType rowType() {
return RowType.builder()
.fields(
new CharType(8),
new VarCharType(8),
new BooleanType(),
new BinaryType(8),
new VarBinaryType(8),
new TinyIntType(),
new SmallIntType(),
new IntType(),
new BigIntType(),
new FloatType(),
new DoubleType(),
new DecimalType(5, 2),
new DecimalType(38, 18),
new DateType(),
new TimeType(),
new TimestampType(3),
new LocalZonedTimestampType(3),
// orc reader & writer currently cannot preserve a high precision timestamp
// new TimestampType(9),
new ArrayType(new IntType()),
new MapType(new VarCharType(8), new VarCharType(8)),
new MultisetType(new VarCharType(8)))
.build();
}
@Override
protected String fileCompression() {
return "LZ4";
}
}
|
JavaScript
|
UTF-8
| 3,209
| 2.703125
| 3
|
[] |
no_license
|
'use strict';
const chai = require('chai');
const sinon = require('sinon');
const { Generator } = require('../index.js');
const should = chai.should();
const debug = sinon.spy(console, 'debug');
describe('The Generator', () => {
const generator = new Generator();
it('should provide a default name with no extra call', () => {
should.exist(generator.default);
});
describe('#make', () => {
it('should generate a name with no parameters', () => {
(() => {
const name = generator.make({ debug: false, adjective: true });
should.exist(name);
}).should.not.throw();
});
it('should generate unique names', () => {
const name = generator.make({ debug: false, adjective: true });
const name2 = generator.make({ debug: false, adjective: true });
should.not.equal(name, name2);
});
it('should generate 10k names without issues', () => {
(() => {
for (let i = 0; i < 10000; i += 1) {
generator.make({ debug: false, adjective: true, nouns: Math.floor(Math.random() * 10) });
}
}).should.not.throw();
});
it('should throw with an invalid race', () => {
(() => {
generator.make({ debug: false, adjective: true, race: 'duviri' });
}).should.throw();
});
it('should throw with an invalid type', () => {
(() => {
generator.make({ debug: false, adjective: true, type: 'verb' });
}).should.throw();
});
it('should call console debug when debugging', () => {
generator.make({ debug: true, adjective: true });
debug.callCount.should.equal(1);
});
it('should include race if requested', () => {
const name = generator.make({
debug: false, adjective: true, type: 'names', includeRace: true, race: 'grineer',
});
name.should.include('Grineer');
});
it('should generate a string with no spaces if told to ignore spaces', () => {
(() => {
const name = generator.make({
debug: false, adjective: true, race: 'grineer', spaces: false,
});
name.should.not.include(' ');
}).should.not.throw();
});
});
describe('#getNoun', () => {
it('should not throw with no parameters', () => {
(() => {
generator.random;
}).should.not.throw();
});
it('should throw if provided a bad race', () => {
(() => {
generator.getNoun([], { race: 'duviri' });
}).should.throw();
});
it('should throw if provided a bad type', () => {
(() => {
generator.getNoun([], { race: 'grineer', type: 'verb' });
}).should.throw();
});
it('should succeed if not provided a race', () => {
(() => {
generator.getNoun([], { type: 'names' });
}).should.not.throw();
});
});
describe('#another', () => {
it('should retrieve another entry not already in tokens', () => {
(() => {
const another = generator.another(['De\'Thaym']);
another.should.not.include('De\'Thaym');
});
});
it('should not throw with no parameters', () => {
(() => {
generator.another();
}).should.not.throw();
});
});
});
|
C#
|
UTF-8
| 3,936
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using NewLife.Collections;
using NewLife.Data;
namespace NewLife.Http
{
/// <summary>Http请求响应基类</summary>
public abstract class HttpBase
{
#region 属性
/// <summary>协议版本</summary>
public String Version { get; set; } = "1.1";
/// <summary>内容长度</summary>
public Int32 ContentLength { get; set; } = -1;
/// <summary>内容类型</summary>
public String ContentType { get; set; }
/// <summary>请求或响应的主体部分</summary>
public Packet Body { get; set; }
/// <summary>主体长度</summary>
public Int32 BodyLength => Body == null ? 0 : Body.Total;
/// <summary>是否已完整。头部未指定长度,或指定长度后内容已满足</summary>
public Boolean IsCompleted => ContentLength < 0 || ContentLength <= BodyLength;
/// <summary>头部集合</summary>
public IDictionary<String, String> Headers { get; set; } = new NullableDictionary<String, String>(StringComparer.OrdinalIgnoreCase);
/// <summary>获取/设置 头部</summary>
/// <param name="key"></param>
/// <returns></returns>
public String this[String key] { get => Headers[key] + ""; set => Headers[key] = value; }
#endregion
#region 解析
/// <summary>快速验证协议头,剔除非HTTP协议。仅排除,验证通过不一定就是HTTP协议</summary>
/// <param name="pk"></param>
/// <returns></returns>
public static Boolean FastValidHeader(Packet pk)
{
// 性能优化,Http头部第一行以请求谓语或响应版本开头,然后是一个空格。最长谓语Options/Connect,版本HTTP/1.1,不超过10个字符
var p = pk.IndexOf(new[] { (Byte)' ' }, 0, 10);
if (p < 0) return false;
return true;
}
private static readonly Byte[] NewLine = new[] { (Byte)'\r', (Byte)'\n', (Byte)'\r', (Byte)'\n' };
/// <summary>分析请求头</summary>
/// <param name="pk"></param>
/// <returns></returns>
public Boolean Parse(Packet pk)
{
if (!FastValidHeader(pk)) return false;
var p = pk.IndexOf(NewLine);
if (p < 0) return false;
var str = pk.ReadBytes(0, p).ToStr();
// 截取
var lines = str.Split("\r\n");
Body = pk.Slice(p + 4);
// 分析头部
for (var i = 1; i < lines.Length; i++)
{
var line = lines[i];
p = line.IndexOf(':');
if (p > 0) Headers[line[..p]] = line[(p + 1)..].Trim();
}
ContentLength = Headers["Content-Length"].ToInt(-1);
ContentType = Headers["Content-Type"];
// 分析第一行
if (!OnParse(lines[0])) return false;
return true;
}
/// <summary>分析第一行</summary>
/// <param name="firstLine"></param>
protected abstract Boolean OnParse(String firstLine);
#endregion
#region 读写
/// <summary>创建请求响应包</summary>
/// <returns></returns>
public virtual Packet Build()
{
var data = Body;
var len = data != null ? data.Count : -1;
var header = BuildHeader(len);
var rs = new Packet(header.GetBytes())
{
Next = data
};
return rs;
}
/// <summary>创建头部</summary>
/// <param name="length"></param>
/// <returns></returns>
protected abstract String BuildHeader(Int32 length);
#endregion
}
}
|
C#
|
UTF-8
| 2,416
| 3.625
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Week4Lab
{
class Program
{
static void Print<T>(string label, IEnumerable<T> results)
{
Console.WriteLine(label);
foreach (var result in results)
Console.WriteLine("\t{0}", result);
}
static void Main(string[] args)
{
Company c = new Company();
// 1. List the names of the employees who do not have a supervisor.
// The results should combine FirstName and LastName into one string.
var r1 = c.Employees.Where(e => e.SupervisorId == null)
.OrderBy(e => e.FirstName)
.Select(e => e.FirstName + " " + e.LastName)
.Distinct();
Print("Q1 (Method)", r1 );
// 2. List the last names of the employees whose last name starts with D.
// The results should be listed in alphabetic order without duplicates.
var r2 = c.Employees.Where(e => e.LastName.StartsWith("D"))
.OrderBy(e => e.LastName)
.Select(e => e.LastName)
.Distinct();
Print("Q2 (Method)", r2);
// 3. List the names of the employees who are on the project Blue.
// The results should combine FirstName and LastName into one string.
var r3 = c.Projects.Where(p => p.Name == "Blue")
.Select(p => p.Members).Single();
Print("Q3 (Method)", r3);
// 4. Find Jane Doe's subordinates, i.e. the employees who are supervised by Jane Doe.
var r4 = c.Employees.Where(p => p.SupervisorId == 2)
.Select(e => e.FirstName + " " + e.LastName);
Print("Q4 (Method)", r4);
var r6 = (from e in c.Employees where e.FirstName == "Jane" && e.LastName == "Doe" select e.Id)
.Intersect((from p in c.Employees select p));
Print("Q5er (Query)", r6);
// 5. Find the employee(s) who were hired in 2015 and worked on the project Blue.
var r5 = (from e in c.Employees where e.DateHired.Year == 2015 select e)
.Intersect((from p in c.Projects where p.Name == "Blue" select p.Members).Single());
Print("Q5 (Query)", r5);
}
}
}
|
Java
|
UTF-8
| 2,516
| 3.796875
| 4
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* John Watson performs an operation called a right circular rotation on an
* array of integers, [a0, a1, ..., a(n-1)]. After performing one right circular
* rotation operation, the array is transformed from [a0, a1, ..., a(n-1)] to
* [a(n-1), a0, ..., a(n-2)].
*
* Watson performs this operation k times. To test Sherlock's ability to identify
* the current element at a particular position in the rotated array, Watson asks
* q queries, where each query consists of a single integer, m, for which you
* must print the element at index m in the rotated array (i.e., the value of a(m)).
*
* Input Format:
* The first line contains 3 space-separated integers, n, k, and q, respectively.
* The second line contains n space-separated integers, where each integer i
* describes array element a(i) (where 0<=i<n).
* Each of the subsequent lines contains a single integer denoting .
*
* Constraints:
* 1 <= n <= 10^5
* 1 <= a(i) <= 10^5
* 1 <= k <= 10^5
* 1 <= q <= 500
* 0 <= m <= n-1
*
* Output Format:
* For each query, print the value of the element at index m of the rotated
* array on a new line.
*
* Sample Input:
* 3 2 3
* 1 2 3
* 0
* 1
* 2
*
* Sample Output:
* 2
* 3
* 1
*
* Explanation:
* After the first rotation, the array becomes [3, 1, 2].
* After the second (and final) rotation, the array becomes [2, 3, 1].
*
* Let's refer to the array's final state as array b. For each query, we just
* have to print the value of b(m) on a new line:
* * m = 0, so we print 2 on a new line.
* * m = 1, so we print 3 on a new line.
* * m = 2, so we print 1 on a new line.
*
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // size of array
int k = in.nextInt(); // rotations
int q = in.nextInt(); // queries
int[] a = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
List<Integer> aList = new ArrayList<>();
for(int num:a){
aList.add(num);
}
for(int j = 1; j<=k; j++){
int lastN = aList.get(n-1);
aList.add(0, lastN);
aList.remove(n);
}
int[] newA = aList.stream().mapToInt(i->i).toArray();
for(int a0 = 0; a0 < q; a0++){
int m = in.nextInt();
System.out.println(newA[m]);
}
}
}
|
Markdown
|
UTF-8
| 1,223
| 3.015625
| 3
|
[] |
no_license
|
学习笔记
1. 有效的字母异位词 DiffPostionWord.java
2. 移动零 MoveZero.java
3. 删除排序数组中的重复项 RemoveDupByTarget.java
4. 合并两个有序链表 Merge2SortLinkedList.java
5. 两数之和 TwoNumAdd.java
6. 合并两个有序数组 Merge2Array.java
我选择了6个简单的习题来完成本次的作业。
原本的算法基础比较薄弱, 又不想以一个不好的开端开始,因此没有选择中等以上难度的。但是他们会在我的计划清单中,保证以后的课程不落下为前提完成他们。
第一周收获:
1. 在做三数之和时,学到了一种新的“判断”、“递增”写法
while (i < j && nums[i] == nums[++i]);
等价于:
while (i < j && nums[i] == nums[i+1]) i++;
2. 跳表是新接触的数据结构,但是好像未得到应用,接下来需要更深入的了解下。个人理解同mysql的索引结构B+树很像。
3. 栈和队列原理都很清楚,在平时工作中应用较少,Deque需要重点学习下,相关的api需要熟练使用。
4. 好多基于链表的题,链表的结构不熟悉,不会使用测试用例,需要想办法解决。
5. 落下了很多视频的课后作业,需要补上。
|
JavaScript
|
UTF-8
| 3,526
| 2.53125
| 3
|
[] |
no_license
|
import React, { useState, useEffect } from 'react';
import './App.css';
import { Container, Button, Row, Col } from 'react-bootstrap';
import Header from './components/Header';
import Variable from './components/Variable';
import Results from './components/Results';
function App() {
const [oilRefineries, setOilRefineries] = useState(0);
const [lubricantPlants, setLubricantPlants] = useState(0);
const [heavyOilCrackingPlants, setHeavyOilCrackingPlants] = useState(0);
const [lightOilCrackingPlants, setLightOilCrackingPlants] = useState(0);
const [heavyOil, setHeavyOil] = useState(0);
const [lightOil, setLightOil] = useState(0);
const [petroleumGas, setPetroleumGas] = useState(0);
const [lubricant, setLubricant] = useState(0);
const increase = type => {
switch (type) {
case 'Oil Refineries':
setOilRefineries(oilRefineries + 1);
break;
case 'Lubricant Plants':
setLubricantPlants(lubricantPlants + 1);
break;
case 'Heavy Oil Cracking Plants':
setHeavyOilCrackingPlants(heavyOilCrackingPlants + 1);
break;
case 'Light Oil Cracking Plants':
setLightOilCrackingPlants(lightOilCrackingPlants + 1);
break;
default:
break;
}
};
const decrease = type => {
switch (type) {
case 'Oil Refineries':
if (oilRefineries !== 0) {
setOilRefineries(oilRefineries - 1);
}
break;
case 'Lubricant Plants':
if (lubricantPlants !== 0) {
setLubricantPlants(lubricantPlants - 1);
}
break;
case 'Heavy Oil Cracking Plants':
if (heavyOilCrackingPlants !== 0) {
setHeavyOilCrackingPlants(heavyOilCrackingPlants - 1);
}
break;
case 'Light Oil Cracking Plants':
if (lightOilCrackingPlants !== 0) {
setLightOilCrackingPlants(lightOilCrackingPlants - 1);
}
break;
default:
break;
}
};
useEffect(() => {
setHeavyOil(
oilRefineries * 5 - lubricantPlants * 10 - heavyOilCrackingPlants * 20
);
setLightOil(
oilRefineries * 9 +
heavyOilCrackingPlants * 15 -
lightOilCrackingPlants * 15
);
setPetroleumGas(oilRefineries * 11 + lightOilCrackingPlants * 10);
setLubricant(lubricantPlants * 10);
}, [
oilRefineries,
lubricantPlants,
heavyOilCrackingPlants,
lightOilCrackingPlants
]);
return (
<Container className="app">
<Header />
<Row className="content">
<Col>
Variables
<hr />
<Variable
name="Oil Refineries"
value={oilRefineries}
increase={increase}
decrease={decrease}
/>
<Variable
name="Lubricant Plants"
value={lubricantPlants}
increase={increase}
decrease={decrease}
/>
<Variable
name="Heavy Oil Cracking Plants"
value={heavyOilCrackingPlants}
increase={increase}
decrease={decrease}
/>
<Variable
name="Light Oil Cracking Plants"
value={lightOilCrackingPlants}
increase={increase}
decrease={decrease}
/>
</Col>
<Results
heavyOil={heavyOil}
lightOil={lightOil}
petroleumGas={petroleumGas}
lubricant={lubricant}
/>
</Row>
</Container>
);
}
export default App;
|
Java
|
UTF-8
| 8,441
| 1.96875
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"MPL-1.0",
"W3C",
"GPL-1.0-or-later",
"LicenseRef-scancode-unicode",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"CDDL-1.0",
"MIT",
"Apache-2.0",
"JSON",
"EPL-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unicode-icu-58"
] |
permissive
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.content;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.persistence.Cacheable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.dspace.content.comparator.NameAscendingComparator;
import org.dspace.content.factory.ContentServiceFactory;
import org.dspace.content.service.CommunityService;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.eperson.Group;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.proxy.HibernateProxyHelper;
/**
* Class representing a community
* <P>
* The community's metadata (name, introductory text etc.) is loaded into'
* memory. Changes to this metadata are only reflected in the database after
* <code>update</code> is called.
*
* @author Robert Tansley
*/
@Entity
@Table(name = "community")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, include = "non-lazy")
public class Community extends DSpaceObject implements DSpaceObjectLegacySupport {
@Column(name = "community_id", insertable = false, updatable = false)
private Integer legacyId;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "community2community",
joinColumns = {@JoinColumn(name = "parent_comm_id")},
inverseJoinColumns = {@JoinColumn(name = "child_comm_id")}
)
private final Set<Community> subCommunities = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "subCommunities")
private final Set<Community> parentCommunities = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "communities", cascade = {CascadeType.PERSIST})
private final Set<Collection> collections = new HashSet<>();
@OneToOne
@JoinColumn(name = "admin")
/** The default group of administrators */
private Group admins;
/**
* The logo bitstream
*/
@OneToOne
@JoinColumn(name = "logo_bitstream_id")
private Bitstream logo = null;
@Transient
protected transient CommunityService communityService;
/**
* Protected constructor, create object using:
* {@link org.dspace.content.service.CommunityService#create(Community, Context)}
* or
* {@link org.dspace.content.service.CommunityService#create(Community, Context, String)}
*/
protected Community() {
}
/**
* Takes a pre-determined UUID to be passed to the object to allow for the
* restoration of previously defined UUID's.
*
* @param uuid Takes a uuid to be passed to the Pre-Defined UUID Generator
*/
protected Community(UUID uuid) {
this.predefinedUUID = uuid;
}
void addSubCommunity(Community subCommunity) {
subCommunities.add(subCommunity);
setModified();
}
public void removeSubCommunity(Community subCommunity) {
subCommunities.remove(subCommunity);
setModified();
}
/**
* Get the logo for the community. <code>null</code> is return if the
* community does not have a logo.
*
* @return the logo of the community, or <code>null</code>
*/
public Bitstream getLogo() {
return logo;
}
void setLogo(Bitstream logo) {
this.logo = logo;
setModified();
}
/**
* Get the default group of administrators, if there is one. Note that the
* authorization system may allow others to be administrators for the
* community.
* <P>
* The default group of administrators for community 100 is the one called
* <code>community_100_admin</code>.
*
* @return group of administrators, or <code>null</code> if there is no
* default group.
*/
public Group getAdministrators() {
return admins;
}
void setAdmins(Group admins) {
this.admins = admins;
setModified();
}
/**
* Get the collections in this community. Throws an SQLException because
* creating a community object won't load in all collections.
*
* @return array of Collection objects
*/
public List<Collection> getCollections() {
// We return a copy because we do not want people to add elements to this collection directly.
// We return a list to maintain backwards compatibility
Collection[] output = collections.toArray(new Collection[] {});
Arrays.sort(output, new NameAscendingComparator());
return Arrays.asList(output);
}
void addCollection(Collection collection) {
collections.add(collection);
}
void removeCollection(Collection collection) {
collections.remove(collection);
}
/**
* Get the immediate sub-communities of this community. Throws an
* SQLException because creating a community object won't load in all
* collections.
*
* @return array of Community objects
*/
public List<Community> getSubcommunities() {
// We return a copy because we do not want people to add elements to this collection directly.
// We return a list to maintain backwards compatibility
Community[] output = subCommunities.toArray(new Community[] {});
Arrays.sort(output, new NameAscendingComparator());
return Arrays.asList(output);
}
/**
* Return the parent community of this community, or null if the community
* is top-level
*
* @return the immediate parent community, or null if top-level
*/
public List<Community> getParentCommunities() {
// We return a copy because we do not want people to add elements to this collection directly.
// We return a list to maintain backwards compatibility
Community[] output = parentCommunities.toArray(new Community[] {});
Arrays.sort(output, new NameAscendingComparator());
return Arrays.asList(output);
}
void addParentCommunity(Community parentCommunity) {
parentCommunities.add(parentCommunity);
}
void clearParentCommunities() {
parentCommunities.clear();
}
public void removeParentCommunity(Community parentCommunity) {
parentCommunities.remove(parentCommunity);
setModified();
}
/**
* Return <code>true</code> if <code>other</code> is the same Community
* as this object, <code>false</code> otherwise
*
* @param other object to compare to
* @return <code>true</code> if object passed in represents the same
* community as this object
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof Community)) {
return false;
}
Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(other);
if (this.getClass() != objClass) {
return false;
}
final Community otherCommunity = (Community) other;
return this.getID().equals(otherCommunity.getID());
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(getID()).toHashCode();
}
/**
* return type found in Constants
*
* @return Community type
*/
@Override
public int getType() {
return Constants.COMMUNITY;
}
@Override
public String getName() {
String value = getCommunityService()
.getMetadataFirstValue(this, MetadataSchemaEnum.DC.getName(), "title", null, Item.ANY);
return value == null ? "" : value;
}
@Override
public Integer getLegacyId() {
return legacyId;
}
private CommunityService getCommunityService() {
if (communityService == null) {
communityService = ContentServiceFactory.getInstance().getCommunityService();
}
return communityService;
}
}
|
Python
|
UTF-8
| 12,255
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
import ujson as json
import random
from enum import Enum
from RAIchu_Enums import MoveType, AIType, PredictionType, Player
from Battle_Resources import Battle_Resources
from RAIchu_Utils import RAIchu_Utils
class Battle_State():
def __init__(self, current_state_str, move_required, prev_action):
self.state_str = current_state_str
self.info = json.loads(current_state_str)
self.move_required = move_required
self.opp_move_required = MoveType.BATTLE_ACTION
#prev_action is the set of actions (player, opponent) taken to reach this state. Both are -1 if this is the root
#of the search tree.
self.prev_action = prev_action
def generate_player_moves(self):
if self.move_required == MoveType.NONE:
return []
moves = [0] *(RAIchu_Utils.NUM_MOVES + RAIchu_Utils.NUM_POKEMON)
if self.move_required == MoveType.BATTLE_ACTION or self.move_required == MoveType.BATTLE_SWITCH:
for i in range(len(self.info['pokemon'])):
if i != self.info['active'] and self.info['pokemon'][i]['condition'] != 0:
moves[i] = 1
if self.move_required == MoveType.BATTLE_ACTION:
for i in range(len(self.info['pokemon'][self.info['active']]['moves'])):
if self.info['pokemon'][self.info['active']]['disabled'][i] == 0:
moves[RAIchu_Utils.NUM_POKEMON+i] = 1
return moves
def generate_opponent_moves(self):
#Generates all moves the opponent could make from the current game state. Considers all possible moves
#of all pokemon the opponent is known to have.
if self.opp_move_required == MoveType.NONE:
return []
moves = [0] *(len(self.info['opp_pokemon'][self.info['opp_active']]['possible_moves']) + RAIchu_Utils.NUM_POKEMON)
if self.opp_move_required == MoveType.BATTLE_ACTION or self.opp_move_required == MoveType.BATTLE_SWITCH:
for i in range(len(self.info['opp_pokemon'])):
if i != self.info['opp_active']:
if len(self.info['opp_pokemon'][i]) == 0:
#Unknown state
moves[i] = -1
elif self.info['opp_pokemon'][i]['condition'] != 0:
moves[i] = 1
if self.opp_move_required == MoveType.BATTLE_ACTION:
for i in range(len(self.info['opp_pokemon'][self.info['opp_active']]['possible_moves'])):
if self.info['opp_pokemon'][self.info['opp_active']]['disabled'][i] == 0:
moves[RAIchu_Utils.NUM_POKEMON+i] = 1
return moves
def generate_next_game_states(self, pred_type):
#Generates all the game states reachable from a single valid action from the current game state
next_states = []
#on a forced switch, only one player will take an action
if self.move_required == MoveType.BATTLE_SWITCH:
switches = self.generate_player_moves()
next_states = [-1 for k in range(len(switches))]
for i in range(len(switches)):
if switches[i] == 1:
next_states[i] = self.simulate_action_sequence(i, -1, pred_type)
if self.opp_move_required == MoveType.BATTLE_SWITCH:
switches = self.generate_opponent_moves()
next_states = [-1 for k in range(len(switches))]
for i in range(len(switches)):
if switches[i] == 1:
next_states[i] = self.simulate_action_sequence(-1, i, pred_type)
if self.move_required == MoveType.BATTLE_ACTION and self.opp_move_required == MoveType.BATTLE_ACTION:
action_sequences = self.generate_action_sequences()
next_states = action_sequences.copy()
for i in range(len(action_sequences)):
for j in range(len(action_sequences[0])):
if action_sequences[i][j] == 1:
next_states[i][j] = self.simulate_action_sequence(i, j, pred_type)
else:
next_states[i][j] = -1
return next_states
def generate_action_sequences(self):
move_vec = self.generate_player_moves()
opp_move_vec = self.generate_opponent_moves()
actions = [[-1]*(len(opp_move_vec)) for k in range((RAIchu_Utils.NUM_MOVES + RAIchu_Utils.NUM_POKEMON))]
for i in range((RAIchu_Utils.NUM_MOVES + RAIchu_Utils.NUM_POKEMON)):
for j in range(len(opp_move_vec)):
if move_vec[i] == 1:
actions[i][j] = opp_move_vec[j]
return actions
def simulate_action_sequence(self, move, opp_move, pred_type):
#Simulate what the game state will be the next turn if the given actions are taken. Returns a new Battle_State
self.update_state_str()
next_state = Battle_State(self.state_str, MoveType.BATTLE_ACTION, (move, opp_move))
#Switches always happen first. Relative order of switches does not matter.
if move < RAIchu_Utils.NUM_POKEMON and move >= 0:
RAIchu_Utils.apply_switch(next_state, Player.SELF, move)
if opp_move >= RAIchu_Utils.NUM_POKEMON:
RAIchu_Utils.simulate_move(next_state.info['opp_pokemon'][next_state.info['opp_active']], next_state.info['pokemon'][next_state.info['active']], Player.OPPONENT, next_state.info['field'], next_state.info['opp_pokemon'][next_state.info['opp_active']]['possible_moves'][opp_move-RAIchu_Utils.NUM_POKEMON], pred_type)
if opp_move < RAIchu_Utils.NUM_POKEMON and opp_move >= 0:
RAIchu_Utils.apply_switch(next_state, Player.OPPONENT, opp_move)
if move >= RAIchu_Utils.NUM_POKEMON:
RAIchu_Utils.simulate_move(next_state.info['pokemon'][next_state.info['active']], next_state.info['opp_pokemon'][next_state.info['opp_active']], Player.SELF, next_state.info['field'], next_state.info['pokemon'][next_state.info['active']]['moves'][move-RAIchu_Utils.NUM_POKEMON], pred_type)
#if both sides attack, the pokemon with a higher speed stat acts first. If the pokemon with lower speed has no hp left after
#the pokemon with higher speed attacks, they will not get to attack and will need to switch.
if move >= RAIchu_Utils.NUM_POKEMON and opp_move >= RAIchu_Utils.NUM_POKEMON:
if RAIchu_Utils.get_stat(next_state.info['opp_pokemon'][next_state.info['opp_active']], 'spe') > RAIchu_Utils.get_stat(next_state.info['pokemon'][next_state.info['active']], 'spe'):
RAIchu_Utils.simulate_move(next_state.info['opp_pokemon'][next_state.info['opp_active']], next_state.info['pokemon'][next_state.info['active']], Player.OPPONENT, next_state.info['field'], next_state.info['opp_pokemon'][next_state.info['opp_active']]['possible_moves'][opp_move-RAIchu_Utils.NUM_POKEMON], pred_type)
if next_state.info['pokemon'][next_state.info['active']]['condition'] > 0:
RAIchu_Utils.simulate_move(next_state.info['pokemon'][next_state.info['active']], next_state.info['opp_pokemon'][next_state.info['opp_active']], Player.SELF, next_state.info['field'], next_state.info['pokemon'][next_state.info['active']]['moves'][move-RAIchu_Utils.NUM_POKEMON], pred_type)
else:
RAIchu_Utils.simulate_move(next_state.info['pokemon'][next_state.info['active']], next_state.info['opp_pokemon'][next_state.info['opp_active']], Player.SELF, next_state.info['field'], next_state.info['pokemon'][next_state.info['active']]['moves'][move-RAIchu_Utils.NUM_POKEMON], pred_type)
if next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] > 0:
RAIchu_Utils.simulate_move(next_state.info['opp_pokemon'][next_state.info['opp_active']], next_state.info['pokemon'][next_state.info['active']], Player.OPPONENT, next_state.info['field'],next_state.info['opp_pokemon'][next_state.info['opp_active']]['possible_moves'][opp_move-RAIchu_Utils.NUM_POKEMON], pred_type)
if next_state.info['pokemon'][next_state.info['active']]['condition'] <= 0:
next_state.move_required = MoveType.BATTLE_SWITCH
next_state.opp_move_required = MoveType.NONE
next_state.info['pokemon'][next_state.info['active']]['condition'] = 0
else:
if next_state.info['pokemon'][next_state.info['active']]['item'] == 'leftovers':
next_state.info['pokemon'][next_state.info['active']]['condition'] += 6
if next_state.info['pokemon'][next_state.info['active']]['condition'] > 100:
next_state.info['pokemon'][next_state.info['active']]['condition'] = 100
if 'burn' in next_state.info['pokemon'][next_state.info['active']]['status']:
next_state.info['pokemon'][next_state.info['active']]['condition'] -= 6
elif 'psn' in next_state.info['pokemon'][next_state.info['active']]['status'] or 'tox' in next_state.info['pokemon'][next_state.info['active']]['status']:
next_state.info['pokemon'][next_state.info['active']]['condition'] -= 12
if next_state.info['pokemon'][next_state.info['active']]['condition'] <= 0:
next_state.info['pokemon'][next_state.info['active']]['condition'] = 0
next_state.move_required = MoveType.BATTLE_SWITCH
next_state.opp_move_required = MoveType.NONE
if next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] <= 0:
next_state.move_required = MoveType.NONE
next_state.opp_move_required = MoveType.BATTLE_SWITCH
next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] = 0
else:
if next_state.info['opp_pokemon'][next_state.info['opp_active']]['item'] == 'leftovers':
next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] += 6
if next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] > 100:
next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] = 100
if 'burn' in next_state.info['opp_pokemon'][next_state.info['opp_active']]['status']:
next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] -= 6
elif 'psn' in next_state.info['opp_pokemon'][next_state.info['opp_active']]['status'] or 'tox' in next_state.info['opp_pokemon'][next_state.info['opp_active']]['status']:
next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] -= 12
if next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] <= 0:
next_state.info['opp_pokemon'][next_state.info['opp_active']]['condition'] = 0
next_state.move_required = MoveType.BATTLE_SWITCH
next_state.opp_move_required = MoveType.NONE
#If both pokemon faint on the same turn due to status or recoil
if next_state.info['pokemon'][next_state.info['active']]['condition'] == 0:
next_state.move_required = MoveType.BATTLE_SWITCH
return next_state
def update_state_str(self):
self.state_str = json.dumps(self.info)
|
Java
|
UTF-8
| 584
| 1.820313
| 2
|
[] |
no_license
|
package com.qa.Assessment;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class LoadUpPage {
@FindBy(xpath = "//*[@id=\"j_username\"]")
private WebElement user;
@FindBy(xpath = "//*[@id=\"main-panel\"]/div/form/table/tbody/tr[2]/td[2]/input")
private WebElement pass;
@FindBy(xpath = "//*[@id=\"yui-gen1-button\"]")
private WebElement submitButton;
public void logIn(String username, String password)
{
user.click();
user.sendKeys(username);
pass.click();
pass.sendKeys(password);
submitButton.submit();
}
}
|
Java
|
UTF-8
| 1,366
| 2.921875
| 3
|
[] |
no_license
|
class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
paragraph = paragraph.replaceAll("[^a-zA-z0-9]"," ").toLowerCase();
String[] words = paragraph.split("\\s+");
HashMap<String, Integer> map = new HashMap<String, Integer>();
String maxString="";
int max = 0;
HashSet<String> ban = new HashSet<>();
for(int i = 0; i < banned.length;i++)
{
ban.add(banned[i]);
}
for(String word:words)
{
System.out.println("word:"+word);
if(!ban.contains(word))
{
map.put(word,map.getOrDefault(word,0)+1);
System.out.println("word:"+word+" | map.get:"+map.get(word));
}
}
for(String word:words)
{
if(!ban.contains(word)){
// System.out.println("Max:"+max +" map.get(word):"+map.get(word));
if(max < map.get(word))
{
max = map.get(word);
maxString = word;
System.out.println("max:"+max +" maxString:"+maxString);
}
}
}
return maxString;
//return Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
}
}
|
Markdown
|
UTF-8
| 3,149
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
# Flyweight \(解释器模式\)
## Code
```javascript
let examCarNum = 0 // 驾考车总数
/* 驾考车对象 */
class ExamCar {
constructor(carType) {
examCarNum++
this.carId = examCarNum
this.carType = carType ? '手动档' : '自动档'
this.usingState = false // 是否正在使用
}
/* 在本车上考试 */
examine(candidateId) {
return new Promise((resolve => {
this.usingState = true
console.log(`考生- ${ candidateId } 开始在${ this.carType }驾考车- ${ this.carId } 上考试`)
setTimeout(() => {
this.usingState = false
console.log(`%c考生- ${ candidateId } 在${ this.carType }驾考车- ${ this.carId } 上考试完毕`, 'color:#f40')
resolve() // 0~2秒后考试完毕
}, Math.random() * 2000)
}))
}
}
/* 手动档汽车对象池 */
ManualExamCarPool = {
_pool: [], // 驾考车对象池
_candidateQueue: [], // 考生队列
/* 注册考生 ID 列表 */
registCandidates(candidateList) {
candidateList.forEach(candidateId => this.registCandidate(candidateId))
},
/* 注册手动档考生 */
registCandidate(candidateId) {
const examCar = this.getManualExamCar() // 找一个未被占用的手动档驾考车
if (examCar) {
examCar.examine(candidateId) // 开始考试,考完了让队列中的下一个考生开始考试
.then(() => {
const nextCandidateId = this._candidateQueue.length && this._candidateQueue.shift()
nextCandidateId && this.registCandidate(nextCandidateId)
})
} else this._candidateQueue.push(candidateId)
},
/* 注册手动档车 */
initManualExamCar(manualExamCarNum) {
for (let i = 1; i <= manualExamCarNum; i++) {
this._pool.push(new ExamCar(true))
}
},
/* 获取状态为未被占用的手动档车 */
getManualExamCar() {
return this._pool.find(car => !car.usingState)
}
}
ManualExamCarPool.initManualExamCar(3) // 一共有3个驾考车
ManualExamCarPool.registCandidates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) // 10个考生来考试
```
## 解釋
* 運用共享技術有效地支持大量細節物件的複用。系統只使用少量的物件,而這些物件都很相似,狀態變化很小,可以實現對物件的多次複用。由於享元模式要求能夠共享的物件必須是較細節的物件,因此又稱為輕量級模式。
## 場景
* 文件上傳需要創建多個文件實體的時候
* 如果一個應用程式使用了大量的物件,而這些大量的物件造成了很大的儲存開銷就應該考慮使用享元模式
## 優點
* 減少物件的創建,降低系統的內存,使效率提高
## 缺點
* 提升系統的複雜度,需要分離出外部狀態和內部狀態,而且外部狀態具有固有化的性質,不應該隨著內部狀態的變化而變化,否則會造成系統的混亂。
|
Python
|
UTF-8
| 6,533
| 2.640625
| 3
|
[] |
no_license
|
import base64
import os
import cv2
import requests
from aip import AipOcr # 百度AI的文字识别库
import matplotlib.pyplot as plt
import time
import queue
import numpy as np
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
path1 = './video/material/%s.jpg' # 视频转为图片存放的路径(帧)
path2 = './video/img/%s.jpg' # 图片经过边缘提取后存放的路径
path3 = './video/captions/%s.jpg' # 图片经过边缘提取后存放的路径
begin = 10
end = 100
step_size = 10
videoName = "material"
def tailor_video():
# 在这里把后缀接上
video_path = os.path.join("D:/project1/", videoName + '.mp4')
times = 0
frameFrequency = 10 # 提取视频的频率,每10帧提取一个
outPutDirName = './video/' + videoName + '/'
if not os.path.exists(outPutDirName):
# 如果文件目录不存在则创建目录
os.makedirs(outPutDirName)
camera = cv2.VideoCapture(video_path)
while True:
times += 1
res, image = camera.read()
if not res:
print('not res , not image')
break
if times % frameFrequency == 0:
cv2.imwrite(outPutDirName + str(times) + '.jpg', image) # 文件目录下将输出的图片名字命名为10.jpg这种形式
print(outPutDirName + str(times) + '.jpg')
print('图片提取结束')
def view_img(img):
cv2.imshow("img", img)
cv2.waitKey()
Q = queue.Queue()
dx = [0, 1, 0, -1, 1, -1, 1, -1]
dy = [1, 0, -1, 0, -1, 1, 1, -1]
vis = None
class POS:
def __init__(self, x, y):
self.x = x
self.y = y
def BFS(img, x, y, flag):
global vis
theta_low = 1
#theta_high = 50
theta_high = 500
n = img.shape[0]
m = img.shape[1]
Q.put(POS(x, y))
vis[x][y] = 1
min_x = x
max_x = x
min_y = y
max_y = y
while not Q.empty():
top = Q.get()
for i in range(8):
X = dx[i] + top.x
Y = dy[i] + top.y
if X < 0 or X >= n or Y < 0 or Y >= m or img[X][Y]==0:
continue
if flag:
img[X][Y] = 0
elif vis[X][Y]:
continue
min_x = min(min_x, X)
max_x = max(max_x, X)
min_y = min(min_y, Y)
max_y = max(max_y, Y)
vis[X][Y] = 1
tmp = POS(X, Y)
Q.put(tmp)
len_x = (max_x - min_x + 1)
len_y = (max_y - min_y + 1)
"""
if not flag:
print(len_x, len_y)
"""
"""
ret = True
if len_x<=theta_low and len_y<=theta_low:
ret=False
if len_x>=theta_high and len_y>=theta_high:
ret=False
if len_x<=theta_low and len_y<=theta_high and
"""
ret = len_x >= theta_low and len_x <= theta_high and len_y >= theta_low and len_y <= theta_high
return ret
def size_filter(img):
# np.set_printoptions(threshold=np.inf)
# print(img)
n = img.shape[0]
m = img.shape[1]
global vis
vis = np.zeros((n, m))
for i in range(n):
for j in range(m):
if img[i][j] > 0:
flag = BFS(img, i, j, False)
if not flag:
img[i][j] = 0
BFS(img, i, j, True)
#view_img(img)
def static(img):
theta = 40
n = img.shape[0]
m = img.shape[1]
row = np.zeros(n)
column = np.zeros(m)
# 统计区域像素
for i in range(n):
for j in range(m):
x = img[i][j]
if x > theta:
row[i] += 1
column[j] += 1
# 求灰度比例
row /= m
column /= n
# 根据阈值分段
row = row > 0.08
column = column > 0.005
for i in range(n):
for j in range(m):
if img[i][j]>theta:
img[i][j] *= (row[i] and column[j])
else:
img[i][j]=0
#view_img(img)
def abstract(): # 截取字幕
for i in range(begin, end, step_size):
fname1 = path1 % str(i)
print(fname1)
img = cv2.imread(fname1)
if img is None:
break;
print(img.shape)
cropped = img
"""
imgray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
thresh = 200
ret, binary = cv2.threshold(imgray, thresh, 255, cv2.THRESH_BINARY) # 输入灰度图,输出二值图
binary1 = cv2.bitwise_not(binary) # 取反
cv2.imwrite(path2 % str(i), binary1)
"""
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
"""
# sobel边缘检测
edges = cv2.Sobel(img, cv2.CV_16S, 1, 0)
# 浮点型转成uint8型
edges = cv2.convertScaleAbs(edges)
"""
img = cv2.Laplacian(img, cv2.CV_8U, ksize=3)
size_filter(img)
static(img)
#view_img(img)
#thresh=100
#_,img = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY) # 输入灰度图,输出二值图
cv2.imwrite(path3 % str(i), img)
# 定义一个函数,用来访问百度API,
def requestApi(img):
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
params = {"image": img,'language_type':'CHN_ENG'}
#access_token = '24.125c4d691b4c97c080b647f0d07c5419.2592000.1634915041.282335-24887036'
access_token='24.8b5758ec70247b64ccb608d52e720c1c.2592000.1634969842.282335-24889932'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
results=response.json()
return results
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
# 将读取出来的图片转换为b64encode编码格式
return base64.b64encode(fp.read())
def subtitle():
for i in range(begin,end,step_size):
time.sleep(0.5) # api-qpr=2
fname1=path3 % str(i)
print(fname1)
image = get_file_content(fname1)
try:
#print(requestApi(image))
ret = requestApi(image)
#print(ret)
results=ret['words_result']
if ret.get('error_msg'):
print(ret['error_msg'])
for item in results:
print(item['words'])
except Exception as e:
print(e)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
#abstract()
subtitle()
"""
reader = easyocr.Reader(['ch_sim', 'en'])
result = reader.readtext('./video/captions2/10.jpg')
"""
|
Python
|
UTF-8
| 1,759
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
from typing import Any, Dict, List, Tuple
import pytest
from construct import Byte, Struct, Construct, Padded
from constructutils import InlineError, InliningStruct, Inline, InlineStruct
data: List[Tuple[Construct, Dict[str, Any], bytes]] = [
(
InliningStruct(
'a' / Byte
),
{'a': 1},
b'\x01'
),
(
InliningStruct(
InlineStruct('a' / Byte)
),
{'a': 1},
b'\x01'
),
(
InliningStruct(
'a' / Byte,
'struct' / Struct('a' / Byte),
InlineStruct('b' / Byte, 'c' / Byte),
'd' / Byte
),
{'a': 1, 'struct': {'a': 2}, 'b': 3, 'c': 4, 'd': 5},
b'\x01\x02\x03\x04\x05'
)
]
@pytest.mark.parametrize('struct, expected, data', data)
def test_parse(data, struct, expected):
assert struct.parse(data) == expected
@pytest.mark.parametrize('struct, value, expected', data)
def test_build(value, struct, expected):
assert struct.build(value) == expected
def test_inline_simple():
s = InliningStruct(
'a' / Byte,
Inline(Padded(2, Struct(
'b' / Byte
))),
'c' / Byte
)
assert s.parse(b'\x01\x02\x03\x04') == {'a': 1, 'b': 2, 'c': 4}
assert s.build({'a': 1, 'b': 2, 'c': 3}) == b'\x01\x02\x00\x03'
def test_duplicate():
s = InliningStruct(
'a' / Byte,
InlineStruct(
'a' / Byte
)
)
assert s.parse(b'\x01\x02') == {'a': 2}
assert s.build({'a': 1}) == b'\x01\x01'
def test_noinlining():
s = Struct(
InlineStruct('a' / Byte)
)
with pytest.raises(InlineError):
s.parse(b'x')
with pytest.raises(KeyError):
s.build({'a': b'x'})
|
Shell
|
UTF-8
| 1,052
| 3.96875
| 4
|
[] |
no_license
|
#!/bin/sh
#
# ocland This shell script takes care of starting and stopping
# ocland server
#
# Author: Cercos-Pita J.L. <jlcercos@gmail.com>
#
# description: ocland server is a service that wait for clients \
# connections in order to perform OpenCL massive computations \
# remotely.
# Involved variables
OCLAND_SERVER_BIN=@CMAKE_INSTALL_PREFIX@/@CMAKE_INSTALL_BINDIR@/ocland_server
OCLAND_SERVER_LOG=/var/log/ocland.log
# Handle manual control parameters like start, stop, status, restart, etc.
start() {
echo -n "Starting ocland server: "
nohup $OCLAND_SERVER_BIN --log-file $OCLAND_SERVER_LOG > $OCLAND_SERVER_LOG.nohup 2> $OCLAND_SERVER_LOG.err < /dev/null &
echo "[Done]"
return 0
}
stop() {
echo -n "Shutting down ocland server: "
killall ocland_server
echo "[Done]"
return 0
}
case "$1" in
start)
# Start daemons.
start
;;
stop)
stop
;;
status)
status ocland_server
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
exit 1
;;
esac
exit 0
|
Python
|
UTF-8
| 206
| 2.796875
| 3
|
[] |
no_license
|
import sys
data = open(sys.argv[1]).read().split('\n')
for i in range(len(data)):
data[i] = data[i].replace(r'\\', '').replace(r'\"', '')
with open(sys.argv[1], 'w') as f:
f.write('\n'.join(data))
|
C#
|
UTF-8
| 2,457
| 2.53125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Factory_management
{
public partial class attendance : Form
{
public attendance()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void agent_save_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you really want to add ?", "Confirmation", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{/*
con.Open();
String sql = "delete * from emp_details where Name = '"+textBox1.Text+"'";
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable d1 = new DataTable();
sda.Fill(d1);
dataGridView1.DataSource = d1;
con.Close();*/
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
}
private void clear_attendance_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you really want to clear ?", "Confirmation", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{/*
con.Open();
String sql = "delete * from emp_details where Name = '"+textBox1.Text+"'";
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable d1 = new DataTable();
sda.Fill(d1);
dataGridView1.DataSource = d1;
con.Close();*/
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
}
private void search_attendance_Click(object sender, EventArgs e)
{
searchAttendance_form sa = new searchAttendance_form();
sa.Show();
this.Dispose();
}
}
}
|
C
|
UTF-8
| 1,372
| 2.65625
| 3
|
[] |
no_license
|
#ifndef _SCHEDULER_H_
#define _SCHEDULER_H_
#include "types.h"
/* \brief Initializes scheduler.
*
* Initializing scheduler entails:
* - allocating and preparing idle process state
* - allocating and preparing first process state
* - setting program counter to code passed as arg
* - inserting first process in queue
*/
void scheduler_init(pcb_code_t);
void scheduler_enqueue_process(pcb_t *);
void scheduler_kill_process(pid_t);
void scheduler_block_current(int *, state_t *);
/* \brief After ints and sysc handled, resumes execution
*
* Multiple cases possible, refer to implementation for details
*/
void scheduler_resume(bool, state_t *);
/* \brief Runs next process from queue
*
* A new process (compared to the last one) runs, so its
* time slice is reset. Time spent in kernel is set, and
* process runs.
*/
void scheduler_run();
/* \brief Assigns time spent to current_proc as kernel or user
*
* Depending on boolean, switch_tick - getTODLO() is assigned
* to either user or kernel time of current_proc
*/
void scheduler_account_time(bool);
/* \brief Launches exception handler if one was registered
*
* If a handler was registered, the handler is launched.
* Otherwise, the process and its progeny are terminated
* Refer to implementation for considerations on location
*/
void scheduler_handle_exception(int, state_t *);
#endif
|
PHP
|
UTF-8
| 674
| 2.515625
| 3
|
[] |
no_license
|
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\TagResource;
class ProjectResource extends JsonResource {
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request) {
return [
"id" => $this->id,
"title" => $this->title,
"description" => $this->description,
"logo" => $this->logo,
"mockup" => $this->mockup,
"visible" => $this->visible,
"tags" => TagResource::collection($this->tags)
];
}
}
|
Java
|
UTF-8
| 9,054
| 2.078125
| 2
|
[] |
no_license
|
package com.socrata;
/*
Copyright (c) 2010 Socrata.
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.
*/
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Base class under which all Socrata classes inherit.
*
* @author aiden.scandella@socrata.com
*/
public abstract class ApiBase {
protected DefaultHttpClient httpClient;
protected HttpContext httpContext;
protected HttpHost httpHost;
protected ResourceBundle properties;
protected String username, password, appToken;
protected List<BatchRequest> batchQueue;
/**
* Default class constructor.
*/
public ApiBase() {
loadProperties();
finishConstruction();
}
/**
* Copy settings from an existing object
* @param properties Specifies credentials and hostnames
*/
public ApiBase(ResourceBundle properties) {
this.properties = properties;
this.httpClient = new DefaultHttpClient();
finishConstruction();
}
private void finishConstruction() {
// Store these because we need them for some specialized calls
this.username = properties.getString("username");
this.password = properties.getString("password");
this.appToken = properties.getString("app_token");
batchQueue = new ArrayList<BatchRequest>();
setupBasicAuthentication();
httpHost = new HttpHost(properties.getString("hostname"),
Integer.valueOf(properties.getString("hostport")));
httpContext = new BasicHttpContext();
}
/**
* Class constructor with user-specified username/password.
*
* @param username the user account to connect with
* @param password the password to connect with
* @return a new Socrata API object with specified credentials
*/
public ApiBase(String username, String password) {
loadProperties();
this.username = username;
this.password = password;
setupBasicAuthentication();
}
/**
* Empty out the batchQueue, sending stored data back to Socrata servers
* @return success or failure
*/
public boolean sendBatchRequest() {
if ( batchQueue == null || batchQueue.size() == 0 ) {
log(Level.WARNING, "No batch requests in queue, ignoring call to sendBatchRequest" , null);
return false;
}
Collection batches = new ArrayList<Map>();
for( BatchRequest b : batchQueue ) {
batches.add(b.data());
}
JSONObject bodyObject = new JSONObject();
try {
bodyObject.put("requests", batches);
}
catch ( JSONException ex ) {
log(Level.SEVERE, "Could not convert array of batch requests to JSON", ex);
return false;
}
HttpPost request = new HttpPost(httpBase() + "/batches");
try {
request.setEntity(new StringEntity(bodyObject.toString()));
log(Level.INFO, bodyObject.toString());
}
catch ( UnsupportedEncodingException ex ) {
log(Level.SEVERE, "Could not encode JSON data into HTTP entity", ex);
return false;
}
JsonPayload response = performRequest(request);
if ( !isErroneous(response) ) {
log(Level.INFO, "Completed batch request, clearing out queue of " +
batchQueue.size() + " entries.");
batchQueue.clear();
return true;
}
return false;
}
/**
* Performs a generic request against Socrata API servers
* @param request Apache HttpRequest object (e.g. HttpPost, HttpGet)
* @return JSON array representation of the response
*/
protected JsonPayload performRequest(HttpRequestBase request) {
HttpResponse response;
HttpEntity entity;
request.addHeader("X-App-Token", this.appToken);
try {
response = httpClient.execute(httpHost, request, httpContext);
if( response.getStatusLine().getStatusCode() != 200 ) {
log(java.util.logging.Level.SEVERE, "Got status " +
response.getStatusLine().getStatusCode() + ": " +
response.getStatusLine().toString() +
" while performing request on " + request.getURI(), null);
return null;
}
return new JsonPayload(response);
}
catch (Exception ex) {
log(Level.SEVERE, "Error caught trying to perform HTTP request", ex);
return null;
}
}
/**
* Loads necessary connection details from disk.
*/
private void loadProperties() {
this.properties = ResourceBundle.getBundle("com.socrata.resources");
this.httpClient = new DefaultHttpClient();
}
/**
* Sets up http authentication (BASIC) for default requests
*/
private void setupBasicAuthentication() {
Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(AuthScope.ANY, defaultcreds);
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.AUTH_CACHE, basicAuth);
httpClient.setCredentialsProvider(credProvider);
}
/**
* Returns the base URL for http requests
* @return the base URL for http requests
*/
public String httpBase() {
return "http://" + properties.getString("hostname") +
":" + properties.getString("hostport");
}
/**
* Sends a message to the logger
* @param l the level of severity
* @param message a message to put in the logs
* @param exception an exception, if applicable, that triggered this log entry
*/
protected void log(Level l, String message, Exception exception) {
Logger.getLogger(ApiBase.class.getName()).log(l, message, exception);
}
/**
* Sends a message to the logger
* @param l the level of severity
* @param message a message to put in the logs
*/
protected void log(Level l, String message) {
log(l, message, null);
}
/**
* Inspects the JSON payload returned from the API server for error messages
* @param response the response
* @return true if response contains errors
*/
protected boolean isErroneous(JsonPayload response) {
if ( response == null ) {
return true;
}
// If the message couldn't be parsed into JSON
if( response.getResponse() != null && !response.getResponse().isEmpty()) {
log(Level.WARNING, "Non-JSON response: " + response.getResponse(), null);
return true;
} else if ( response.getObject() != null ) {
try {
if (response.getObject().has("error")) {
log(Level.SEVERE, "Error in server response: " +
response.getObject().getString("error"), null);
return true;
}
} catch (JSONException ex) {
Logger.getLogger(ApiBase.class.getName()).log(Level.SEVERE, null, ex);
}
} else if ( response.getArray() != null ) {
// An array means it's not erroneous
return false;
}
// No response means no error
return false;
}
}
|
PHP
|
UTF-8
| 185
| 2.546875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
namespace App\Models\ViewModels;
use App\Models\User;
class UserProfile {
public $user;
public function __construct(User $user) {
$this->user = $user;
}
}
|
Java
|
UTF-8
| 1,297
| 2.453125
| 2
|
[] |
no_license
|
package ac.za.cput.service.user.implement;
import ac.za.cput.domain.user.Employee;
import ac.za.cput.repository.user.EmployeeRepository;
import ac.za.cput.repository.user.implement.EmployeeRepositoryImpl;
import ac.za.cput.service.user.EmployeeService;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class EmployeeServiceImpl implements EmployeeService {
public static EmployeeServiceImpl service = null;
private EmployeeRepository repository;
private EmployeeServiceImpl(){
this.repository= EmployeeRepositoryImpl.getRepository();
}
public static EmployeeServiceImpl getService(){
if(service == null) service = new EmployeeServiceImpl();
return service;
}
@Override
public Set<Employee> getAll() {
return this.repository.getAll();
}
@Override
public Employee create(Employee employee) {
return this.repository.create(employee);
}
@Override
public Employee update(Employee employee) {
return this.repository.update(employee);
}
@Override
public void delete(String employee) {
repository.delete(employee);
}
@Override
public Employee read(String employee) {
return this.repository.read(employee);
}
}
|
Markdown
|
UTF-8
| 1,869
| 2.640625
| 3
|
[] |
no_license
|
# Article D217-1
Les associations régulièrement déclarées ayant pour objet statutaire de mettre à disposition des femmes et des familles
toutes informations, notamment familiale, sociale, professionnelle, économique, éducative et de santé, tendant à promouvoir
les droits des femmes et l'égalité entre les femmes et les hommes ainsi qu'à lutter contre les violences et les préjugés
sexistes, peuvent recevoir des subventions de l'Etat sous réserve d'être agréées en tant que centres d'information sur les
droits des femmes et des familles dans les conditions prévues au présent chapitre.
Sont considérées comme des informations, au sens du présent chapitre, les données à caractère documentaire et les
renseignements juridiques délivrés de façon gratuite et exclusive de toute consultation juridique au sens de la loi n°
71-1130 du 31 décembre 1971 modifiée portant réforme de certaines professions judiciaires et juridiques.
Les informations sont délivrées dans des conditions de nature à garantir leur confidentialité lors de séances d'entretien
individuelles ou collectives se déroulant dans des locaux d'accès public dénommés “ permanences d'information juridique ” et
pouvant, le cas échéant, avoir lieu par visioconférence.
**Liens relatifs à cet article**
_Cite_:
- Loi n°71-1130 du 31 décembre 1971
_Cité par_:
- Arrêté du 20 janvier 2016 (V)
- Code de l'action sociale et des familles - art. D217-3 (V)
- Code de l'action sociale et des familles - art. R536-1 (V)
- Code de l'action sociale et des familles - art. R555-1 (V)
- Code de l'action sociale et des familles - art. R565-1 (M)
- Code de l'action sociale et des familles - art. R575-1 (M)
- Code de l'action sociale et des familles - art. R583-1 (V)
_Modifié par_:
- Décret n°2019-1383 du 18 décembre 2019 - art. 3
|
Python
|
UTF-8
| 4,712
| 2.671875
| 3
|
[] |
no_license
|
import gym
import math
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as T
env = gym.make('Breakout-v0').unwrapped
steps_done = 0
# set up matplotlib
is_ipython = 'inline' in matplotlib.get_backend()
if is_ipython:
from IPython import display
Transition = namedtuple('Transition',
('state', 'action', 'reward', 'newstate'))
class ReplayMemory(object):
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
self.position = 0
def push(self, *args):
if len(self.memory) < self.capacity:
self.memory.append(None)
self.memory[self.position] = Transition(*args)
self.position = (self.position + 1) % self.capacity #replaces oldest transitions once at capacity
def sample(self, batch_size):
return random.sample(self.memory, batch_size)
def __len__(self):
return len(self.memory)
class DQN(nn.Module):
def __init__(self):
super(DQN, self).__init__()
self.conv1 = nn.Conv2d(4, 16, kernel_size=8, stride=4)
self.conv2 = nn.Conv2d(16, 32, kernel_size=4, stride=2)
self.fc1 = nn.Linear(2592, 256)
self.fc2 = nn.Linear(256, 6)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = x.view(-1, 2592)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
def act(self, state):
global steps_done
roll = random.random()
if steps_done < 1000000:
eps = 1-0.9*steps_done/1000000
else:
eps = 0.05
steps_done += 1
if roll > eps:
with torch.no_grad():
return self(state).max(1)[1].view(1,1)
else:
return torch.tensor([[random.randrange(6)]], dtype=torch.long)
resize = T.Compose([T.ToPILImage(),
T.ToTensor()])
def preprocess(obs):
im = Image.fromarray(obs)
im = im.convert('L')
im = im.resize((84,110))
w, h = im.size
im = im.crop((0, 26, w, h))
return np.array(im)
dqn = DQN()
target_dqn = DQN()
optimizer = optim.RMSprop(dqn.parameters())
memory = ReplayMemory(10000)
BATCH_SIZE = 32
GAMMA = 0.99
TARGET_UPDATE = 10
def optimize_model():
if len(memory) < BATCH_SIZE:
return
transitions = memory.sample(BATCH_SIZE)
batch = Transition(*zip(*transitions))
non_terminal_mask = torch.tensor(tuple(map(lambda s: s is not None,
batch.newstate)), dtype=torch.uint8)
non_terminal_newstates = torch.cat([s for s in batch.newstate if s is not None])
states = torch.cat(batch.state)
actions = torch.cat(batch.action)
rewards = torch.cat(batch.reward)
policy_Qs = dqn(states).gather(1, actions)
newstate_Vs = torch.zeros(BATCH_SIZE)
newstate_Vs[non_terminal_mask] = target_dqn(non_terminal_newstates).max(1)[0].detach()
target_Qs = rewards + GAMMA*newstate_Vs
loss = F.mse_loss(policy_Qs, target_Qs.unsqueeze(1))
optimizer.zero_grad()
loss.backward()
for param in dqn.parameters():
param.grad.data.clamp_(-1, 1)
optimizer.step()
for i in range(1000):
frame0 = env.reset()
frame1 = frame0
frame2 = frame0
frame3 = frame0
preprocessed = (preprocess(frame0), preprocess(frame1),
preprocess(frame2), preprocess(frame3))
state = np.stack(preprocessed, axis=2)
state = resize(state).unsqueeze(0)
total_reward = 0
while True:
env.render()
#action = env.action_space.sample()
action = dqn.act(state)
frame3 = frame2
frame2 = frame1
frame1 = frame0
frame0, reward, done, info = env.step(action.item())
preprocessed = (preprocess(frame0), preprocess(frame1),
preprocess(frame2), preprocess(frame3))
if not done:
newstate = np.stack(preprocessed, axis=2)
newstate = resize(newstate).unsqueeze(0)
else:
newstate = None
memory.push(state, action, torch.tensor([reward]), newstate)
print(dqn(state))
state = newstate
total_reward += reward
optimize_model()
if done:
#for i in range(len(preprocessed)):
#plt.subplot(1, 4, i+1)
#plt.imshow(preprocessed[i])
print("Got %d points" % total_reward)
plt.show()
break
if i % TARGET_UPDATE == 0:
target_dqn.load_state_dict(dqn.state_dict())
|
Java
|
UTF-8
| 946
| 3
| 3
|
[] |
no_license
|
package mechanics.rb2d.shapes;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import de.physolator.usr.components.Vector2D;
import de.physolator.usr.tvg.Shape;
import de.physolator.usr.tvg.TVG;
public class Circle extends AbstractShape {
public double radius;
public Circle() {
this(1);
}
public Circle(double radius) {
this.radius = radius;
}
@Override
public void paint(TVG tvg, Vector2D position, double phi) {
Vector2D rm = new Vector2D(radius, 0);
Vector2D line = rotateVector2D(rm, phi);
line.add(position);
tvg.beginShape(Shape.POLYGON_LINE_LOOP);
tvg.drawCircle(position, radius);
tvg.drawLine(position.x, position.y, line.x, line.y);
tvg.endShape();
}
private Vector2D rotateVector2D(Vector2D r, double rot) {
return new Vector2D(r.x * cos(rot) - r.y * sin(rot), r.x * sin(rot) + r.y * cos(rot));
}
@Override
public double getI(double m) {
return m*radius*radius;
}
}
|
Swift
|
UTF-8
| 601
| 2.984375
| 3
|
[] |
no_license
|
//
// NetworkHandler.swift
// TMDb
//
// Created by Atiqa Ikram on 21/02/2020.
// Copyright © 2020 Atiqa Ikram . All rights reserved.
//
import Foundation
struct NetworkHandler{
/// Sends a request for the requested API endpoint and returns a completion closure with Data object or error string
/// - Parameter completion: returns data or error string
func fetchData(path: URL, completion: @escaping (_ data: Data?,_ error: Error?)-> ()){
URLSession.shared.dataTask(with: path as URL) { (data, urlResponse, error) in
completion(data, error)
}.resume()
}
}
|
Python
|
UTF-8
| 1,789
| 3.4375
| 3
|
[] |
no_license
|
# Finds max and min # of extra entities per website (out of all articles WITH CAPTIONS)
import csv
data_file = "/Users/mirandadayadkins/Desktop/Media_Bias/Data/processed_data/Main_Entities/" \
"caption_main_figures_edited.csv"
# Finds maximum number of extra entities in the captions from a given website
def find_max_extra_entities(website):
max_extras = 0
with open(data_file, 'rt')as file:
open_file = csv.reader(file)
for row in open_file:
# Only check articles from certain website
if row[1] == website:
try:
if int(row[8]) > max_extras:
max_extras = int(row[8])
except ValueError:
continue
return max_extras
# Uses previous function to find the minimum number of extra entities in the captions from a given website
def find_min_extra_entities(website, max_extras):
min_extras = max_extras
with open(data_file, 'rt')as file:
open_file = csv.reader(file)
for row in open_file:
# Only check articles from certain website
if row[1] == website:
try:
if int(row[8]) < min_extras:
min_extras = int(row[8])
except ValueError:
continue
return min_extras
def main():
print("Max # of Extra Entities:\n")
fox_max_extras = find_max_extra_entities('FOX')
nyt_max_extras = find_max_extra_entities('NYT')
print('FOX: ', fox_max_extras, "\n")
print('NYT: ', nyt_max_extras, '\n\n')
print("0% Matches:\n")
print('FOX: ', find_min_extra_entities('FOX', fox_max_extras), '\n')
print('NYT: ', find_min_extra_entities('NYT', nyt_max_extras), "\n")
main()
|
Markdown
|
UTF-8
| 2,753
| 2.984375
| 3
|
[] |
no_license
|
---
id: one-to-many-relations
title: One to Many relations
---
Este tutorial vai mostrar como é fácil incluir relações Um para Muitos em seu projeto móvel.
Vamos começar baixando o Projeto Starter:
<div className="center-button">
<a className="button button--primary"
href="https://github.com/4d-go-mobile/tutorial-OneToManyRelations/archive/c006015afeb0e134d872152f53b8cd5e4dcb59bb.zip">Starter project</a>
</div>
Neste tutorial, vamos construir um **Task app** colorido usando 4D for iOS.

Mas primeiro, vamos olhar a estrutura de nosso banco de dados:

Como pode ver, há um link One to Many chamado **tasks** que vamos usar em nosso iOS app para exibir as tasks/tarefas(**to Many**).dos funcionários'(**One**)
Agora vá direto para o menu Open > Mobile project... selecione *Time Keeper* e vá para a seção **Structure**.
## Structure section
Pode ver a **relação de tasks/tarefas** que vimos antes... Publique!
Agora isso vai operar como qualquer outro campo pelo resto do processo de criação do app.

:::dica
Quando passar o mouse over, uma dica exibe o nome de tabela originando a relação.
:::
## Labels & Icons section
A relação Um para Muitos está agora disponível na seção **Etiquetas e ìcones**.
É importante saber que incluindo uma relação Um para Muitos vai criar um botão no app iOS gerado.
Então, na seção Etiquetas & Icones você vai definir:
* um botão Etiqueta
* um botão ícone
* um título será exibido na vista de destino (para indicar de onde vem, por exemplo).

## Forms section
* Vá para a seção Formulários e solte a relação *tasks* no formulário detalhado Employee Task.

## Build and Run
1. Do formulário Employee List, clique em um empregado.
2. Isso vai abrir o formulário detalhado employee/empregados, onde você verá um novo botão **Relation** !
3. Clique no botão Relation para exibir as tarefas dos funcionários

Muito bem! Você incluiu com sucesso as relações Um a Muitos em seu projeto móvel.
Baixe o projeto terminado:
<div className="center-button">
<a className="button button--primary"
href="https://github.com/4d-go-mobile/tutorial-OneToManyRelations/releases/latest/download/tutorial-OneToManyRelations.zip">Baixar</a>
</div>
|
Java
|
UTF-8
| 188
| 1.585938
| 2
|
[] |
no_license
|
package com.my.admin.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
public enum E {
@Autowired
UNKNOWN;
}
|
Python
|
UTF-8
| 619
| 3.203125
| 3
|
[] |
no_license
|
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
'''
print(lemmatizer.lemmatize("cats")) #cat
print(lemmatizer.lemmatize("cacti")) #cactus
print(lemmatizer.lemmatize("geese")) #goose
print(lemmatizer.lemmatize("rocks")) #rock
print(lemmatizer.lemmatize("python")) #python
'''
print(lemmatizer.lemmatize("better")) #better
print(lemmatizer.lemmatize("better", pos="a")) # Since adjective, good (pos is "part of speech")
print(lemmatizer.lemmatize("best", pos="a")) # Since adjective, good
print(lemmatizer.lemmatize("ran")) #ran
print(lemmatizer.lemmatize("ran", pos="v")) # Since verb, run
|
JavaScript
|
UTF-8
| 656
| 2.6875
| 3
|
[] |
no_license
|
/*Middleware authorization:
Verify the existence of a jwt in the header of the HTTP request*/
const jwt = require('jsonwebtoken');
require('dotenv/config');
const authorization = (req, res, next) => {
const token = req.header('x-auth-token');
if (!token) return res.status(401).json({message:"Access denied. No token", code:-10});
try{
const valid = jwt.verify(token, process.env.JWT_PRIVATE_KEY);
req.user = valid;
next();///<valid token, pass to other middleware
} catch(err){
res.status(401).json({message:"Access denied. Bad token", code:-11});
}
}
module.exports = {
authorization
};
|
JavaScript
|
UTF-8
| 800
| 4.28125
| 4
|
[] |
no_license
|
// 观察者模式:观察者、被观察者(在被观察者中存储观察者) 之间有关系
// 订阅和发布没有关系 观察者模式是基于发布订阅的
// 被观察者
class Subject{
constructor(){
this.arr=[]//存储谁在观察
this.state="很开心"
}
attach(o){
this.arr.push(o)
}
setState(newState){
this.state=newState
this.arr.forEach(o=>o.update(newState))
}
}
// 观察者
class Observer{
constructor(name){
this.name=name;
}
update(newState){
console.log(this.name ,"孩子状态",newState)
}
}
let s=new Subject("孩子")
let o1=new Observer("爸爸")
let o2=new Observer("妈妈")
s.attach(o1)
s.attach(o2)
// console.log(s.state)
s.setState("不开心")
console.log(s.state)
|
Ruby
|
UTF-8
| 1,237
| 4.25
| 4
|
[] |
no_license
|
# Problem 4
#
# A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
require 'rubygems'
require 'pp'
def is_a_palindrome?(number)
number = number.to_s
middle = number.length/2
return number[0,middle] == number[middle,number.length].reverse
end
def largest_palindromic_number_for_x_digits(number_of_digits)
time_start = Time.now
largest_palindrome = 0
starting_number = String.new
ending_number = "1"
number_of_digits.times { starting_number << "9" }
starting_number = starting_number.to_i
(number_of_digits-1).times { ending_number << "0" }
ending_number = ending_number.to_i
ending_number.upto(starting_number) do |ending|
ending.upto(starting_number) do |number|
result = ending * number
if is_a_palindrome?(result)
largest_palindrome = result if result > largest_palindrome
end
end
end
time_end = Time.now
duration = time_end - time_start
pp "Largest palindrome for #{number_of_digits}: #{largest_palindrome}"
pp "Duration: #{duration}"
end
largest_palindromic_number_for_x_digits(3)
|
Java
|
UTF-8
| 245
| 2
| 2
|
[] |
no_license
|
public class Main
{
public static void main(String[] args) {
BioStudents b=new BioStudents();
b.display();
b.displaybio();
System.out.println();
Students s=new Students();
s.display();
}
}
|
JavaScript
|
UTF-8
| 86
| 2.8125
| 3
|
[] |
no_license
|
var nome = "Alexander"
var sobreNome = "Brandao"
console.log(nome + " " + sobreNome);
|
PHP
|
UTF-8
| 234
| 3.046875
| 3
|
[
"BSD-4-Clause-UC",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"TCL",
"ISC",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"blessing",
"MIT"
] |
permissive
|
--TEST--
array_values() preserves next index from source array when shallow-copying
--FILE--
<?php
$a = [1,2,3];
unset($a[2]);
$b = array_values($a);
$b[] = 4;
print_r($b);
--EXPECT--
Array
(
[0] => 1
[1] => 2
[2] => 4
)
|
Python
|
UTF-8
| 628
| 2.8125
| 3
|
[] |
no_license
|
from typing import Dict
from bs4 import BeautifulSoup
import requests
import re
URL = "https://www.johnlewis.com/2018-apple-ipad-pro-12-9-inch-a12x-bionic-ios-wi-fi-cellular-512gb/space-grey/p3834614"
TAG_NAME = "p"
QUERY = {"class": "price price--large"}
request = requests.get(URL)
content = request.content
soup = BeautifulSoup(content, "html.parser")
element = soup.find(TAG_NAME, QUERY)
string_price = element.text.strip()
pattern = re.compile(r"(\d+,?\d+\.\d+)")
match = pattern.search(string_price)
found_price = match.group(1)
without_commas = found_price.replace(",", "")
price = float(without_commas)
print(price)
|
Java
|
UTF-8
| 783
| 2.15625
| 2
|
[] |
no_license
|
package by.Andrey.jis3telegram.command;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class CommandServiceTest {
// @Test
// public void getCommand() {
// System.out.println(CommandService.getWordFromCommand("/get word put over"));
// }
@Test
public void getMeaningsFromWebSite() {
System.out.println(CommandService.getMeaningsFromWebSite("put "));
}
// @Test
// public void checkCommand() {
// boolean expected = CommandService.checkCommand("/get pv get");
// System.out.println(expected);
// }
//
// @org.junit.Test
// public void getWordFromCommandAdded() {
// String result = CommandService.getWordFromCommandAdd("/added get off");
// System.out.println(result);
// }
}
|
Java
|
UTF-8
| 146
| 1.507813
| 2
|
[] |
no_license
|
package PAGES;
import org.openqa.selenium.WebDriver;
public class EntertainmentPage {
public EntertainmentPage(WebDriver driver){
}
}
|
C#
|
UTF-8
| 2,803
| 2.765625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
namespace TravelOnline.Class.NewClass
{
public class TopMenu
{
public static String GetTopMenuString(string MenuType)
{
StringBuilder Strings = new StringBuilder();
//string m1 = "", m2 = "", m3 = "", m4 = "", m5 = "", m6 = "";
//switch (MenuType)
//{
// case "Index":
// m1 = " class=\"active\"";
// break;
// case "OutBound":
// m2 = " class=\"active\"";
// break;
// case "InLand":
// m3 = " class=\"active\"";
// break;
// case "FreeTour":
// m4 = " class=\"active\"";
// break;
// case "Cruises":
// m5 = " class=\"active\"";
// break;
// case "Visa":
// m6 = " class=\"active\"";
// break;
// default:
// break;
//}
Strings.Append("<div id=\"menu\">");
Strings.Append("<div class=\"container\">");
Strings.Append("<div class=\"row\">");
Strings.Append("<div class=\"span12\">");
Strings.Append("<ul class=\"nav nav-menu\" style=\"margin-bottom: 0px;\">");
if (MenuType == "Index")
{
Strings.Append("<li id=topmenu class=\"active\"><a style=\"WIDTH: 156px;\" href=\"javascript:void(0);\">旅游目的地</a></li>");
}
else
{
Strings.Append("<li id=topmenu class=\"active\"><a style=\"WIDTH: 100px;\" href=\"javascript:void(0);\">旅游目的地<i style=\"margin-left: 5px;\" class=\"icon-chevron-down icon-white\"></i></a></li>");
Strings.Append("<li><a href=\"/\">首页</a></li>");
}
//Strings.Append("<li" + m1 + "><a href=\"/\">首页</a></li>");
Strings.Append("<li><a href=\"outbound.aspx\">出国旅游</a></li>");
Strings.Append("<li><a href=\"inland.aspx\">国内旅游</a></li>");
Strings.Append("<li><a href=\"freetour.aspx\">自由行</a></li>");
Strings.Append("<li><a href=\"cruises.aspx\">邮轮旅游</a></li>");
Strings.Append("<li><a href=\"visa.aspx\">签证</a></li>");
Strings.Append("</ul>");
Strings.Append("</div>");
Strings.Append("</div>");
Strings.Append("</div>");
Strings.Append("</div>");
return Strings.ToString();
}
}
}
|
C#
|
UTF-8
| 1,907
| 2.75
| 3
|
[] |
no_license
|
using Priority_Queue;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AStar : Algorithms {
public AStar()
{
name = "A*";
}
public override void StartAlgorithm(TDTile start, TDTile end, TGMap map)
{
algoSteps.Clear();
SimplePriorityQueue<TDTile> frontier = new SimplePriorityQueue<TDTile>();
frontier.Enqueue(start, 0);
Dictionary<TDTile, TDTile> cameFrom = new Dictionary<TDTile, TDTile>();
cameFrom.Add(start, null);
Dictionary<TDTile, float> costSoFar = new Dictionary<TDTile, float>();
costSoFar.Add(start, 0);
float priority = 0.0f;
while (frontier.Count > 0)
{
TDTile currentTile = frontier.Dequeue();
if (currentTile.GetTileType() == (int)TILE_TYPE.ENDPOINT)
break;
AlgorithmStep algoStep = new AlgorithmStep(currentTile);
algoSteps.Add(algoStep);
foreach (TDTile nextTile in currentTile.neighbours)
{
if (nextTile == null || nextTile.GetTileType() == (int)TILE_TYPE.WATER || nextTile.GetTileType() == (int)TILE_TYPE.WALL) continue;
// diagonal step check: if neighbour is diagonal but diagonal step not allowed --> we skip
if (IsDiagonalNeighbour(currentTile, nextTile) && !IsDiagonalStepAllowed()) continue;
float newCost = costSoFar[currentTile] + map.GetCostByTileType(nextTile.GetTileType());
if (!costSoFar.ContainsKey(nextTile) || newCost < costSoFar[nextTile])
{
costSoFar[nextTile] = newCost;
priority = newCost + Heuristic(end, nextTile) + ComputeVectorCrossProduct(start, end, nextTile);
frontier.Enqueue(nextTile, priority);
if (cameFrom.ContainsKey(nextTile)) // TODO: check if this is correct approach (without this we get multiple entries for keys)
cameFrom.Remove(nextTile);
cameFrom.Add(nextTile, currentTile);
algoStep.NeighbourTiles.Add(nextTile);
}
}
}
GeneratePath(end, cameFrom);
}
}
|
Python
|
UTF-8
| 793
| 3.046875
| 3
|
[] |
no_license
|
# python3
import sys
def compute_min_refills(distance, tank, stops):
# write your code here
running_tank = tank
refills = 0
car_index = 0
stops.append(distance)
check_diff = 0
diff_list = list()
for index, stop in enumerate(stops):
if index == len(stops) - 1:
break
if (stops[index+1] - stop) > tank:
return -1
for index, stop in enumerate(stops):
dist_left = running_tank - stop
if dist_left < 0:
refills = refills + 1
running_tank = running_tank + tank
return refills
if __name__ == '__main__':
d, m, _, *stops = map(int, sys.stdin.read().split())
# d, m, _, *stops = map(int, input().split())
print(compute_min_refills(d, m, stops))
|
JavaScript
|
UTF-8
| 2,730
| 2.859375
| 3
|
[] |
no_license
|
$(document).ready(function() {
$('#submitButton').prop("disabled", true);
function updateFormEnabled() {
if (verifySelect()) {
$('#submitButton').prop("disabled", false);
} else {
$('#submitButton').prop("disabled", true);
}
}
function verifySelect() {
if ($("#countySel :selected").val() !== '') {
return true;
} else {
return false;
}
}
$("#countySel").on('change', function() {
//alert($("#countySel :selected").val());
updateFormEnabled();
});
// Create the connector object
var myConnector = tableau.makeConnector();
// Define the schema
myConnector.getSchema = function(schemaCallback) {
var cols = [{
id: "CountyName",
alias: "County Name",
dataType: tableau.dataTypeEnum.string
}, {
id: "tested",
alias: "Number Tested",
dataType: tableau.dataTypeEnum.int
}, {
id: "confirmed_cases",
alias: "Total Cases",
dataType: tableau.dataTypeEnum.int
}, {
id: "deaths",
alias: "Deaths",
dataType: tableau.dataTypeEnum.int
}, {
id: "reportDate",
alias: "Date",
dataType: tableau.dataTypeEnum.datetime
}];
var tableSchema = {
id: "countyTemproalCovidFeed",
alias: "Temporal COVID data by County - IL DPH Public Data",
columns: cols
};
schemaCallback([tableSchema]);
};
// Download the data
myConnector.getData = function(table, doneCallback) {
var apiUri = "https://idph.illinois.gov/DPHPublicInformation/api/COVID/GetCountyHistorical?application=json&";
var paramsObj = JSON.parse(tableau.connectionData),
paramsString = "countyName=" + paramsObj.countyName,
apiCall = apiUri + paramsString;
$.getJSON(apiCall, function(resp) {
var vals = resp.values,
tableData = [];
// Iterate over the JSON object
for (var i = 0, len = vals.length; i < len; i++) {
tableData.push({
"CountyName": vals[i].CountyName,
"tested": vals[i].TotalTested,
"confirmed_cases": vals[i].CumulativeCases,
"deaths": vals[i].Deaths,
"reportDate": vals[i].ReportDate
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.connectionName = "County Level COVID Data"; // This will be the data source name in Tableau
tableau.registerConnector(myConnector);
$("#submitButton").click(function() {
// Create event listeners for when the user submits the form
// $(document).ready(function() {
// $("#submitButton").click(function() {
var cntyName = {
countyName: $("#countySel :selected").val()
};
tableau.connectionData = JSON.stringify(cntyName); // Use this variable to pass data to your getSchema and getData functions
tableau.submit(); // This sends the connector object to Tableau
// });
// });
});
});
|
C++
|
UTF-8
| 2,079
| 2.921875
| 3
|
[] |
no_license
|
#include <iostream>
#include <functional>
void run_test();
namespace testSpace{
template <std::size_t... M>
struct _indices{};
template <std::size_t N, std::size_t... M>
struct _indices_builder : _indices_builder<N - 1, N - 1, M...>{};
template <std::size_t... M>
struct _indices_builder<0, M...>{
using type = _indices<M...>;
};
template <typename Ret, typename... ARGS, std::size_t... N>
inline Ret testTraitsTuple(const std::function<Ret(ARGS...)>& func, const std::tuple<ARGS...>& args, _indices<N...>){
return func(std::get<N>(args)...);
}
// template <typename Ret, typename... ARGS>
// inline Ret testTraitsTuple(const std::function<Ret(ARGS...)>& func, const std::tuple<ARGS...>& args){
// return testTraitsTuple(func, args, typename _indices_builder<sizeof...(ARGS)>::type());
// }
template <typename Ret, typename... ARGS, std::size_t... N>
inline Ret testTraitsTuple(Ret(*func)(ARGS ...), const std::tuple<ARGS...>& args, _indices<N...>){
return func(std::get<N>(args)...);
}
// template <typename Ret, typename... ARGS>
// inline Ret testTraitsTuple(Ret(*func)(ARGS ...), const std::tuple<ARGS...>& args){
// return testTraitsTuple(func, args, typename _indices_builder<sizeof...(ARGS)>::type());
// }
template <typename Ret, typename... ARGS>
inline Ret testTraits(Ret(*func)(ARGS ...), ARGS ... args){
return testTraitsTuple(func, std::make_tuple(args ... ), typename _indices_builder<sizeof...(ARGS)>::type());
}
template <typename Ret, typename... ARGS>
inline Ret testTraits(const std::function<Ret(ARGS...)>& func, ARGS ... args){
return testTraitsTuple(func, std::make_tuple(args ...), typename _indices_builder<sizeof...(ARGS)>::type());
}
}
int printTest( int a, int b, int c, bool d){
std::cout << "a:" << a << " b:" << b << " c:" << c << " d:" << (d ? "true" : "false") << std::endl;
return d ? (a + b + c) : (a - b - c);
}
int main(int argc, char* argv[]) {
run_test();
//testSpace::testTraits(&printTest, 1, 2, 3, false);
return 0;
}
|
C#
|
UTF-8
| 3,118
| 2.953125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Vim.BFast
{
/// <summary>
/// Anything that can be add to a BFAST has to be abled to compute its size, and write to a stream.
/// </summary>
public interface IBFastComponent
{
long GetSize();
void Write(Stream stream);
}
/// <summary>
/// A wrapper around a buffer so that it can be used as a BFAST component
/// </summary>
public class BufferAsBFastComponent : IBFastComponent
{
public BufferAsBFastComponent(IBuffer buffer)
=> Buffer = buffer;
public IBuffer Buffer { get; }
public void Write(Stream stream) => stream.Write(Buffer);
public long GetSize() => Buffer.NumBytes();
}
/// <summary>
/// Used to build BFASTs incrementally that contain named buffers and/or other BFASTs.
/// </summary>
public class BFastBuilder : IBFastComponent
{
public BFastHeader Header { get; private set; }
public long GetSize() => GetOrComputeHeader().Preamble.DataEnd;
public List<(string, IBFastComponent)> Children { get; } = new List<(string, IBFastComponent)>();
public void Write(Stream stream)
=> stream.WriteBFast(GetOrComputeHeader(),
BufferNames().ToArray(),
BufferSizes().ToArray(),
OnBuffer);
public void Write(string filePath)
{
using (var stream = File.OpenWrite(filePath))
Write(stream);
}
public long OnBuffer(Stream stream, int index, string name, long size)
{
(string bufferName, IBFastComponent x) = Children[index];
Debug.Assert(name == bufferName);
Debug.Assert(size != GetSize());
Debug.Assert(size == x.GetSize());
x.Write(stream);
return size;
}
private BFastHeader GetOrComputeHeader()
=> Header ?? (Header = BFast.CreateBFastHeader(
BufferSizes().ToArray(), BufferNames().ToArray()));
private BFastBuilder _add(string name, IBFastComponent component)
{
Header = null;
Children.Add((name, component));
return this;
}
public BFastBuilder Add(string name, IBFastComponent component)
=> _add(name, component);
public BFastBuilder Add(string name, IBuffer buffer)
=> _add(name, new BufferAsBFastComponent(buffer));
public BFastBuilder Add(INamedBuffer buffer)
=> Add(buffer.Name, buffer);
public BFastBuilder Add(IEnumerable<INamedBuffer> buffers)
=> buffers.Aggregate(this, (x, y) => x.Add(y));
public BFastBuilder Add(string name, IEnumerable<INamedBuffer> buffers)
=> Add(name, new BFastBuilder().Add(buffers));
public IEnumerable<string> BufferNames()
=> Children.Select(x => x.Item1);
public IEnumerable<long> BufferSizes()
=> Children.Select(x => x.Item2.GetSize());
}
}
|
Markdown
|
UTF-8
| 11,939
| 2.71875
| 3
|
[] |
no_license
|
# Another World 3DO Technical Notes
Another World has been ported on many platforms. The way the game was written (interpreted game logic) clearly helped.
This document focuses on the 3DO release made by Interplay in 1994. This version was not a straight port. In addition to reworking the assets, the game code was modified.
- [Assets](#assets)
- [Game Code](#game-code)
- [Game Copy Protection](#game-copy-protection)
- [Bytecode](#bytecode)
- [Resources](#resources)
- [Rendering](#rendering)
- [Introduction Sequence Synchronization](#introduction-sequence-synchronization)
- [Game Passwords](#game-passwords)
## Assets
Type | Amiga/DOS | 3DO
-------- | --------- | ---
Music | 4 channels tracker with raw signed 8bits samples (3 files) | AIFF SDX2 compressed audio (30 files)
Sound | raw signed 8bits mono (103 files) | AIFF signed 16 bits (92 files)
Bitmap | 4 bits depth paletted 320x200 (8 files) | True-color RGB555 320x200 (139 files)
Bytecode | Big-endian (Motorola 68000) | Little-endian (ARMv3)
## Game Code
The game code is split in 9 different sections.
```
16000.asm - protection screen
16001_intro.asm
16002_eau.asm - water
16003_pri.asm - jail
16004_cite.asm
16005_arene.asm
16006_luxe.asm
16007_final.asm
16008.asm - password screen
```
Each section can be used as a starting point by the engine, with _vars[0] set to start at a specific position within that section.

The password screen bytecode contains series of checks such as below to lookup the code entered.
```
02E3: jmpIf(VAR(0x07) != 10, @0303)
02E9: jmpIf(VAR(0x08) != 2, @0303)
02EF: jmpIf(VAR(0x09) != 9, @0303)
02F5: jmpIf(VAR(0x0A) != 2, @0303)
02FB: VAR(0x00) = 10
02FF: updateResources(res=16002)
```
The 4 variables (var7..varA) hold the index of the letter selected.
```
alphabet = [ 'B', 'C', 'D', 'F', 'G', 'H', '?', '?', 'J', 'K', 'L', 'R', 'T', 'X' ]
```
## Game Copy Protection
With the original Amiga/DOS version, the player has to lookup some symbols from a code wheel provided with the game.

In addition to checking if the symbols entered are the correct ones, the game code is setting a few variables which are checked during gameplay.
This was probably added to defeat game cracks that would simply bypass the game protection screen.
The Amiga version bytecode checks 4 variables :
```
0091: VAR(0xBC) &= 16
0095: VAR(0xC6) &= 128
0099: jmpIf(VAR(0xBC) == 0, @00B3)
009F: jmpIf(VAR(0xC6) == 0, @00B3)
00A5: jmpIf(VAR(0xF2) != 6000, @00B3)
00AC: jmpIf(VAR(0xDC) != 33, @00B3)
```
The DOS version bytecode checks 5 variables :
```
00B7: VAR(0xBC) &= 16
00BB: VAR(0xF8) = VAR(0xC6)
00BE: VAR(0xF8) &= 128
00C2: jmpIf(VAR(0xBC) == 0, @00E9)
00C8: jmpIf(VAR(0xF8) == 0, @00E9)
00CE: VAR(0xF8) = VAR(0xE4)
00D1: VAR(0xF8) &= 60
00D5: jmpIf(VAR(0xF8) != 20, @00E9)
00DB: jmpIf(VAR(0xF2) != 4000, @00E9)
00E2: jmpIf(VAR(0xDC) != 33, @00E9)
```
## Bytecode
The game engine is based on a virtual machine with 30 opcodes.
### Opcodes
The game was developed on an Amiga. As the Motorola 68000 CPU was big endian, this is the byte order found in the bytecode on the original Amiga/DOS versions.
Most of the opcodes operand size is 2 bytes, matching the register size of the target 68000 CPU.
* ALU
Num | Name | Parameters | Description
--- | ---- | ---------- | ---
0 | movConst | var: byte, value: word | var := value
1 | mov | var(dst): byte, var(src): byte | dst := src
2 | add | var(dst): byte, var(src): byte | dst += src
3 | addConst | var: byte; value: word | var += value
19 | sub | var(dst): byte, var(src): byte | var -= src
20 | and | var: byte, value: word | var &= value
21 | or | var: byte, value: word | var |= value
22 | shl | var: byte, count: word | var <<= count
23 | shr | var: byte, count: word | var >>= count
* Control flow
Num | Name | Parameters | Description
--- | ---- | ---------- | ---
4 | call | offset: word | function call
5 | ret | | return from function call
7 | jmp | offset: word | pc = offset
9 | jmpIfVar | var: byte, offset: word | --var != 0: pc = offset (dbra)
10 | condJmp | operator: byte, var(operand1): byte, operand2: byte/word, offset: word | cmp op1, op2: pc = offset
* Coroutines
Num | Name | Parameters | Description
--- | ---- | ---------- | ---
8 | installTask | num: byte, offset: word | setup a coroutine, pc = offset
6 | yieldTask | | pause current coroutine
12 | changeTasksState | num1: byte, num2: byte, state:byte | change coroutines num1..num2 state
17 | removeTask | | abort current coroutine
* Display
Num | Name | Parameters | Description
--- | ---- | ---------- | ---
11 | setPalette | num: word | set palette (16 colors)
13 | selectPage | num: byte | set current drawing page
14 | fillPage | num: byte, color: byte | fill page with color
15 | copyPage | num(dst): byte, num(src): byte | copy page content
16 | updateDisplay | num: byte | present page to screen
18 | drawString | num: word, x(/8): byte, y(/8): byte, color: byte | draw string
* Assets
Num | Name | Parameters | Description
--- | ---- | ---------- | ---
24 | playSound | num: word, frequency: byte, volume: byte, channel: byte | play sound
25 | updateResources | num: word | load asset resource or section
26 | playMusic | num: word, pitch: word, position: byte | play music
### 3DO Specific Opcodes
The 3DO port does not use the same bytecode. The game code was modified, recompiled and saved under the target endianness of the target ARM CPU of the 3DO.
In the process, some opcodes have been added and some others have been optimized for size by using one byte operand when applicable.
The new shift opcode is a good example : the original bytecode was using a 16bits value to specify the number of bits to shift on the target 16 bits register.
8 bits were twice as enough.
Num | Name | Parameters | Description
--- | ---- | -----------| ---
11 | setPalette | num: byte |
22 | shiftLeft | var: byte, count: byte | var <<= count
23 | shiftRight | var: byte, count: byte | var >>= count
26 | playMusic | num: byte |
27 | drawString | num: byte, var(x): byte, var(y): byte, color: byte |
28 | jmpIfVarFalse | var: byte, offset: word | if var == 0: pc = offset
29 | jmpIfVarTrue | var: byte, offset: word | if var != 0: pc = offset
30 | printTime | | output running time (via SWI 0x1000E), not referenced in game code
## Resources
As any 3DO game, the data-files are read from an OperaFS CD-ROM.
Inside the GameData/ directory
* The game data-files are numbered from 1 to 340 (File%d)
* The song files (AIFF-C) are numbered from 1 to 30 (song%d)
* Three cinematics files : Logo.Cine, Spintitle.Cine, ootw2.cine
The files are stored uncompressed at the exception of the background bitmaps.
The decompression code can be found in the DOOM 3DO source code - [dlzss.s](https://github.com/Olde-Skuul/doom3do/blob/master/lib/burger/dlzss.s)
## Rendering
### Transparency
The engine can display semi-transparent shapes such as the car lights in the introduction.
 
The original Amiga/DOS game used a palette of 16 colors. The semi-transparency is achieved by allocating the upper half of the palette to the transparent colors.
The palette indexes 0 to 7 hold the scene colors, indexes 8 to 15 the blended colors.

Turning a pixel semi-transparent is simply done by setting to 1 the bit 3 of the palette color index (|= 8).
This is not directly applicable to the 3DO which renders everything with true-color buffers.
The 3DO engine leverages the console capabilities to render an alpha blended shape. Interestingly, the color of the lights is not yellow in that version.
 
### Background Bitmaps
While the original Amiga/DOS game relied on polygons for most of its graphics, the game engine supports using a raster bitmap to be used as the background.
In the original game version, this is only used for 8 different screens.
   
   
The 3DO version uses the feature for all the screens of the game. For comparison, the same screens in RGB555.
   
   
### Drawing Primitives
The original Amiga/DOS used only one primitive for all its drawing : a quad (4 vertices).
The 3DO reworked that format, probably to optimize shapes made of single pixels or straight lines.
The upper nibble of the shape color byte specifies the primitive to draw.
```
0x00 : nested/composite shape
0x20 : rectangle
0x40 : pixel
0xC0 : polygon/quad
```
## Introduction Sequence Synchronization
On Amiga/DOS, the introduction is synchronized to the music.
The music module contains 2 bytes patterns, that are copied to the variable 0xF4.
```
if (pat.note_1 == -3) {
_vars[0xF4] = pat.note_2;
}
```
The condition can be found in the original 68000 SoundFX player [routine](https://github.com/cyxx/rawgl/blob/master/docs/fxplayer.s#L555).
The bytecode contains checks on this variable to wait and continue.
```
000B: (00) VAR(0xF4) = 0
0F66: (0A) jmpIf(VAR(0xF4) == 43, @0F91)
...
1399: (0A) jmpIf(VAR(0xF4) == 46, @13AA)
13AE: (0A) jmpIf(VAR(0xF4) == 47, @13BF)
13C3: (0A) jmpIf(VAR(0xF4) == 48, @13D4)
13F6: (0A) jmpIf(VAR(0xF4) != 49, @1406)
```
On the 3DO, the tracker based music has been replaced with digital tracks.
The synchronization had to be modified.
That version relies on the variable 0xF7. It holds the total number of VBLs since the game started.
```
nbtrame = readTick() - OldVBL;
if (_vars[0xFF] != 0) {
while (_vars[0xFF] > nbtrame) {
nbtrame = readTick() - OldVBL;
}
}
_vars[0xF7] += nbtrame;
OldVBL += nbtrame;
```
The introduction bytecode has the checks against this variable for the timing.
```
0068: jmpIf(VAR(0xF7) < 3450, @0067)
043E: jmpIf(VAR(0xF7) < 7484, @043D)
046A: jmpIf(VAR(0xF7) < 8602, @0469)
jmpIf(VAR(0xF7) < 9212, @0576)
...
jmpIf(VAR(0xF7) < 400, @1C40)
```
## Game Passwords
Game passwords extracted from the 16008 part bytecode.
Code | Part | Checkpoint | Notes
---- | ----- | ---------- | -----
LDKD | 16002 | 10 |
HTDC | 16003 | 20 |
CLLD | 16004 | 30 |
FXLC | 16004 | 35 |
KRFK | 16004 | 37 |
XDDJ | 16004 | 33 |
LBKG | 16004 | 31 |
KLFB | 16004 | 39 |
TTCT | 16004 | 41 |
DDRX | 16004 | 42 |
TBHK | 16004 | 43 |
BRTD | 16004 | 49 |
CKJL | 16005 | 50 |
LFCK | 16006 | 60 |
BFLX | 16004 | 44 |
XJRT | 16004 | 45 |
HRTB | 16004 | 46 |
HBHK | 16004 | 47 |
JCGB | 16004 | 48 |
HHFL | 16006 | 62 |
TFBB | 16006 | 64 |
TXHF | 16006 | 66 |
KRTD | 16007 | 70 |
BRGR | 16010 | -1 | Stalactites
|
Java
|
UTF-8
| 172
| 1.671875
| 2
|
[] |
no_license
|
package ru.podelochki.otus.socketchat.services;
public interface ClientMessageService extends MessageService {
void addReceiver(ServiceMessageHandler receiver);
}
|
Shell
|
UTF-8
| 781
| 2.8125
| 3
|
[] |
no_license
|
BASEDIR=$(cd "$(dirname "$1")"; pwd)/$(basename "$1")
KUBERNETES=/usr/local/share/kubernetes2/kubernetes-1.0.1
KUBECTL=./cluster/kubectl.sh
cd $KUBERNETES
#stop services
$KUBECTL stop -f ${BASEDIR}kube-yml/local/redis-service.yml
$KUBECTL stop -f ${BASEDIR}kube-yml/local/main-service.yml
$KUBECTL stop -f ${BASEDIR}kube-yml/local/conference-service.yml
$KUBECTL stop -f ${BASEDIR}kube-yml/local/advertising-service.yml
#create proxy
#$KUBECTL stop -f ${BASEDIR}kube-yml/local/proxy-port-local.yml
#stop pods
$KUBECTL stop -f ${BASEDIR}kube-yml/local/redis-controller.yml
$KUBECTL stop -f ${BASEDIR}kube-yml/local/main-controller.yml
$KUBECTL stop -f ${BASEDIR}kube-yml/local/conference-controller.yml
$KUBECTL stop -f ${BASEDIR}kube-yml/local/advertising-pod.yml
cd $BASEDIR
|
Java
|
UTF-8
| 381
| 3.09375
| 3
|
[] |
no_license
|
package com.ejemplo.figuras;
public class Cubo extends Figura {
private double lado;
public double getLado() {
return lado;
}
public void setLado(double lado) {
this.lado = lado;
}
@Override
public void draw() {
System.out.println(getEtiqueta() + " con area " + volumen());
}
public double volumen(){
return lado * lado * lado;
}
}
|
PHP
|
UTF-8
| 4,941
| 3.078125
| 3
|
[] |
no_license
|
<?php
/**
* Контроллер AdminUserController
* Управление в админпанели
*/
class AdminUserController extends AdminBase
{
/**
* Action для страницы "Управление..."
*/
public function actionIndex()
{
// Проверка доступа
self::checkAdmin('superadmin');
// Получаем список
$usersList = User::getUsersListAdmin();
// Подключаем вид
require_once(ROOT . '/views/admin_user/index.php');
return true;
}
/**
* Action для страницы "Добавить ..."
*/
public function actionCreate()
{
// Проверка доступа
self::checkAdmin('superadmin');
$usersList = User::getUsersListAdmin();
// Обработка формы
if (isset($_POST['submit'])) {
// Если форма отправлена
// Получаем данные из формы
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$role = $_POST['role'];
// Флаг ошибок в форме
$errors = false;
if (!User::checkName($name)) {
$errors[] = 'Имя не должно быть короче 2-х символов';
}
if (!User::checkEmail($email)) {
$errors[] = 'Неправильный E-mail';
}
if (!User::checkPassword($password)) {
$errors[] = 'Пароль не должен быть короче 6-ти символов';
}
if (User::checkEmailExists($email)) {
$errors[] = 'Такой email уже используется';
}
if ($errors == false) {
$result = User::createUser($name, $email, $password,$role);
}
// Перенаправляем пользователя на страницу управления
header("Location: /admin/user");
}
require_once(ROOT . '/views/admin_user/create.php');
return true;
}
/**
* Action для страницы "Редактировать...@
*/
public function actionUpdate($id)
{
// Проверка доступа
self::checkAdmin('superadmin');
// Получаем данные о конкретной категории
$tableName = "user";
$user = Db::getRowById($id, $tableName);
// Обработка формы
if (isset($_POST['submit'])) {
// Если форма отправлена
// Получаем данные из формы
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$role = $_POST['role'];
// Флаг ошибок в форме
$errors = false;
if (!User::checkName($name)) {
$errors[] = 'Имя не должно быть короче 2-х символов';
}
if (!User::checkEmail($email)) {
$errors[] = 'Неправильный E-mail';
}
if (!User::checkPassword($password)) {
$errors[] = 'Пароль не должен быть короче 6-ти символов';
}
if (User::checkEmailExists($email)) {
$errors[] = 'Такой email уже используется';
}
if ($errors == false) {
$result = User::updateUser($id,$name,$email,$password,$role);
}
// Перенаправляем пользователя на страницу управления
header("Location: /admin/user");
}
// Подключаем вид
require_once(ROOT . '/views/admin_user/update.php');
return true;
}
/**
* Action для страницы "Удалить..."
*/
public function actionDelete($id)
{
// Проверка доступа
self::checkAdmin('superadmin');
// Обработка формы
if (isset($_POST['submit'])) {
// Если форма отправлена
// Удаляем оплату
$tableName = "user";
Db::deleteRowById($tableName,$id);
// Перенаправляем пользователя на страницу управления
header("Location: /admin/user");
}
// Подключаем вид
require_once(ROOT . '/views/admin_user/delete.php');
return true;
}
}
|
Python
|
UTF-8
| 4,991
| 2.84375
| 3
|
[] |
no_license
|
"""
This file contains test functions for channel_join function
in channel.py.
"""
import pytest
from data import data
from src.other import clear_v1
from src.error import InputError, AccessError
from src.channel import channel_join_v2
from src.auth import auth_register_v2
from src.channels import channels_create_v2, channels_list_v2
from src.helper import generate_token
def test_channel_join():
"""
This function checks if the user is successfully
added to the channel and store in the data structure.
"""
# Clear the data structure
clear_v1()
# Call other functions to create the data and store in data structure
auth_dict1 = auth_register_v2("johnsmith@gmail.com", "123456", "john", "smith")
auth_dict2 = auth_register_v2("harrypotter@gmail.com", "555555", "harry", "potter")
auth_token1 = auth_dict1["token"]
auth_token2 = auth_dict2["token"]
channel_id1 = channels_create_v2(auth_token1, "Chill Soc", True)
channel_join_v2(auth_token2, channel_id1["channel_id"])
# Black box testing version in waiting
# Check if the user is successfully added to the channel data frame
assert channels_list_v2(auth_token2) == {
'channels': [
{
'channel_id': 1, # channel id start at 1 or 0 is worth checking ? It's currently start at 1.
'name': 'Chill Soc',
}
],
}
def test_channel_join_except_channel():
"""
This function tests if channel ID is
a valid channel.
"""
# Clear the data structure
clear_v1()
# Call other functions to create the data and store in data structure
auth_dict1 = auth_register_v2("johnsmith@gmail.com", "123456", "john", "smith")
auth_dict2 = auth_register_v2("harrypotter@gmail.com", "555555", "harry", "potter")
auth_token1 = auth_dict1["token"]
auth_token2 = auth_dict2["token"]
channels_create_v2(auth_token1, "Chill Soc", True)
invalid_channel = 50
with pytest.raises(InputError):
channel_join_v2(auth_token2, invalid_channel)
def test_channel_join_except_invalid_auth():
"""
This function tests if token is valid
"""
# Clear the data structure
clear_v1()
# Call other functions to create the data and store in data structure
auth_dict1 = auth_register_v2("johnsmith@gmail.com", "123456", "john", "smith")
auth_register_v2("harrypotter@gmail.com", "555555", "harry", "potter")
auth_token1 = auth_dict1["token"]
channel_id1 = channels_create_v2(auth_token1, "Chill Soc", True)
# Create invalid token for the test
invalid_user = 999
invalid_token = generate_token(invalid_user)
with pytest.raises(AccessError):
channel_join_v2(invalid_token, channel_id1["channel_id"])
def test_channel_join_except_private():
"""
This function tests if the channel status
is private and user is not global owner.
"""
# Clear the data structure
clear_v1()
# Call other functions to create the data and store in data structure
auth_dict1 = auth_register_v2("johnsmith@gmail.com", "123456", "john", "smith")
auth_dict2 = auth_register_v2("harrypotter@gmail.com", "555555", "harry", "potter")
auth_token1 = auth_dict1["token"]
auth_token2 = auth_dict2["token"]
channel_id1 = channels_create_v2(auth_token1, "Chill Soc", False)
with pytest.raises(AccessError):
channel_join_v2(auth_token2, channel_id1["channel_id"])
def test_channel_join_private_global():
"""
This function tests if the channel status
is private and user is global DREAM owner.
"""
# Clear the data structure
clear_v1()
# Call other functions to create the data and store in data structure
auth_dict1 = auth_register_v2("johnsmith@gmail.com", "123456", "john", "smith")
auth_dict2 = auth_register_v2("harrypotter@gmail.com", "555555", "harry", "potter")
auth_token1 = auth_dict1["token"]
auth_token2 = auth_dict2["token"]
channel_id1 = channels_create_v2(auth_token2, "Chill Soc", False)
# Global DREAM owner attempt to join a private channel
channel_join_v2(auth_token1, channel_id1["channel_id"])
# Check if the global owner successfully join private channel
assert channels_list_v2(auth_token1) == {
'channels': [
{
'channel_id': 1, # channel id start at 1 or 0 is worth checking ? It's currently start at 1.
'name': 'Chill Soc',
}
],
}
def test_channel_join_except_repetitive():
"""
This function tests if the user is already
a member in that channel.
"""
# Clear the data structure
clear_v1()
# Call other functions to create the data and store in data structure
auth_register_v2("johnsmith@gmail.com", "123456", "john", "smith")
auth_dict2 = auth_register_v2("harrypotter@gmail.com", "555555", "harry", "potter")
auth_token2 = auth_dict2["token"]
channel_id1 = channels_create_v2(auth_token2, "Chill Soc", True)
with pytest.raises(AccessError):
channel_join_v2(auth_token2, channel_id1["channel_id"])
|
C++
|
UTF-8
| 348
| 2.5625
| 3
|
[] |
no_license
|
#include "eventoTransmissao.h"
eventoTransmissao::eventoTransmissao(double t, const pessoa* p) : evento(evento::TRANSMISSAO, t), p(p), src(p->id()) {}
pessoa eventoTransmissao::origem() const
{
return *p;
}
const pessoa *eventoTransmissao::ptr() const
{
return p;
}
const unsigned int eventoTransmissao::id() const
{
return src;
}
|
Markdown
|
UTF-8
| 329
| 2.734375
| 3
|
[
"CC-BY-4.0"
] |
permissive
|
# 整式加减
2008-12-01
已知a2(a的平方)+ab=4,ab+b2(b的平方)=-1。求①a2(a的平方)-b2(b的平方)的值②a2(a的平方)+3ab+2b2(2*b的平方)的值
①a方-b方=(a方+ab)-(b方-ab)=4-(-1)=5②a方+3ab+2b方=(a方+ab)+(2ab+2b方)=4+2(ab+b方)=4+2*(-1)=4-2=2
|
C++
|
UTF-8
| 1,176
| 3.671875
| 4
|
[] |
no_license
|
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
using namespace std;
class Solution {
public:
int len ;
vector<string> ans;
vector<string> generateParenthesis(int n) {
len = n;
dfs(0 , 0 , "");
return ans;
}
void dfs(int left , int right , string s){
if(left < right || s.size() > len*2) return ; //保证左括号要大于右括号
if(left == len && right == len && s.size() == len*2){ //满足条件
ans.push_back(s);
return ;
}
dfs(left + 1 , right , s+"("); // 放左括号
dfs(left , right+1, s+")"); //放右括号
}
};
int main()
{
Solution solution;
auto t = solution.generateParenthesis(3);
for(auto tt : t) cout << tt << " ";
return 0;
}
/*
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
1 <= n <= 8
*/
|
C++
|
UTF-8
| 2,816
| 3.234375
| 3
|
[] |
no_license
|
#include "account_manager.h"
AccountManager::AccountManager(const char *filename){
account_filename = std::string(filename);
if(!load(filename))
std::cerr << "AccountManager(): load initial data error." << std::endl;
}
AccountManager::AccountManager(){
}
AccountManager::~AccountManager(){
}
bool
AccountManager::isExist(const char *id){
return isExist(std::string(id));
}
bool
AccountManager::isExist(std::string id){
return (account_table.find(id) != account_table.end());
}
bool
AccountManager::isCorrect(std::string id, std::string pwd){
if(isExist(id))
if(account_table.find(id)->second == pwd)
return true;
return false;
}
void
AccountManager::insert(const char *id, const char *pwd){
insert(std::string(id), std::string(pwd));
}
void
AccountManager::insert(std::string id, std::string pwd){
if(!isExist(id)){
account_table.insert(AccountRecord(id, pwd));
update(id, pwd);
}
else
throw ERR_DUPID;
}
void
AccountManager::remove(const char *id){
AccountTable::iterator it;
if((it = account_table.find(std::string(id))) != account_table.end()){
account_table.erase(it);
update();
}
else
throw ERR_NULL;
}
void
AccountManager::update(){
if(!store(account_filename.c_str()))
throw ERR_IO;
}
void
AccountManager::update(const char *id, const char *pwd){
if(!store(account_filename.c_str(), id, pwd))
throw ERR_IO;
}
void
AccountManager::update(std::string id, std::string pwd){
update(id.c_str(), pwd.c_str());
}
bool
AccountManager::load(const char *filename){
std::ifstream ifs;
ifs.open(filename, std::ios::in);
if(!ifs.good()) return false;
std::string id, pwd;
while(ifs >> id >> pwd){
account_table.insert(AccountRecord(id, pwd));
}
ifs.close();
return true;
}
bool
AccountManager::store(const char *filename){
std::ofstream ofs;
ofs.exceptions (std::ifstream::failbit | std::ifstream::badbit );
try {
ofs.open(filename, std::ios::out | std::ios::trunc);
for(AccountTable::iterator it = account_table.begin(); it != account_table.end(); it++){
ofs << it->first << " " << it->second << std::endl;
}
return true;
}
catch (std::ifstream::failure e) {
std::cerr << "account_manager.load(): Load account data error" << std::endl;
ofs.close();
return false;
}
}
bool
AccountManager::store(const char *filename, const char *id, const char *pwd){
std::ofstream ofs;
ofs.exceptions (std::ifstream::failbit | std::ifstream::badbit );
try {
ofs.open(filename, std::ios::out | std::ios::app);
ofs << id << " " << pwd << std::endl;
ofs.close();
return true;
}
catch (std::ifstream::failure e) {
std::cerr << "account_manager.loac(): Load account data error" << std::endl;
ofs.close();
return false;
}
}
|
Markdown
|
UTF-8
| 3,322
| 2.53125
| 3
|
[] |
no_license
|
---
title: modules
tag: modules
birth: 2017-03-28
modified: 2017-03-28
---
# modules
**前言:详解 node 的模块加载机制**
---
## API
详解模块暴露的 API
* **require(id)** 加载一个模块,详见 [模块机制](#模块机制)
* **require.cache** 缓存对象,键为文件的全局路径,值为解析后的地址
* **require.extensions** 不同扩展的处理函数
* **require.main** 模块的入口脚本
* **require.resolve(request,options)** 模块的入口脚本
<!-- TODO: 验证 options paths 属性无效需查明原因 -->
* **require.resolve.paths** 用于解析模块加载的文件路径
* **module** 模块实例对象,作用域为每个模块文件
* **module.children** 该模块引入的子模块对象
* **module.exports** 模块导出的对象
* **module.filename** 解析的模块文件名
* **module.id** 模块 id
> 实际上可以利用模块 id 和 filename 不相等来判断启动文件,因为启动文件默认 id 为 `.`
* **module.loaded** 模块是否加载的标志
* **module.parent** 引用该模块的父模块
* **module.paths** 索引该模块的路径集合
* **module.require** module 的原型方法
* **Module** 模块构造器,可以利用 `require('module')` 或 `module.constructor` 的方式引入
* 利用 `require('module').builtinModules` 查看内置模块
* **module.createRequire(filename)** 创建模块请求
<!-- TODO: 需找出适用场景 -->
## 模块机制
### 模块查找
加载机制详见 [模块加载机制](https://nodejs.org/api/modules.html#modules_addenda_the_mjs_extension)
重点如下:
* node 会先加载不带任何后缀的文件作为 js 文件解析,随后按照 `js,json,node` 的后缀加载文件
* js 采用 compileFunction 编译
* json 采用 json.parse 解析
* node 作为二进制扩展解析调用 `process.dlopen()`,参看示例 [](./module-order) 验证模块记载机制,模块名区分大小写
* 若文件无法查找到,按照同名文件夹会读取 `package.json` **main** 字段,不存在会查找 `index` 文件按照 `js,json,node` 扩展顺序进行加载
> 注意此处不会加载没有扩展名文件,若文件夹下 index 无扩展名会直接抛出错误
* 对于不包含路径的模块,会先去加载内部模块若失败,会按照`module.paths` 的一系列目录按照
对于循环加载,当检测到模块已加载后会返回加载一半的模块参看示例 [循环加载](./cycle-load)
此外可以通过 `NODE_PATH` 来增加解析路径。利用 `:` 分隔多个目录。windows 为 `;`
除此之外 node 会加载如下路径:
* `$HOME/.node_modules`
* `$HOME/.node_libraries`
* `$PREFIX/lib/node` 该变量由 `node_prefix` 配置
> 参看此示例 <https://github.com/nodejs/node/issues/18024>
<!-- TODO: 此处需验证是否合理 -->
### 模块缓存
每个模块会生成一个 `module` 对象,依赖模块会在 `module.cache` 中持有对该模块的引用
当多次引用同一模块时会优先去 `module.cache` 加载。若清除该缓存,重新加载模块会触发模块热重载。
参考范例 [缓存](./module-cache) 该示例说明 index.js 会重载 a.js 但是模块 b 不会。
### 模块封装
> node 中不加任何前缀的变量会附着在全局环境
nodejs 利用闭包实现模块化!!!
|
Python
|
UTF-8
| 1,636
| 2.8125
| 3
|
[
"Apache-2.0",
"Swift-exception"
] |
permissive
|
#!/usr/bin/env python3
import re
import subprocess
import sys
def run():
if len(sys.argv) > 1:
print("""
ns-html2rst - Convert Cocoa HTML documentation into ReST
usage: nshtml2rst < NSString.html > NSString.rst
""")
sys.exit(0)
html = sys.stdin.read()
# Treat <div class="declaration>...</div> as <pre>...</pre>
html = re.sub(
r'<div\s+class="declaration">(.*?)</div>',
r'<pre>\1</pre>',
html, flags=re.MULTILINE | re.DOTALL)
# Strip all attributes from <pre>...</pre> containing class="..."
# The resulting classes confound ReST
html = re.sub(
r'<pre\s[^>]*class=[^>]*>(.*?)</pre>',
r'<pre>\1</pre>',
html, flags=re.MULTILINE | re.DOTALL)
# Remove links from <code>...</code>, which doesn't have a rendering in
# ReST
html = re.sub(
r'<code>(.*?)<a[^>]*?>(.*?)</a>(.*?)</code>',
r'<code>\1\2\3</code>',
html, flags=re.MULTILINE | re.DOTALL)
# Let pandoc do most of the hard work
p = subprocess.Popen(
args=['pandoc', '--reference-links', '-f', 'html', '-t', 'rst'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
rst, stderr = p.communicate(html)
# HACKETY HACK HACK: Our html documents apparently contain some
# bogus heading level nesting. Just fix up the one we know about
# so that ReST doesn't complain later.
rst = re.sub("(^|\n)('+)($|\n)",
lambda m: m.group(1) + len(m.group(2)) * '^' + m.group(3),
rst, flags=re.MULTILINE)
sys.stdout.write(rst)
if __name__ == '__main__':
run()
|
JavaScript
|
UTF-8
| 799
| 2.546875
| 3
|
[] |
no_license
|
import React from "react";
import styled from "styled-components";
const TitleH1 = styled.h1`
font-size: 32px;
text-align: center;
color: #641c1c;
`;
const Button = styled.button`
background: ${(props) => (props.active ? "#641c1c" : "#cccccc")};
color: ${(props) => (props.active ? "#ffffff" : "#000000")};
padding: 10px 30px;
cursor: pointer;
transition: 0.6s;
border: none;
border-radius: 5px;
display: block;
margin: 5px auto;
&:hover {
background-color: rgba(0, 0, 0, 0.5);
transition: 0.6s;
}
`;
export default class StyledTest extends React.Component {
render() {
return (
<div>
<TitleH1>Hello styled, i am Sasha Dvryadkin!!!!</TitleH1>
<Button>Not Active</Button>
<Button active>I am Active</Button>
</div>
);
}
}
|
Java
|
UTF-8
| 2,491
| 2.140625
| 2
|
[] |
no_license
|
package cn.showclear.www.pojo.base;
/**
* @author Wang Junbo
* @description 订单查询类
* @date 2019/4/16
*/
public class SearchOrderQo {
private OrderDo orderDo;
private String prodName;
private Double prodPrice;
private Integer prodQuantity;
private String typeName;
private String buyUserName;
private String saleUserName;
private String saleWayCode;
private String saleWayName;
public OrderDo getOrderDo() {
return orderDo;
}
public void setOrderDo(OrderDo orderDo) {
this.orderDo = orderDo;
}
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
this.prodName = prodName;
}
public Double getProdPrice() {
return prodPrice;
}
public void setProdPrice(Double prodPrice) {
this.prodPrice = prodPrice;
}
public Integer getProdQuantity() {
return prodQuantity;
}
public void setProdQuantity(Integer prodQuantity) {
this.prodQuantity = prodQuantity;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public String getBuyUserName() {
return buyUserName;
}
public void setBuyUserName(String buyUserName) {
this.buyUserName = buyUserName;
}
public String getSaleUserName() {
return saleUserName;
}
public void setSaleUserName(String saleUserName) {
this.saleUserName = saleUserName;
}
public String getSaleWayCode() {
return saleWayCode;
}
public void setSaleWayCode(String saleWayCode) {
this.saleWayCode = saleWayCode;
}
public String getSaleWayName() {
return saleWayName;
}
public void setSaleWayName(String saleWayName) {
this.saleWayName = saleWayName;
}
@Override
public String toString() {
return "SearchOrderQo{" +
"orderDo=" + orderDo +
", prodName='" + prodName + '\'' +
", prodPrice=" + prodPrice +
", prodQuantity=" + prodQuantity +
", typeName='" + typeName + '\'' +
", buyUserName='" + buyUserName + '\'' +
", saleUserName='" + saleUserName + '\'' +
", saleWayCode='" + saleWayCode + '\'' +
", saleWayName='" + saleWayName + '\'' +
'}';
}
}
|
Python
|
UTF-8
| 934
| 2.8125
| 3
|
[] |
no_license
|
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('filtering_target_seqs_PB_Ca.csv')
x = data['target sequences cutoff']
genes = data['genes']
auc = data['auc']
target = data['Target / bp FI']
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_xlabel('Number of target sequences in ORF used as cutoff')
ax1.set_ylabel('AUC', color=color)
ax1.scatter(x, auc, color=color)
for i, txt in enumerate(genes):
ax1.annotate(txt, (x[i], auc[i]))
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = 'tab:blue'
ax2.set_ylabel('Targets / bp Feature Importance', color=color) # we already handled the x-label with ax1
ax2.scatter(x, target, color=color)
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout()
plt.savefig('Ca PB AUC with different targets cutoffs.png') # otherwise the right y-label is slightly clipped
plt.show()
|
Python
|
UTF-8
| 458
| 3.515625
| 4
|
[] |
no_license
|
guess = int(input("\nyou have eight tries. \n\nguess a number 1-25?"))
num = 14
count = 1
while guess != num and count < 8:
if guess > num:
print("\ntoo high, guess again!")
guess = int(input("\nwhat's the number?"))
elif guess < num:
print("\ntoo low, guess again!")
guess = int(input("\nwhat's the number?"))
count = count + 1
if guess == num:
print("\nyou got it!\n")
if count == 8:
print("you lose!")
|
TypeScript
|
UTF-8
| 888
| 3.046875
| 3
|
[] |
no_license
|
export abstract class Produto{
private codigo : string;
private nome : string;
private genero : string;
private preco : number;
public constructor(codigo : string, nome : string, genero : string, preco : number){
this.codigo = codigo;
this.nome = nome;
this.genero = genero;
this.preco = preco;
}
public getCogido() : string{
return this.codigo;
}
public setCodigo(codigo : string) : void{
this.codigo = codigo;
}
public getNome() : string{
return this.nome;
}
public setNome(nome : string) : void{
this.nome = nome;
}
public getGenero() : string{
return this.genero;
}
public setGenero(genero : string) : void{
this.genero = genero;
}
public getPreco() : number{
return this.preco;
}
public setPreco(preco : number) : void{
this.preco = preco;
}
public abstract executar() : void;
}
|
Java
|
UTF-8
| 2,273
| 2.265625
| 2
|
[
"MIT"
] |
permissive
|
package com.xiongxh.baking_app.data.bean;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.ForeignKey;
import android.arch.persistence.room.PrimaryKey;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.xiongxh.baking_app.data.local.RecipesDbContract;
import org.parceler.Parcel;
@Entity(tableName = RecipesDbContract.STEPS_TABLE_NAME,
foreignKeys = @ForeignKey(entity = Recipe.class,
parentColumns = "id",
childColumns = "recipeId",
onDelete = ForeignKey.CASCADE))
@Parcel(Parcel.Serialization.BEAN)
public class Step {
private int recipeId;
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private int _id;
@SerializedName("id")
@Expose
private Integer idx;
@SerializedName("description")
@Expose
private String description;
@SerializedName("shortDescription")
@Expose
private String shortDescription;
@SerializedName("videoURL")
@Expose
private String videoURL;
@SerializedName("thumbnailURL")
@Expose
private String thumbnailURL;
public int getId(){
return _id;
}
public void setId(int id) { this._id = id; }
public int getRecipeId() { return recipeId; }
public void setRecipeId(int recipeId) { this.recipeId = recipeId; }
public Integer getIdx(){
return idx;
}
public void setIdx (Integer idx){
this.idx = idx;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public String getShortDescription(){
return shortDescription;
}
public void setShortDescription(String shortdescription){
this.shortDescription = shortdescription;
}
public String getVideoURL(){
return videoURL;
}
public void setVideoURL(String videoURL){
this.videoURL = videoURL;
}
public String getThumbnailURL(){
return thumbnailURL;
}
public void setThumbnailURL(String thumbnailURL){
this.thumbnailURL = thumbnailURL;
}
}
|
JavaScript
|
UTF-8
| 2,251
| 2.953125
| 3
|
[] |
no_license
|
//**************************************************
//*DONT USE, DOESN'T WORK, USE WeatherCardb instead*
//**************************************************
import React, { useState } from 'react';
import axios from 'axios';
import { useAsync } from 'react-async';
var zoneId = '';
const loadWeather = async () =>{
const res = await axios
.get(zoneId)
if (!(res.status >= 200 && res.status < 300)) throw new Error(res.statusText);
return res.data;
}
const WeatherCard = props =>{
const [fIndex, setFIndex] = useState({
index:0
})
zoneId = `https://api.weather.gov/zones/public/${props.parentData[0]}/forecast`;
const {data,error, isLoading} = useAsync({promiseFn: loadWeather});
data===undefined?console.log('loading data...'):console.log(`zoneid: ${zoneId}\nparentData:${props.parentData}\ndata:`)
data===undefined?console.log(`...`):console.log(data.properties.periods)
if(isLoading) return(
<div>
<p>Loading weather card...</p>
</div>
)
if(error){
//console.log(error)
return(
<div>
<p>Error loading card...</p>
<p>{error.message}</p>
</div>
)
}
let forecast = data.properties.periods;
const updateFIndex = (e) =>{
let updateNumber = fIndex.index;
if (e.target.id==="1"){
if (updateNumber===0)
updateNumber = forecast.length-1
else
updateNumber--
}
if (e.target.id==="2"){
if (updateNumber===forecast.length-1)
updateNumber = 0
else
updateNumber++
}
setFIndex({index:updateNumber});
}
//console.log(forecast)
return(
<div id={"Card"+props.index}>
<div>
<h2>{props.parentData[1] + ', ' + props.parentData[2]}</h2>
<h4>{forecast[fIndex.index].name}</h4>
<p>{forecast[fIndex.index].detailedForecast}</p>
<button id="1" onClick={updateFIndex}>Previous</button>
<button id="2" onClick={updateFIndex}>Next</button>
</div>
</div>
)
}
export default WeatherCard;
|
C++
|
UTF-8
| 1,147
| 3.40625
| 3
|
[] |
no_license
|
#include <bitset>
class HashClass{
public:
HashClass(int c, int s) : cap(c), seed(s) {}
int hashFunc(string &value) {
int ret = 0;
for (int i = 0; i < value.size(); ++i) {
ret += seed * ret + value[i];
ret %= cap;
}
return ret;
}
private:
int cap, seed;
};
class StandardBloomFilter {
public:
/*
* @param k: An integer
*/
StandardBloomFilter(int k) {
this->k = k;
for (int i = 0; i < k; ++i) {
hashVec.push_back(new HashClass(100000 + i, 2 * i + 3));
}
}
/*
* @param word: A string
* @return: nothing
*/
void add(string &word) {
for (int i = 0; i < k; ++i) {
bits.set(hashVec[i]->hashFunc(word));
}
}
/*
* @param word: A string
* @return: True if contains word
*/
bool contains(string &word) {
for (int i = 0; i < k; ++i) {
if (!bits[hashVec[i]->hashFunc(word)])
return false;
}
return true;
}
private:
int k;
vector<HashClass *> hashVec;
bitset<200000> bits;
};
|
Shell
|
UTF-8
| 223
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/bash
source ./selfdrive/golden/guess_op_ip.sh
echo $OP_IP
PORT=8022
RSA_FILE=~/.ssh/op.rsa
TARGET=$1
if [ "$2" ]; then
TARGET=$2
fi
set -x
scp -r -P $PORT -i $RSA_FILE $1 root@$OP_IP:/data/openpilot/$TARGET
|
Java
|
UTF-8
| 2,761
| 2.34375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package jp.yokomark.remoteview.reader.utils;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.RemoteViews;
import java.lang.reflect.Field;
/**
* @author KeishinYokomaku
*/
public final class ClassUtils {
public static final String TAG = ClassUtils.class.getSimpleName();
private ClassUtils() {
throw new AssertionError();
}
public static Class getRemoteViewsClass(Class<? extends RemoteViews> clazz) {
if (clazz.equals(RemoteViews.class))
return clazz;
Class superClass = clazz.getSuperclass();
while (!superClass.equals(RemoteViews.class)) {
superClass = superClass.getSuperclass();
}
return superClass;
}
public static @Nullable ApplicationInfo getApplicationInfo(Context context, RemoteViews remoteViews, Class<? extends RemoteViews> clazz) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return getApplicationInfoLollipop(remoteViews, clazz);
} else {
return getApplicationInfoDefault(context, remoteViews, clazz);
}
}
private static @Nullable ApplicationInfo getApplicationInfoLollipop(RemoteViews remoteViews, Class<? extends RemoteViews> clazz) {
try {
Field applicationField = clazz.getDeclaredField("mApplication");
applicationField.setAccessible(true);
return (ApplicationInfo) applicationField.get(remoteViews);
} catch (NoSuchFieldException e) {
Log.e(TAG, "no such field: ", e);
return null;
} catch (IllegalAccessException e) {
Log.e(TAG, "cannot access to the field: ", e);
return null;
}
}
private static @Nullable ApplicationInfo getApplicationInfoDefault(Context context, RemoteViews remoteViews, Class<? extends RemoteViews> clazz) {
try {
Field applicationField = clazz.getDeclaredField("mPackage");
applicationField.setAccessible(true);
String pkg = (String) applicationField.get(remoteViews);
PackageManager pm = context.getPackageManager();
return pm.getApplicationInfo(pkg, 0);
} catch (NoSuchFieldException e) {
Log.e(TAG, "no such field: ", e);
return null;
} catch (IllegalAccessException e) {
Log.e(TAG, "cannot access to the field: ", e);
return null;
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "no such package is installed: ", e);
return null;
}
}
}
|
C
|
UTF-8
| 7,164
| 3.5
| 4
|
[] |
no_license
|
/**
* @file cs131_program_1_FLAST.c
* @author YOUR NAME HERE
* @author Prof. Adams
* @date THE CURRENT DATE
*/
// INSTRUCTIONS:
// TASK 0/5: LOG IN TO ECLIPSE AND TYPE THE FOLLOWING IN PuTTY:
// cd ~/cs131
// touch cs131_program_1_FLAST.c
// git add cs131_program_1_FLAST.c
// git commit -m "Initial creation of Program 1 source code file"
//
// TASK 1/5: ADD INITIAL CONTENT:
// Open cs131_program_1_FLAST.c for editing (in Komodo or Pico)
// Paste the contents of this file into cs131_program_1_FLAST.c
// Modify the documentation at the very top to fix the FLAST, YOUR NAME HERE, and THE CURRENT DATE
// Save a snapshot with commit message "Starting content added to file"
// (Save your changes, 'git add' again, and 'git commit' with the requested message)
//
// There are four more tasks.
// Each task has a line that starts with "// TASK"
// You may do the rest of the tasks in any order
// Once you have followed the instructions for a task:
// Delete the "// TASK..." comment
// Save a snapshot with a message describing the task you completed
// Once you have done all the tasks, and your program compiles and runs:
// Add a line to the documentation at the top that says:
// * @status Working!
// Delete this big block of comments
// Double check there are no other // comments in your file
// Make one more snapshot with a message like "Done final cleanup"
// Tag your snapshot FLAST.prog.1
// Turn in your work in Moodle
//
// FYI, the task lines will ask you to:
// Write a documentation block for squareOf
// Write a declaration for the nextFibonacci function
// Write the function calls that find the averages of (1,2,3), (10, 10, 10), (11, 10, 10), (10, 12, 10), and (10,10,13)
// Write a definition for the nextInteger function
#include <stdio.h>
/**
* @author Prof. Adams
* @brief Figure out numbers in the Fibonacci sequence
* @param previous One of the two previous numbers in the sequence
* @param preprevious The other of the two previous numbers in the sequence
* @sideeffect Prints "The Fibonacci number after X and Y is Z" on screen, where X and Y are previous and preprevious, and Z is the same as what'll be returned.
* @return The next number in the Fibonacci sequence
* The forumla for the next number N in the Fibonacci sequence, based on the two previous numbers A,B, is N=A+B.
*
*/
//TASK 2: PUT DECLARATION LINE FOR nextFibonacci HERE
/**
* @author Prof. Adams
* @brief Figure out Ulam numbers... whatever those are.
* @param previous The number you want to start at
* @sideeffect Prints "The Ulam number after X is Y" on screen, where X is previous, and Y is the same as what'll be returned.
* @return The next Ulam number
*
* The 'next Ulam number' depends on whether the current number is odd or even.
* If it's even, the next number is half the current number.
* If it's odd, the next number is one more than three times the current number.
* Some guy named Ulam things that, eventually, this pattern will always lead you to 1.
*/
int nextUlam(int previous);
/**
* @author Prof. Adams
* @brief Count up by one.
* @param previous The number you're starting at
* @sideeffect Prints "The integer after X is Y" on screen, where X is previous, and Y is the same as what'll be returned.
* @return The one more than where you started from
*
* Really, this is just a glorified way to add one.
* (And put some spam on the screen in the process).
*/
int nextInteger(int previous);
/**
* @author Prof. Adams
* @brief Find the average of three numbers
* @param first One of your three numbers.
* @param second Another of your three numbers.
* @param third The last of your three numbers.
* @sideeffect Prints "The average of X, Y, Z is W" on screen, where X,Y,Z are the first, second, and third inputs, and W is their average.
* @return The average of first, second, and third
*
* Adds up all the inputs, then divides the total by three. Easy peasy.
*/
int averageOfThree(int first, int second, int third);
//TASK 3: PUT DOCUMENTATION BLOCK FOR squareOf HERE
int squareOf(int thingToSquare);
/**
* @brief Where your program starts running.
* @param argc How many 'tokens' were typed when you ran the program
* @param argv A collection of all the tokens that were typed
* @sideeffect The program is the side effect! CS language is weird...
* @return This returns 0, unless it crashes or something weird happens.
*
* This program has three stages.
*
* In the first stage, it figures out the first eight Fibonacci numbers, starting with 1,1,....
*
* In the second stage, it figures out the nine Ulam numbers after 5 (which ends up getting redundant after a while...)
*
* In the third stage, it counts out the six integers after 1.
*
* In the fourth and last stage, it finds the averages of a few trios of numbers.
*/
int main(int argc, char* argv[])
{
int shaggy_dog;
int scratchpad2;
printf("Integers...\n");
nextInteger(1);
nextInteger(2);
nextInteger(3);
nextInteger(4);
nextInteger(5);
nextInteger(6);
printf("\n\n");
printf("Averages...\n");
//TASK 4: PUT averageOfThree FUNCTION CALLS HERE
printf("\n\n");
printf("Squares...\n");
shaggy_dog=0;
squareOf( shaggy_dog=nextInteger(shaggy_dog) );
squareOf(shaggy_dog=nextInteger(shaggy_dog));
squareOf(shaggy_dog=nextInteger(shaggy_dog));
squareOf(shaggy_dog=nextInteger(shaggy_dog));
squareOf(shaggy_dog=nextInteger(shaggy_dog));
printf("\n\n");
printf("Fibonacci numbers...\n");
shaggy_dog=nextFibonacci(1,1);
scratchpad2=nextFibonacci(shaggy_dog,1);
shaggy_dog=nextFibonacci(shaggy_dog, scratchpad2);
scratchpad2=nextFibonacci(shaggy_dog, scratchpad2);
shaggy_dog=nextFibonacci(shaggy_dog, scratchpad2);
scratchpad2=nextFibonacci(shaggy_dog, scratchpad2);
shaggy_dog=nextFibonacci(shaggy_dog, scratchpad2);
scratchpad2=nextFibonacci(shaggy_dog, scratchpad2);
printf("\n\n");
printf("Ulam numbers...\n");
shaggy_dog=nextUlam(5);
scratchpad2=nextUlam(shaggy_dog);
scratchpad2=nextUlam(scratchpad2);
scratchpad2=nextUlam(scratchpad2);
scratchpad2=nextUlam(scratchpad2);
scratchpad2=nextUlam(scratchpad2);
scratchpad2=nextUlam(scratchpad2);
scratchpad2=nextUlam(scratchpad2);
scratchpad2=nextUlam(scratchpad2);
printf("\n\n");
return 0;
}
int nextFibonacci(int previous, int preprevious)
{
printf("\tThe Fibonacci number after %d and %d is %d\n",
preprevious, previous, previous+preprevious);
return previous+preprevious;
}
int nextUlam(int previous)
{
printf("\tThe Ulam number after %d is %d\n",
previous, (previous%2)?(previous/2):(3*previous+1));
return (previous%2)?(previous/2):(3*previous+1);
}
//TASK 5: PUT nextInteger FUNCTION DEFINITION HERE
int averageOfThree(int first, int second, int third)
{
printf("\tThe average of %d, %d, %d is %d\n",
first, second, third, (first+second+third)/3);
return (first+second+third)/3;
}
int squareOf(int thingToSquare)
{
printf("\tThe square of %d is %d\n", thingToSquare, thingToSquare*thingToSquare);
return thingToSquare*thingToSquare;
}
|
Shell
|
UTF-8
| 1,191
| 2.875
| 3
|
[] |
no_license
|
# vimで日本語が文字化けする場合:
# http://d.hatena.ne.jp/over80/20080907/1220794834
# Githubへのpushでusername/passwordを省略する方法
# http://shoken.hatenablog.com/entry/20120629/p1
# こんな感じで自分の$HOME直下に.netrcファイルを作成する。
#
# machine github.com
# login syokenz
# password xxxxxxx
# HTTPSではなくSSHを使う
# http://stackoverflow.com/questions/6565357/git-push-requires-username-and-password
# url = git@github.com:weed/140127-2013---2014--.git
# レポジトリに入る
cd 140127-2013-soukatsu-2014-houshin
# Markdownをpush
git add .
git commit -m "commited automatically by push.sh"
git push
# mdpressコマンドでreadmeフォルダを生成
cd ..
mdpress 140127-2013-soukatsu-2014-houshin/readme.md
# gh-pagesブランチに切り替える
cd 140127-2013-soukatsu-2014-houshin
git checkout gh-pages
# 先ほど生成したreadmeフォルダの中身をレポジトリにコピーする
cp -rf ../readme/* .
# 自動的にcommit+push
git add .
git commit -m "commited automatically by push.sh"
git push
# originブランチに戻す
git checkout master
# 元いたディレクトリに戻る
cd ..
|
C
|
UTF-8
| 6,199
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "gamma.h"
#include <stdbool.h>
#include <string.h>
int main() {
/*
scenario: test_random_actions
uuid: 775876853
*/
/*
random actions, total chaos
*/
gamma_t* board = gamma_new(9, 4, 8, 5);
assert( board != NULL );
assert( gamma_move(board, 1, 4, 1) == 1 );
assert( gamma_move(board, 1, 1, 2) == 1 );
assert( gamma_move(board, 2, 0, 2) == 1 );
assert( gamma_move(board, 3, 0, 2) == 0 );
assert( gamma_busy_fields(board, 3) == 0 );
assert( gamma_golden_move(board, 3, 2, 0) == 0 );
assert( gamma_move(board, 4, 0, 5) == 0 );
assert( gamma_move(board, 4, 5, 1) == 1 );
char* board687834865 = gamma_board(board);
assert( board687834865 != NULL );
assert( strcmp(board687834865,
".........\n"
"21.......\n"
"....14...\n"
".........\n") == 0);
free(board687834865);
board687834865 = NULL;
assert( gamma_move(board, 5, 8, 2) == 1 );
assert( gamma_move(board, 6, 0, 1) == 1 );
assert( gamma_golden_move(board, 6, 2, 0) == 0 );
assert( gamma_move(board, 7, 0, 5) == 0 );
assert( gamma_move(board, 7, 7, 2) == 1 );
assert( gamma_golden_possible(board, 7) == 1 );
assert( gamma_move(board, 8, 3, 3) == 1 );
assert( gamma_move(board, 1, 3, 5) == 0 );
assert( gamma_move(board, 2, 3, 6) == 0 );
assert( gamma_move(board, 3, 3, 7) == 0 );
assert( gamma_move(board, 3, 4, 0) == 1 );
assert( gamma_move(board, 4, 0, 8) == 0 );
assert( gamma_move(board, 4, 2, 3) == 1 );
assert( gamma_move(board, 5, 2, 4) == 0 );
assert( gamma_busy_fields(board, 5) == 1 );
assert( gamma_move(board, 6, 3, 7) == 0 );
assert( gamma_move(board, 7, 7, 1) == 1 );
assert( gamma_move(board, 7, 0, 1) == 0 );
assert( gamma_move(board, 8, 0, 1) == 0 );
assert( gamma_move(board, 8, 7, 0) == 1 );
assert( gamma_move(board, 1, 7, 1) == 0 );
assert( gamma_golden_possible(board, 1) == 1 );
assert( gamma_move(board, 2, 3, 0) == 1 );
assert( gamma_move(board, 2, 6, 3) == 1 );
assert( gamma_move(board, 3, 0, 1) == 0 );
assert( gamma_golden_possible(board, 3) == 1 );
assert( gamma_move(board, 4, 0, 8) == 0 );
assert( gamma_move(board, 4, 4, 2) == 1 );
assert( gamma_move(board, 5, 1, 2) == 0 );
assert( gamma_move(board, 6, 6, 2) == 1 );
assert( gamma_move(board, 7, 0, 5) == 0 );
assert( gamma_golden_possible(board, 7) == 1 );
assert( gamma_move(board, 8, 3, 3) == 0 );
assert( gamma_move(board, 8, 3, 0) == 0 );
assert( gamma_move(board, 1, 3, 1) == 1 );
assert( gamma_move(board, 2, 6, 1) == 1 );
assert( gamma_move(board, 3, 0, 1) == 0 );
assert( gamma_move(board, 3, 5, 1) == 0 );
assert( gamma_move(board, 5, 0, 0) == 1 );
assert( gamma_golden_possible(board, 5) == 1 );
assert( gamma_move(board, 6, 1, 1) == 1 );
assert( gamma_move(board, 6, 4, 1) == 0 );
assert( gamma_move(board, 7, 0, 5) == 0 );
assert( gamma_move(board, 7, 3, 3) == 0 );
assert( gamma_golden_move(board, 7, 0, 4) == 0 );
assert( gamma_move(board, 8, 0, 6) == 0 );
assert( gamma_move(board, 8, 4, 3) == 1 );
assert( gamma_busy_fields(board, 8) == 3 );
assert( gamma_move(board, 1, 3, 1) == 0 );
assert( gamma_move(board, 1, 3, 1) == 0 );
assert( gamma_move(board, 2, 3, 5) == 0 );
assert( gamma_move(board, 2, 5, 2) == 1 );
char* board880686049 = gamma_board(board);
assert( board880686049 != NULL );
assert( strcmp(board880686049,
"..488.2..\n"
"21..42675\n"
"66.11427.\n"
"5..23..8.\n") == 0);
free(board880686049);
board880686049 = NULL;
assert( gamma_move(board, 3, 2, 3) == 0 );
assert( gamma_move(board, 4, 3, 1) == 0 );
assert( gamma_move(board, 5, 0, 8) == 0 );
assert( gamma_move(board, 6, 3, 8) == 0 );
assert( gamma_golden_possible(board, 6) == 1 );
assert( gamma_move(board, 8, 2, 3) == 0 );
assert( gamma_move(board, 1, 3, 0) == 0 );
assert( gamma_busy_fields(board, 1) == 3 );
assert( gamma_move(board, 2, 3, 1) == 0 );
assert( gamma_golden_move(board, 2, 3, 2) == 0 );
assert( gamma_move(board, 3, 0, 5) == 0 );
assert( gamma_free_fields(board, 3) == 14 );
assert( gamma_move(board, 4, 7, 0) == 0 );
assert( gamma_move(board, 4, 7, 0) == 0 );
assert( gamma_move(board, 5, 1, 1) == 0 );
assert( gamma_move(board, 5, 6, 3) == 0 );
assert( gamma_move(board, 6, 0, 5) == 0 );
assert( gamma_move(board, 6, 1, 0) == 1 );
assert( gamma_move(board, 7, 3, 7) == 0 );
assert( gamma_free_fields(board, 7) == 13 );
assert( gamma_move(board, 1, 2, 2) == 1 );
assert( gamma_move(board, 1, 0, 1) == 0 );
assert( gamma_busy_fields(board, 1) == 4 );
assert( gamma_move(board, 2, 3, 5) == 0 );
assert( gamma_move(board, 3, 6, 1) == 0 );
assert( gamma_move(board, 3, 8, 1) == 1 );
assert( gamma_move(board, 4, 8, 0) == 1 );
assert( gamma_busy_fields(board, 4) == 4 );
assert( gamma_move(board, 5, 3, 0) == 0 );
assert( gamma_move(board, 6, 0, 5) == 0 );
assert( gamma_move(board, 7, 3, 8) == 0 );
assert( gamma_move(board, 7, 1, 0) == 0 );
assert( gamma_move(board, 8, 3, 7) == 0 );
char* board933430431 = gamma_board(board);
assert( board933430431 != NULL );
assert( strcmp(board933430431,
"..488.2..\n"
"211.42675\n"
"66.114273\n"
"56.23..84\n") == 0);
free(board933430431);
board933430431 = NULL;
assert( gamma_move(board, 1, 3, 0) == 0 );
assert( gamma_move(board, 1, 7, 2) == 0 );
assert( gamma_move(board, 2, 3, 8) == 0 );
assert( gamma_move(board, 3, 3, 7) == 0 );
assert( gamma_move(board, 3, 1, 0) == 0 );
assert( gamma_move(board, 4, 1, 3) == 1 );
assert( gamma_move(board, 4, 6, 3) == 0 );
assert( gamma_move(board, 5, 1, 2) == 0 );
assert( gamma_move(board, 5, 6, 2) == 0 );
assert( gamma_move(board, 6, 0, 5) == 0 );
assert( gamma_move(board, 6, 0, 1) == 0 );
assert( gamma_move(board, 7, 3, 7) == 0 );
assert( gamma_move(board, 7, 0, 3) == 1 );
assert( gamma_golden_possible(board, 7) == 1 );
assert( gamma_move(board, 8, 5, 1) == 0 );
assert( gamma_move(board, 8, 3, 3) == 0 );
assert( gamma_move(board, 1, 0, 2) == 0 );
assert( gamma_move(board, 2, 3, 8) == 0 );
assert( gamma_move(board, 2, 7, 3) == 1 );
assert( gamma_move(board, 3, 0, 6) == 0 );
assert( gamma_move(board, 5, 2, 3) == 0 );
assert( gamma_move(board, 6, 7, 1) == 0 );
assert( gamma_move(board, 7, 0, 6) == 0 );
assert( gamma_free_fields(board, 7) == 7 );
assert( gamma_move(board, 8, 0, 5) == 0 );
assert( gamma_move(board, 8, 2, 0) == 1 );
gamma_delete(board);
return 0;
}
|
Python
|
UTF-8
| 1,842
| 3.21875
| 3
|
[] |
no_license
|
class Accounts:
def __init__(self):
self.firstname = Accounts.new_firstname()
self.lastname = Accounts.new_lastname()
self.middlename = Accounts.new_middlename()
self.username = Accounts.new_username()
self.password = Accounts.new_pass()
self.account_number = Accounts.newacc_number()
self.account_email = Accounts.new_email()
def new_firstname():
cls()
while True:
new_fname = input("Enter your first name: ")
if new_fname == '':
cls()
print("First name field cannot be blank. Please try again")
else:
return new_fname
def new_lastname():
cls()
while True:
new_lname = input("Enter your last name: ")
if new_lname == '':
cls()
print("Last name field cannot be blank. Please try again")
else:
return new_lname
def new_middlename():
cls()
new_mname = input("Enter your middle name or press enter to leave it blank: ")
return new_mname
cls()
def new_username():
new_uname = input("Create a username: ")
while True:
#Need to fix this to look at the database instead of the dictionary
if new_uname in db.username:
print("Username already exists. Please try again")
else:
return new_uname
def new_pass():
while True:
new_pass = input("Create a password: (*minimum of 8 characters and must begin with a letter):")
if len(new_pass) < 8 or new_pass[0].isalpha() != True :
print("Password does not meet the criteria. Please try again")
else:
return new_pass
def new_accnumber():
gen_accnum = string.digits
accnum = ''.join(choice(gen_accnum) for i in range(8))
return accnum
def new_email():
while True:
email = input("Enter your email address: ")
import os
import database as db
def cls():
os.system('cls')
|
Markdown
|
UTF-8
| 629
| 2.609375
| 3
|
[] |
no_license
|
---
layout: post
title: Macbook Air, upgrade or not? No, thanks.
date: 2016-11-16
categories: #off-topic #mac
---
Someone asked if I have thought about upgrading my Macbook Air 11" and the answer is **no, I won't upgrade yet**.
Still more than enough for everything I use it for and the SSD makes it blazing fast. Basically my daily usage:
- Tmux/Vim multiple sessions
- Vagrant (2 machines at a time)
- MongoDB/Elasticsearch/PostgreSQL
- Photoshop
- Chrome
<a href="http://imgur.com/17PfYWM"><img src="http://i.imgur.com/17PfYWM.png" title="source: imgur.com" /></a>
The Macbook Air 11" still the best Macbook made yet.
|
Python
|
UTF-8
| 1,617
| 2.5625
| 3
|
[] |
no_license
|
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def main():
fs = 44100
Ts = 1/fs
suffix = "_f"
rows_fname = "rows_buffs_size" + suffix + ".csv"
cols_fname = "cols_irs_size" + suffix + ".csv"
buffs_fname = "n_proc_buffers" + suffix + ".csv"
proc_fname = "proc_duration" + suffix + ".csv"
# [:, :-1] Remove last value caused by trailing comma
rows = pd.read_csv(rows_fname, header=None).to_numpy()[:, :-1]
cols = pd.read_csv(cols_fname, header=None).to_numpy()[:, :-1]
buffs_n = pd.read_csv(buffs_fname, header=None).to_numpy()[:, :-1]
proc = pd.read_csv(proc_fname, header=None).to_numpy()[:, :-1]
print(rows)
print('\n')
print(cols)
print('\n')
print(buffs_n)
print('\n')
print(proc)
print('\n')
proc[proc <= 0] = np.nan
plt.figure()
for i in range(2, len(proc)):
p = proc[i]
buff_size = rows[0, i]
print(buff_size*Ts)
plt.plot(cols.T, p/(buff_size*Ts), '--o',
label="buffer_size = {:.0f}".format(buff_size))
# plt.figure()
# for i, p in enumerate(proc):
# buff_size = rows[0, i]
# plt.plot(cols.T, p/(buff_size*Ts), '--o',
# label="buffer_size = {:.0f}".format(buff_size))
plt.hlines(1, xmin=cols[0, 0], xmax=cols[0, -1], linestyles='dashdot')
plt.xlabel("Impulse response size")
plt.ylabel("Processing time")
plt.xticks(cols.T)
plt.legend()
plt.savefig(os.path.join('../img/', 'graph' + suffix + '_tmp.png'))
plt.show()
if __name__ == "__main__":
main()
|
Markdown
|
UTF-8
| 2,535
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
# React Todo App
A basic todos application with data persistence and authentication that uses ReactJS on the frontend and Firebase on the backend.
## Usage
Install packages
```
npm install
```
And build client.min.js bundle
```
npm run build
```
Now index.html can be used with the bundled javascript file to view React components.
### Using Dev Server
Webpack has capabilities to run the app on its server.
```
npm run build-server
```
And now the app can be viewed on <http://localhost:8080> by default.
### Setting Up Firebase
Go to <https://firebase.google.com/> and "Get Started" to create unique project. Once project is created, navigate to main console and click on "Add Firebase to your web app" and the snippet should look like this:
```
<script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "[My API Key]",
authDomain: "[my-project-name].firebaseapp.com",
databaseURL: "https://[my-project-name].firebaseio.com",
projectId: "[my-project-name]",
storageBucket: "[my-project-name].appspot.com",
messagingSenderId: "833094533555"
};
firebase.initializeApp(config);
</script>
```
Copy only the javascript and insert it into the constructor in src/js/FirebaseAPI.js and replace the similar javascript pertaining to the example Firebase backend project.
It will also be required that the authentication settings be changed as well. Go to the Authentication dashboard, navigate to the 'SIGN-IN METHOD' tab and Enable the "Email/Password" Provider to be able to start signing in and creating new users within the todo app.
The app is now ready to be used and modified to build on it as a starter template for more complex applications.
## Built With
* [ReactJS](https://reactjs.org/) - The ReactJS frontend library
* [Firebase](https://firebase.google.com/) - Backend Tools and Infrastructure for Free with Limited Use
* [Material-UI](http://www.material-ui.com/#/) - Awesome library of React Components that implement Google's Material design.
* [Bootstrap 4](https://getbootstrap.com/) - Responsive front-end component library.
* [Webpack](https://webpack.js.org/) - Bundles modules and dependencies into static assets.
* [Babel](https://babeljs.io/) - Javascript and React Transpiler
## Authors
* **Titan Global Tech, LLC** - *All Work Contained* - [b1tn3r](https://github.com/b1tn3r)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
|
Java
|
UTF-8
| 1,749
| 2.78125
| 3
|
[] |
no_license
|
package com.garethabrahams.repository.impl;
import com.garethabrahams.factory.EmployeeFactory;
import com.garethabrahams.model.Employee;
import com.garethabrahams.repository.EmployeeRepository;
import org.junit.Assert;
import org.junit.Test;
import sun.awt.geom.AreaOp;
import java.applet.Applet;
import static org.junit.Assert.*;
public class EmployeeRepositoryImplTest {
private static EmployeeRepository repository;
private static Employee employee;
private String employeeID;
@Test
public void create() {
repository = EmployeeRepositoryImpl.getRepository();
employee = EmployeeFactory.createEmployee("Gareth","Abrahams");
Employee results = repository.create(employee);
employeeID = results.getEmpNum();
Assert.assertEquals(employeeID,employee.getEmpNum());
}
@Test
public void update() {
create();
Employee oldEmp = repository.read(employeeID);
System.out.println(oldEmp.toString());
String newLast = "Gates";
Employee newEmp = new Employee.Builder().copy(oldEmp).lastName(newLast).build();
System.out.println(newEmp.toString());
this.repository.update(newEmp);
Assert.assertEquals(newLast,newEmp.getLastName());
}
@Test
public void delete() {
create();
Employee result = repository.read(employeeID);
System.out.println(result.toString());
repository.delete(employeeID);
Employee newResult = repository.read(employeeID);
Assert.assertNull(newResult);
}
@Test
public void read() {
create();
Employee result = repository.read(employeeID);
Assert.assertEquals(employeeID,result.getEmpNum());
}
}
|
C#
|
UTF-8
| 2,232
| 2.96875
| 3
|
[] |
no_license
|
using Cash_Register_Divyansh.ApplicationTypes;
using Cash_Register_Divyansh.Contracts.Business;
using Cash_Register_Divyansh.Models;
using System;
namespace Cash_Register_Divyansh.BusinessLogic
{
/// <summary>
/// Responsible for discount calculation of scanned items
/// </summary>
public class CostCalculatorManager : ICostCalculatorManager
{
public ListItem CalculateCost(Item scannedItem, decimal quantity)
{
var lItem = new ListItem();
switch (scannedItem.DiscountType)
{
case DiscountType.Cost:
lItem.CalculatedCost = (100 - Convert.ToDecimal(scannedItem.DiscountValue)) * (decimal)0.01 *
scannedItem.PerUnitPrice * quantity;
lItem.Item = scannedItem;
lItem.DiscountSummary = string.Format("Discount Applied: {0}% off", scannedItem.DiscountValue);
break;
case DiscountType.Quantity:
var baseQty = Convert.ToInt16(scannedItem.DiscountValue.Split('|')[0]);
var discountedQty = Convert.ToInt16(scannedItem.DiscountValue.Split('|')[1]);
var qtyPerDiscountedQty = (int)(quantity / (baseQty + discountedQty));
lItem.CalculatedCost = qtyPerDiscountedQty * baseQty *
scannedItem.PerUnitPrice + ((quantity % (baseQty + discountedQty)) * scannedItem.PerUnitPrice);
lItem.Item = scannedItem;
if (qtyPerDiscountedQty > 0)
{
lItem.DiscountSummary = string.Format("Discount Applied: Buy {0} get {1} free", baseQty, discountedQty);
}
break;
default:
lItem.CalculatedCost = scannedItem.PerUnitPrice * quantity;
lItem.Item = scannedItem;
break;
}
lItem.EnteredQuantity = quantity;
return lItem;
}
}
}
|
Shell
|
UTF-8
| 9,216
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
# Set Variables
PROJECT="default"
HOST_PROJECT="default"
NETWORK="default"
SUBNET="default"
REGION="us-east4"
ZONE="us-east4-a"
USER_EMAIL="default"
USER_ROLE_NAME="netappuserrole"
SERVICE_CONNECTOR_ROLE_NAME="netappscrole"
SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME="netapp-service-connector"
CVO_SERVICE_ACCOUNT_NAME="netapp-cloud-volumes-ontap"
USER_POLICY_LINK="https://occm-sample-policies.s3.amazonaws.com/Setup_As_Service_3.7.3_GCP.yaml"
SC_POLICY_LINK="https://occm-sample-policies.s3.amazonaws.com/Policy_for_Cloud_Manager_3.9.0_GCP.yaml"
SERVICE_CONNECTOR_INSTANCE_NAME="netapp-service-connector"
SHARED_VPC=0
function welcome {
echo "Hello, $USER!"
echo "This script will prepare your Google project to deploy Cloud Volumes ONTAP and the Service Connector, would you like to keep the default settings (Yes if already changed variables)?"
select yn in "Yes" "No"; do
case $yn in
Yes ) break;;
No ) echo "Please change the settings, goodbye!"; exit;;
esac
done
}
function shared_vpc_choice {
echo "Would you like to deploy into a shared VPC?"
select yn in "Yes" "No"; do
case $yn in
Yes ) SHARED_VPC=1; correct_project_choice; break;;
No ) break;;
esac
done
}
function correct_project_choice {
printf "Are these values correct? \n\
Service Project: $PROJECT \n\
Host Project: $HOST_PROJECT \n\
Network: $NETWORK \n\
Subnet: $SUBNET \n"
select yn in "Yes" "No"; do
case $yn in
Yes ) break;;
No ) echo "Please set the project to the service project and set all variables within this script"; exit;;
esac
done
}
function set_variables {
test "$PROJECT" == "default" && PROJECT=`gcloud config list --format 'value(core.project)' 2>/dev/null`
echo "Project set to: $PROJECT"
test "$USER_EMAIL" == "default" && USER_EMAIL=`gcloud config list --format 'value(core.account)' 2>/dev/null`
echo "User set to: $USER_EMAIL"
}
function enable_apis {
echo "Enabling APIs"
gcloud services enable deploymentmanager.googleapis.com logging.googleapis.com cloudresourcemanager.googleapis.com compute.googleapis.com iam.googleapis.com
test $SHARED_VPC == 1 && gcloud services enable --project=$HOST_PROJECT deploymentmanager.googleapis.com logging.googleapis.com cloudresourcemanager.googleapis.com compute.googleapis.com iam.googleapis.com
}
function download_policies {
echo "Downloading policies"
curl $USER_POLICY_LINK -o NetAppUserPolicy.yaml
curl $SC_POLICY_LINK -o NetAppSCPolicy.yaml
}
function set_user_permissions {
echo "Setting user permissions"
gcloud iam roles create $USER_ROLE_NAME --project=$PROJECT --file NetAppUserPolicy.yaml
gcloud projects add-iam-policy-binding $PROJECT --member=user:$USER_EMAIL --role=projects/$PROJECT/roles/$USER_ROLE_NAME
if test $SHARED_VPC == 1
then
gcloud iam roles create $USER_ROLE_NAME --project=$HOST_PROJECT --file NetAppUserPolicy.yaml
gcloud projects add-iam-policy-binding $HOST_PROJECT --member=user:$USER_EMAIL --role=projects/$HOST_PROJECT/roles/$USER_ROLE_NAME
fi
}
function set_service_connector_permissions {
echo "Setting service connector permissions"
gcloud iam roles create $SERVICE_CONNECTOR_ROLE_NAME --project $PROJECT --file NetAppSCPolicy.yaml
gcloud iam service-accounts create $SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME --description="Allows NetApp Service Connector to deploy and manage Cloud Volumes ONTAP instances" --display-name="NetApp Service Connector"
gcloud projects add-iam-policy-binding $PROJECT --member=serviceAccount:$SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com --role=projects/$PROJECT/roles/$SERVICE_CONNECTOR_ROLE_NAME
if test $SHARED_VPC == 1
then
gcloud projects add-iam-policy-binding $HOST_PROJECT --member=serviceAccount:$SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com --role=roles/compute.networkUser
gcloud projects add-iam-policy-binding $HOST_PROJECT --member=serviceAccount:$SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com --role=roles/deploymentmanager.editor
COMPUTE_ENGINE_SERVICE_ACCOUNT=`gcloud iam service-accounts list --format 'value(email)' --filter 'displayName:"Compute Engine default service account"' 2>/dev/null`
gcloud projects add-iam-policy-binding $HOST_PROJECT --member=serviceAccount:$COMPUTE_ENGINE_SERVICE_ACCOUNT --role=roles/compute.networkUser
fi
}
function set_tiering_account_permissions {
echo "Setting CVO permissions"
gcloud iam service-accounts create $CVO_SERVICE_ACCOUNT_NAME --description="Allows NetApp Cloud Volumes ONTAP instance to tier to GCS" --display-name="NetApp Cloud Volumes ONTAP"
gcloud projects add-iam-policy-binding $PROJECT --member=serviceAccount:$CVO_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com --role=roles/storage.admin
gcloud iam service-accounts add-iam-policy-binding $CVO_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com --member=serviceAccount:$SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com --role=roles/iam.serviceAccountUser
}
function deploy_service_connector_choice {
PUBLIC_IP=0
echo "Would you like to deploy the Service Connector from here?"
select yn in "Yes" "No"; do
case $yn in
Yes ) break;;
No ) echo "Configuration complete, goodbye!"; exit;;
esac
done
echo "Would you like to assign a public IP?"
select yn in "Yes" "No"; do
case $yn in
Yes ) echo "Public IP will be assigned";
PUBLIC_IP=1;
if test $SHARED_VPC == 1
then
gcloud compute instances create $SERVICE_CONNECTOR_INSTANCE_NAME \
--machine-type=n1-standard-4 \
--zone=$ZONE \
--network=projects/$HOST_PROJECT/global/networks/$NETWORK \
--subnet=projects/$HOST_PROJECT/regions/$REGION/subnetworks/$SUBNET \
--image-project=netapp-cloudmanager \
--image-family=cloudmanager \
--tags=http-server,https-server \
--service-account=$SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com\
--scopes=cloud-platform;
else
gcloud compute instances create $SERVICE_CONNECTOR_INSTANCE_NAME \
--machine-type=n1-standard-4 \
--zone=$ZONE \
--network=$NETWORK \
--subnet=$SUBNET \
--image-project=netapp-cloudmanager \
--image-family=cloudmanager \
--tags=http-server,https-server \
--service-account=$SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com\
--scopes=cloud-platform;
fi
break;;
No ) echo "Private IP only being used"; \
if test $SHARED_VPC == 1
then
gcloud compute instances create $SERVICE_CONNECTOR_INSTANCE_NAME \
--machine-type=n1-standard-4 \
--zone=$ZONE \
--network=projects/$HOST_PROJECT/global/networks/$NETWORK \
--subnet=projects/$HOST_PROJECT/regions/$REGION/subnetworks/$SUBNET \
--no-address \
--image-project=netapp-cloudmanager \
--image-family=cloudmanager \
--tags=http-server,https-server \
--service-account=$SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com\
--scopes=cloud-platform;
else
gcloud compute instances create $SERVICE_CONNECTOR_INSTANCE_NAME \
--machine-type=n1-standard-4 \
--zone=$ZONE \
--network=$NETWORK \
--subnet=$SUBNET \
--no-address \
--image-project=netapp-cloudmanager \
--image-family=cloudmanager \
--tags=http-server,https-server \
--service-account=$SERVICE_CONNECTOR_SERVICE_ACCOUNT_NAME@$PROJECT.iam.gserviceaccount.com\
--scopes=cloud-platform;
fi
break;;
esac
done
echo "Service connector being deployed!"
gcloud compute instances describe $SERVICE_CONNECTOR_INSTANCE_NAME --zone $ZONE
}
function goodbye {
echo "Thank you for using the GCP Service Connector deployment script, goodbye!"
}
function main {
welcome
set_variables
shared_vpc_choice
enable_apis
download_policies
set_user_permissions
set_service_connector_permissions
set_tiering_account_permissions
deploy_service_connector_choice
goodbye
}
main
|
Java
|
UTF-8
| 389
| 1.78125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package xyz.erupt.annotation.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* @author YuePeng
* date 2020-12-23.
*/
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.FIELD, ElementType.TYPE_PARAMETER, ElementType.PARAMETER})
@Documented
public @interface Comments {
Comment[] value();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.