language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 3,035
| 3.984375
| 4
|
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# ### 파이썬 문자열
# In[1]:
a = '파이썬'
# In[2]:
print(a)
# In[3]:
b = "문자열"
# In[4]:
print(b)
# In[7]:
c = """
파이썬
문자열
"""
# In[8]:
print(c)
# In[10]:
# '파이썬' + 3
#파이썬은 +으로 문자열 연결 불가능
# In[11]:
d = '파이썬' + str(3)
# In[12]:
print(d)
# In[13]:
e = '*' * 10
# In[14]:
print(e)
# In[15]:
a = 'helloWorld'
# In[16]:
a
# In[17]:
a[0]
# In[18]:
a[5]
# In[19]:
a[-1]
# In[20]:
a[-2]
# In[21]:
a[:5]
# In[22]:
a[5:]
# In[23]:
a[:]
# In[24]:
a
# In[25]:
a[::2]
# In[26]:
a[::-1] #역정렬
# In[28]:
a[::-2]
# ### 파이썬 문자열 함수
# #### len
# In[29]:
len('helloworldpython')
# #### join
# In[30]:
'-'.join("helloworldpython")
# In[31]:
'-'.join('12345')
# #### split
# In[33]:
'Hello-World-Python'.split('-')
# In[34]:
'서울시 마포구 상암동 1586'.split()
# #### strip
# In[35]:
text = '\t 문자열 정리 \n'
text.strip()
# #### startswith / endswith
# In[37]:
'hello world python'.startswith('hello')
# In[38]:
'hello world python'.startswith('Hello')
# In[39]:
'hello world python'.endswith('python')
# In[40]:
'hello world python'.endswith('Python')
# #### count
# In[41]:
text = 'hello world python'
text.count('o')
# In[42]:
text = 'Hello world Python, welcome to Python world'
text.count('Python')
# #### index
# In[43]:
text.index('o')
# In[44]:
text.index('o',5) #인덱스 5이후의 o의 인덱스 반환
# #### find
# In[45]:
text.find('Python')
# In[46]:
text.find('Python', 20)
# #### capitalize / lower / upper
# In[47]:
"Hello World".capitalize()
# In[48]:
"Hello World".lower()
# In[49]:
"Hello World".upper()
# #### in
# In[50]:
'Python' in 'Hello World Python'
# In[51]:
'Java' in 'Hello World Python'
# ### 파이썬 문자열 포맷팅
# In[52]:
name, age, phone = '홍길동', 25, '010-111-2222'
# #### 포맷 방법 1
# In[53]:
소개 = "이름은 {} 이고, 나이는 {}세 이며, 전화번호는 {} 입니다. ".format(name, age, phone)
소개
# #### 포맷 방법 2
# In[54]:
소개 = "이름은 {0} 이고, 나이는 {2}세 이며, 전화번호는 {1} 입니다. ".format(name, phone, age)
소개
# #### 포맷 방법 3
# In[55]:
소개 = "이름은 {a} 이고, 나이는 {b}세 이며, 전화번호는 {c} 입니다. ".format(c = phone, a = name, b = age)
소개
# #### 포맷 방법 4 (권장)
# In[56]:
소개 = f"이름은 {name} 이고, 나이는 {age}세 이며, 전화번호는 {phone} 입니다. "
소개
# ### 문자열 포맷팅
# In[58]:
jan, dec = 1, 12
# In[59]:
print("한 해의 시작은 {:02d}월".format(jan))
print("한 해의 마지막은 {:02d}월".format(dec))
# In[61]:
val = 123456789
money = "{:,}"
money.format(val)
# In[62]:
'{}, {:f}, {:.1f}, {:.2f}, {:.2%}'.format(3, 3, 3, 3.1415, 1/3)
# In[63]:
1/3
# In[ ]:
|
Python
|
UTF-8
| 943
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib import style
from os import path
style.use('ggplot')
rcParams.update({'font.size': 9})
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 10
fig_size[1] = 4.2
plt.rcParams["figure.figsize"] = fig_size
df = pd.read_csv('Storage net withdrawals.csv')
df.dropna()
df = df.iloc[::-1]
mycolors = ['g', 'orange', 'b']
a = df.plot(x = 'Date', y=['Injections',\
'Withdrawals',\
'Net Withdrawals'], kind="line", color=mycolors)
for line in a.lines:
line.set_linewidth(0.7)
a.xaxis.grid(False)
a.legend(bbox_to_anchor=(0.88, -0.12), loc='best', ncol=3, fontsize='x-large')
plt.tick_params(axis='x', labelsize=7)
plt.xlabel("Date", color='black')
plt.ylabel("Billion Cubic Feet per Day (Bcf/d)",color='black')
plt.savefig(path.basename(__file__)+".png",bbox_inches='tight')
# plt.show()
|
Python
|
UTF-8
| 419
| 4.03125
| 4
|
[] |
no_license
|
print('You will be prompted for 3 Test Scores below.')
print('======================')
score_1 = int(input('Enter test score:'))
score_2 = int(input('Enter test score:'))
score_3 = int(input('Enter test score:'))
print('=======================')
print('Your Scores: ', score_1, score_2, score_3)
total_score = score_1 + score_2 + score_3
print('Total Score: ', total_score)
print('Average Score: ', total_score / 3)
|
Markdown
|
UTF-8
| 1,529
| 3.28125
| 3
|
[] |
no_license
|
# ComputerDialog
## Props
<!-- @vuese:ComputerDialog:props:start -->
|Name|Description|Type|Required|Default|
|---|---|---|---|---|
|edit|The computer that we are editing if any has been given|`any`|`false`|-|
|dialog|The dialog that controls if this component is showing or not|`boolean`|`false`|-|
<!-- @vuese:ComputerDialog:props:end -->
## Methods
<!-- @vuese:ComputerDialog:methods:start -->
|Method|Description|Parameters|
|---|---|---|
|updated|Used to change the funcionalty from editing to new computer and vice versa|-|
|mounted|Used to open the component with the funcionalty of editing or new computer|-|
|handleProgram|Used to add a program to the computer programs list|The argument is a computer|
|deleteProgram|Used to remove a program to the computer programs list|The argument is a computer|
|close|Used to close this dialog|-|
|saveComputer|Used to save the newly created computer to the database making a call to the API or edit a given computer depending on the mode this component is working|The argument is a computer|
|deleteComputer|Used to remove a computer from the system|The argument is a computer|
|changeAllowed|Used to change the permissions of a user to allowed or disallowed|The first argument is a string representing the user who is to be changed The second argument is a boolean representing if the user is allowed(true) or not(false) The third argument is a string representing the mac of the computer that we want to allow access or not|
<!-- @vuese:ComputerDialog:methods:end -->
|
Java
|
UTF-8
| 616
| 2.40625
| 2
|
[] |
no_license
|
package com.controller.responce;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by vlad on 23.04.17.
*/
public class ForwardViewDispatcher implements Dispatcher {
private final String VIEW;
public ForwardViewDispatcher(String view) {
VIEW = view;
}
@Override
public void dispatch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher(VIEW).forward(request,response);
}
}
|
Python
|
UTF-8
| 2,515
| 3.328125
| 3
|
[] |
no_license
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import OrderedDict
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
depth = 0
n = len(S)
i = 0
root = None
stk = []
while i < n:
if S[i] == "-":
depth += 1
i += 1
else:
j = i
while j < n and S[j] != "-":
j += 1
val = int(S[i:j])
cur = TreeNode(val)
if depth == 0:
root = cur
stk = [(depth, root)]
else:
assert stk
while stk[-1][0] != depth - 1:
stk.pop()
_, pi = stk[-1]
if not pi.left:
pi.left = cur
elif not pi.right:
pi.right = cur
stk.pop()
else:
raise
stk.append((depth, cur))
depth = 0
i = j
return root
def recoverFromPreorder_error(self, S: str) -> TreeNode:
depth = 0
depths = OrderedDict()
n = len(S)
i = 0
while i < n:
if S[i] == "-":
depth += 1
i += 1
else:
j = i
while j < n and S[j] != "-":
j += 1
val = int(S[i:j])
depths[val] = depth
depth = 0
i = j
stk = []
root = None
for k, v in depths.items():
cur = TreeNode(k)
if v == 0:
root = cur
stk = [root]
else:
assert stk
while depths[stk[-1].val] != v - 1:
stk.pop()
if not stk[-1].left:
stk[-1].left = cur
elif not stk[-1].right:
stk[-1].right = cur
stk.pop()
else:
raise
stk.append(cur)
return root
if __name__ == "__main__":
assert Solution().recoverFromPreorder("5-4--4")
assert Solution().recoverFromPreorder("1-2--3--4-5--6--7")
|
Python
|
UTF-8
| 1,243
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
# Usage:
# cd 2-visual_test
# cat ../1-data/training_images.txt | ../mapper.py | ../reducer.py > weights.txt
# ../evaluate_to_file.py weights.txt ../1-data/images.txt > prediction.txt
import logging
import sys
import numpy as np
# So we can use the same feature vectors.
from mapper import transform
if __name__ == "__main__":
if not len(sys.argv) == 3:
logging.error("Usage: evaluate.py weights.txt test_data.txt")
sys.exit(1)
with open(sys.argv[1], "r") as fp_weights:
weights = np.genfromtxt(fp_weights).flatten()
with open(sys.argv[2], "r") as fp_data:
#with open(sys.argv[3], "r") as fp_labels:
for x_string in fp_data:
x_string = x_string.strip()
x_original = np.fromstring(x_string, sep=' ')
x = transform(x_original).flatten() # Use our features.
if not x.shape == weights.shape:
logging.error("Shapes of weight vector and transformed "
"data don't match")
sys.exit(3)
#if (np.inner(weights, x) < 0):
# print -1
#else:
# print 1
print(-1 if np.inner(weights, x) < 0 else 1)
|
C++
|
UTF-8
| 447
| 2.796875
| 3
|
[] |
no_license
|
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main() {
long t;
cin>>t;
queue<long> q;
string s;
while (t--) {
cin>>s;
if (s == "PUSH") {
long x;
cin>>x;
q.push(x);
}
if (s == "POP" && !q.empty()) {
q.pop();
}
if (s == "PRINTFRONT") {
if (!q.empty())
cout<<q.front();
else
cout<<"NONE";
if (t > 0)
cout<<endl;
}
}
return 0;
}
|
Python
|
UTF-8
| 119
| 3.09375
| 3
|
[] |
no_license
|
v1 = 80
v2 = 70
distanceB = 490
distanceE = 150
minutes = 60 * (distanceB - distanceE) / (v1 + v2)
print(minutes)
|
PHP
|
UTF-8
| 798
| 3.53125
| 4
|
[] |
no_license
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test numbers</title>
</head>
<body>
<?php
echo '<form method="POST">
<label>Enter a number larger than 10</label><br>
<input type="number" name="num"><br><br>
<input type="submit" value="Submit"><br><br>
</form>';
if (empty($_POST['num'])) {
$num = '';
} else {
$num = $_POST['num'];
function test($n){
$r = $n > 30
? "greater than 30"
: ($n > 20
? "greater than 20"
: ($n >10
? "greater than 10"
: "Input a number greater than 10!"));
echo $n." : ".$r.'<br>';
}
test($num);
}
?>
</body>
</html>
|
JavaScript
|
UTF-8
| 1,103
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
const { readdirSync } = require("fs");
const ascii = require("ascii-table");
const table = new ascii("Commands").setHeading("Command", "Load status"); // create the table
module.exports = (client) => {
readdirSync("./commands/").forEach((dir) => {
readdirSync(`./commands/${dir}/`).forEach((file) => {
if (!file.endsWith(".js")) return; // filter the file
const command = require(`../commands/${dir}/${file}`); // load command from file
// filter invalid command
if (!command.name)
return table.addRow(
file,
"FAIL -> Missing a command.name, or command.name is not a string."
);
// set command to bot
client.commands.set(command.name, command);
// set command aliases
if (command.aliases && Array.isArray(command.aliases))
command.aliases.forEach((alias) =>
client.aliases.set(alias, command.name)
);
table.addRow(file, "OK");
});
});
console.log(table.toString()); // write the table to console, idk why i comment this thing lol
};
|
Python
|
UTF-8
| 117
| 2.71875
| 3
|
[] |
no_license
|
# Change the amount of text printed in cells in Pandas with .head() method
pd.set_option('display.max_colwidth', -1)
|
Python
|
UTF-8
| 353
| 2.9375
| 3
|
[] |
no_license
|
def quick(args):
if not args:
return []
small_list = []
big_list = []
middle = args[0]
for i in args[1:]:
if i <= middle:
small_list.append(i)
else:
big_list.append(i)
return quick(small_list) + [middle] + quick(big_list)
args = [2, 4, 1, 7, 2, 1, 6, 3]
print quick(args)[-2]
|
Python
|
UTF-8
| 4,707
| 2.59375
| 3
|
[] |
no_license
|
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
import dash_leaflet as dl
import dash_leaflet.express as dlx
from dash.dependencies import Input, Output, State
# Generate some in-memory data.
locations = [dict(lat=50.064840, lon=14.442720), dict(lat=50.082525, lon=14.451692), dict(lat=50.075539, lon=14.437800)]
Prague1 = dlx.dicts_to_geojson(locations)
app = dash.Dash(
__name__,
external_stylesheets=[dbc.themes.BOOTSTRAP]
)
# For Heroku deployment.
server = app.server
df_spending = pd.DataFrame({
"Day": ["Mo", "Tue", "We", "Tu", "Fr", "Sa", "So"],
"Amount": [300, 500, 0, 600, 200, 0, 400],
})
df_status = pd.DataFrame(
{
"Parameter": ["Points", "Level", "Number of visits"],
"Value": ["5000", "3", "20"],
}
)
df_ranking = pd.DataFrame(
{
"Place": [x for x in range(1,5)],
"Username": ["chrisO", "DavidP", "JosefH", "PeterK"],
"Level": ["5", "8", "20", "7"],
"Points": ["5000", "8000", "20000", "7000"],
}
)
fig_spending = px.bar(df_spending, x="Day", y="Amount", title="Purchases last week")
fig_spending.update_layout({
"plot_bgcolor": "rgba(0, 0, 0, 0)",
"paper_bgcolor": "rgba(0, 0, 0, 0)",
})
regionalRanking = dbc.Table.from_dataframe(df_ranking, striped=True, bordered=True, hover=True)
friendsRanking = dbc.Table.from_dataframe(df_ranking, striped=True, bordered=True, hover=True)
app.layout = html.Div([
dbc.Nav(
[
dbc.NavbarBrand(html.H3("Local Heroes"), className="ml-2"),
dbc.NavLink("Dashboard", href="#"),
dbc.NavLink("Sign-Up as Customer", href="#"),
dbc.NavLink("Sign-Up as Owner", href="#"),
dbc.NavLink("Login", href="#"),
dbc.NavLink("Invite Friends", href="#"),
], className= 'navbar navbar-expand-lg navbar-light bg-light fixed-top'
),
# Row: Title
# html.Div([
# dbc.Input(id='inputLocation', type="text", className="col-4"),
# dbc.Button("Primary", color="primary", className="mr-1 mt-2")
# ], className="pt-5"),
# Row: Map + Bar Chart
html.Div([
# Column: Map
html.Div([
html.H5("Map of local stores and restaurants"),
dl.Map(center=[50.064840, 14.442720], zoom=13, children=[
dl.TileLayer(),
dl.GeoJSON(data=Prague1),
# in-memory geojson (slowest option)
], style={'width': '100%', 'height': '35vh', 'margin': "auto", "display": "block"}, id="map"),
html.Div(id="stores")
], className="col-md-4"),
# Column: Bar Chart
html.Div([
html.H5("Statistics"),
dbc.Table.from_dataframe(df_status, striped=True, bordered=True, hover=True)
], className="col-md-4"),
html.Div([
html.H5("Messages from store owners"),
html.Article([
html.Article([
html.P("Hey everone, today I am offering your a special thing bla bla bla")
],className="each_message2"),
html.Article([
html.P("Lorem ipsum dolor sit amet consectetur adipisicing elit. Commodi,")
],className="each_message1"),
html.Article([
html.P("At placeat explicabo temporibus eius est tenetur? Maiores impedit")
],className="each_message2"),
html.Article([
html.P("Hello, we are open today until 10 pm. Stop by and try our new ...")
],className="each_message1")
],className="message_section")
], className="col-md-4")
], className="row my-5"),
# Row: Line Chart + Donut Chart
html.Div([
# Column: Line Chart
html.Div([
html.H5("Rewards"),
dbc.ListGroup([
dbc.ListGroupItem("20% discount at Rob's Pizza"),
dbc.ListGroupItem("Next beer for free at BeerGeek"),
dbc.ListGroupItem("Free coffee at MyBackery"),
])], className="col-md-4"),
html.Div([
dcc.Graph(id="spending", figure=fig_spending)
], className="col-md-4"),
html.Div([
html.H5("Ranking"),
dbc.Tabs(
[
dbc.Tab(regionalRanking, label="Friends"),
dbc.Tab(friendsRanking, label="People Around Me")
]
)
], className="col-md-4")
], className="row mt-5"),
], className="container-fluid pt-5")
if __name__ == '__main__':
app.run_server(debug=True)
|
C#
|
UTF-8
| 1,352
| 3.40625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
namespace Collections
{
class Program
{
static void Main(string[] args)
{
// int[] arr = {0,1,2,3,4,5,6,7,8,9,};
string[] names = new string[] {"Tim", "Martin", "Nikki", "Sara"};
// bool[] trueFalse = new bool[10] {true, false, true, false, true, false, true, false, true, false};
List<string> flavors = new List<string>();
flavors.Add("Vanilla");
flavors.Add("Chocolate");
flavors.Add("Banana");
flavors.Add("Strawberry");
flavors.Add("Mint");
// Console.WriteLine(flavors.Count);
// Console.WriteLine(flavors[2]);
// flavors.Remove("Banana");
// Console.WriteLine(flavors.Count);
Dictionary<string,string> profile = new Dictionary<string,string>();
Random rand = new Random();
foreach(string name in names)
{
profile.Add(name, flavors[rand.Next(flavors.Count)]);
}
foreach(var entry in profile)
{
Console.WriteLine(entry.Key + " - " + entry.Value);
}
}
}
}
|
PHP
|
UTF-8
| 839
| 2.890625
| 3
|
[] |
no_license
|
<?php
//
function unlinkr($dir, $pattern = "*") {
// find all files and folders matching pattern
$files = glob($dir . "/$pattern");
foreach($files as $file){
// if it's a directory, delete files inside it
if (is_dir($file) and !in_array($file, array('..', '.'))) {
unlinkr($file, $pattern);
rmdir($file);
} else if(
is_file($file) and
($file != __FILE__) and // make sure you don't delete the current script
($file != $dir."/extract.php") and
($file != $dir."/public.zip") and
($file != $dir."/cleanup.php")) {
unlink($file);
}
}
}
// current working directory
$dir = getcwd();
unlinkr($dir);
?>
|
PHP
|
UTF-8
| 294
| 2.53125
| 3
|
[] |
no_license
|
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
interface Response {
public function setStatus($status);
public function addHeader($name, $value);
public function write($data);
public function flush();
}
?>
|
Java
|
UTF-8
| 1,871
| 2.546875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
package qcri.dafna.dataModel.dataSetReader;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.NoSuchElementException;
import java.util.Scanner;
import qcri.dafna.dataModel.data.Globals;
import qcri.dafna.dataModel.quality.dataQuality.DataItemMeasures;
public class SyntheticDataSetTruthReader extends TruthReader {
/*
* File format
* object Id \t propertyNAme \t value
*/
public SyntheticDataSetTruthReader(HashMap<String, DataItemMeasures> dataItemMeasures) {
super(dataItemMeasures);
}
public int readDirectoryFiles(String directory) {
trueValueCount = 0;
try {
DirectoryStream<Path> directoryStream;
directoryStream = Files.newDirectoryStream(Paths.get(directory));
for (Path readFilePath : directoryStream) {
processFileLines(readFilePath, "null");
}
directoryStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return trueValueCount;
}
private void processFileLines(Path filePath, String timeStamp) {
try (Scanner scanner = new Scanner(filePath, Globals.Flight_DataSet_FILE_ENCODING.name())) {
while (scanner.hasNextLine()) {
processLine(scanner.nextLine(), timeStamp);
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void processLine(String fileLine, String timeStamp) {
// line format:
// object Id \t propertyNAme \t value
Scanner scanner = new Scanner(fileLine);
scanner.useDelimiter("\t");
try {
String objectID = scanner.next();
String propertyName = scanner.next();
String value = scanner.next();
addTrueValue("", objectID, propertyName, value);
} catch (NoSuchElementException e) {
System.out.println("Wrong Line Format : " + fileLine + " . ");
}
scanner.close();
}
}
|
TypeScript
|
UTF-8
| 2,601
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import React from "react";
import { CheckboxGroupProps } from "antd/lib/checkbox";
import { QueryObserverResult, UseQueryOptions } from "react-query";
import { useList } from "@hooks";
import {
CrudSorting,
Option,
BaseRecord,
GetListResponse,
CrudFilters,
SuccessErrorNotification,
HttpError,
MetaDataQuery,
} from "../../../interfaces";
export type useCheckboxGroupProps<TData, TError> = {
resource: string;
optionLabel?: string;
optionValue?: string;
sort?: CrudSorting;
filters?: CrudFilters;
queryOptions?: UseQueryOptions<GetListResponse<TData>, TError>;
metaData?: MetaDataQuery;
} & SuccessErrorNotification;
export type UseCheckboxGroupReturnType<TData extends BaseRecord = BaseRecord> =
{
checkboxGroupProps: CheckboxGroupProps;
queryResult: QueryObserverResult<GetListResponse<TData>>;
};
/**
* `useCheckboxGroup` hook allows you to manage an Ant Design {@link https://ant.design/components/checkbox/#components-checkbox-demo-group Checkbox.Group} component when records in a resource needs to be used as checkbox options.
*
* @see {@link https://refine.dev/docs/api-references/hooks/field/useCheckboxGroup} for more details.
*
* @typeParam TData - Result data of the query extends {@link https://refine.dev/docs/api-references/interfaceReferences#baserecord `BaseRecord`}
*
*/
export const useCheckboxGroup = <
TData extends BaseRecord = BaseRecord,
TError extends HttpError = HttpError,
>({
resource,
sort,
filters,
optionLabel = "title",
optionValue = "id",
successNotification,
errorNotification,
queryOptions,
metaData,
}: useCheckboxGroupProps<TData, TError>): UseCheckboxGroupReturnType<TData> => {
const [options, setOptions] = React.useState<Option[]>([]);
const defaultQueryOnSuccess = (data: GetListResponse<TData>) => {
setOptions(
data.data.map((item) => ({
label: item[optionLabel],
value: item[optionValue],
})),
);
};
const queryResult = useList<TData, TError>({
resource,
config: {
sort,
filters,
},
queryOptions: {
...queryOptions,
onSuccess: (data) => {
defaultQueryOnSuccess(data);
queryOptions?.onSuccess?.(data);
},
},
successNotification,
errorNotification,
metaData,
});
return {
checkboxGroupProps: {
options,
},
queryResult,
};
};
|
Markdown
|
UTF-8
| 1,615
| 2.796875
| 3
|
[] |
no_license
|
# Lending Club

A loan prediction tool based on a machine learning model using lending club data inspired by a [Kaggle notebook](https://www.kaggle.com/pavlofesenko/minimizing-risks-for-loan-investments/notebook)
Skeleton using fast-api and docker inspired by [Testdriven.io course](https://testdriven.io/courses/tdd-fastapi/) and [this fastapi/ml template](https://github.com/eightBEC/fastapi-ml-skeleton).
## Requirements
Python 3.6+
## Installation
Install the required packages in your local environment (ideally virtualenv, conda, etc.).
```bash
pip install -r requirements
```
## Setup
1. Duplicate the `.env.example` file and rename it to `.env`
2. In the `.env` file configure the `API_KEY` entry. The key is used for authenticating our API. <br>
A sample API key can be generated using Python REPL:
```python
import uuid
print(str(uuid.uuid4()))
```
## Run It
1. Start your app with:
```bash
uvicorn app.main:app
```
2. Go to [http://localhost:8000/docs](http://localhost:8000/docs).
3. Click `Authorize` and enter the API key as created in the Setup step.

4. You can use the sample payload from the `docs/loan_payload.json` file when trying out the model using the API.
## Run Tests
If you're not using `tox`, please install with:
```bash
pip install tox
```
Run your tests with:
```bash
tox
```
This runs tests and coverage for Python 3.6 and Flake8, Autopep8, Bandit.
|
Java
|
UTF-8
| 321
| 3.125
| 3
|
[] |
no_license
|
package org.selva.recursion;
public class WorkSheet {
public static void main(String[] args) {
String s = "fog";
stringReverse(s);
}
static void stringReverse(String s){
if(s.length() >0) {
stringReverse(s.substring(1));
System.out.print(s.substring(0, 1));
}
}
}
|
Java
|
UTF-8
| 627
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.springframework.format.datetime.joda;
import java.text.ParseException;
import java.util.Locale;
import org.joda.time.Period;
import org.springframework.format.Formatter;
/**
* {@link Formatter} implementation for a Joda-Time {@link Period},
* following Joda-Time's parsing rules for a Period.
*
* @since 4.2.4
* @see Period#parse
*/
class PeriodFormatter implements Formatter<Period> {
@Override
public Period parse(String text, Locale locale) throws ParseException {
return Period.parse(text);
}
@Override
public String print(Period object, Locale locale) {
return object.toString();
}
}
|
Markdown
|
UTF-8
| 2,455
| 2.796875
| 3
|
[] |
no_license
|
## Go 语言常用包学习
#### 一、sync包
##### (一)waitgroup
- WaitGroup用于等待一组线程的结束。父线程调用Add方法来设定应等待的线程的数量。每个被等待的线程在结束时应调用Done方法。同时,主线程里可以调用Wait方法阻塞至所有线程的结束。
例如:
```go
func main() {
var wg sync.WaitGroup
for i := 0; i <= 10; i++ {
// increment the WaitGroup counter
wg.Add(1)
go func(i int) {
// decrement the counter when the goroutine completes
defer wg.Done()
fmt.Println(i)
}(i)
}
// wait for all go func to complete
wg.Wait()
}
```
1. `func (wg *WaitGroup) Add(delta int)`
- Add方法向内部计数加上delta,delta可以是负数;如果内部计数器变为0,Wait方法阻塞等待的所有线程都会释放,如果计数器小于0,方法panic。注意Add加上正数的调用应在Wait之前,否则Wait可能只会等待很少的线程。一般来说本方法应在创建新的线程或者其他应等待的事件之前调用。
2. `func (wg *WaitGroup) Done()`
- Done方法减少WaitGroup计数器的值,应在线程的最后执行。
3. `func (wg *WaitGroup) Wait()`
- Wait方法阻塞直到WaitGroup计数器减为0。
##### (二)Once
- Once 是只执行一次动作的对象
- 例如:
```go
func main() {
var once sync.Once
onceBody := func() {
fmt.Println("Only once")
}
done := make(chan bool)
for i := 0; i < 10; i++ {
go func() {
once.Do(onceBody)
done <- true
}()
}
for i := 0; i < 10; i++ {
<-done
}
}
// 运行结果
Only once
```
1. `func (o *Once) Do(f func())`
Do 方法当且仅当第一次调用是才会执行函数f。
Do 用于必须刚好运行一次的初始化。因为f没有参数的,因为可能需要使用闭包来提供给Do方法调用:
```go
config.once.Do(func(){ config.init(filename)})
```
因为只有f返回后Do方法才会返回,f若引起了Do的调用,会导致死锁
##### 二、sync/atomic
#### 二、sync/atomic
#### 三、context
#### 四、strconv
#### 五、time
#### 六、strings
#### 七、bufio
#### 八、os
#### 九、json
#### 十 、flag
#### 十一、io
#### 十二、math
#### 十三、net
#### 十四、reflect
#### 十五、regexp
#### 十六、encoding
#### 十七、
|
Java
|
UTF-8
| 12,202
| 1.664063
| 2
|
[] |
no_license
|
/**
* NetXMS - open source network management system
* Copyright (C) 2003-2013 Victor Kirhenshtein
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.netxms.ui.eclipse.dashboard.propertypages;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.dialogs.PropertyPage;
import org.netxms.client.datacollection.ChartDciConfig;
import org.netxms.client.datacollection.DciValue;
import org.netxms.ui.eclipse.dashboard.Messages;
import org.netxms.ui.eclipse.dashboard.propertypages.helpers.DciListLabelProvider;
import org.netxms.ui.eclipse.dashboard.widgets.internal.AbstractChartConfig;
import org.netxms.ui.eclipse.datacollection.dialogs.DataSourceEditDlg;
import org.netxms.ui.eclipse.datacollection.dialogs.SelectDciDialog;
import org.netxms.ui.eclipse.tools.ColorCache;
import org.netxms.ui.eclipse.tools.ColorConverter;
import org.netxms.ui.eclipse.tools.WidgetHelper;
import org.netxms.ui.eclipse.widgets.SortableTableViewer;
/**
* DCI list editor for dashboard element
*/
public class DataSources extends PropertyPage {
public static final int COLUMN_POSITION = 0;
public static final int COLUMN_NODE = 1;
public static final int COLUMN_METRIC = 2;
public static final int COLUMN_LABEL = 3;
public static final int COLUMN_COLOR = 4;
private AbstractChartConfig config;
private DciListLabelProvider labelProvider;
private SortableTableViewer viewer;
private Button addButton;
private Button editButton;
private Button deleteButton;
private Button upButton;
private Button downButton;
private List<ChartDciConfig> dciList = null;
private ColorCache colorCache;
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse
* .swt.widgets.Composite)
*/
@Override
protected Control createContents(Composite parent) {
config = (AbstractChartConfig) getElement().getAdapter(
AbstractChartConfig.class);
Composite dialogArea = new Composite(parent, SWT.NONE);
colorCache = new ColorCache(dialogArea);
dciList = new ArrayList<ChartDciConfig>();
for (ChartDciConfig dci : config.getDciList())
dciList.add(new ChartDciConfig(dci));
labelProvider = new DciListLabelProvider(dciList);
labelProvider.resolveDciNames(dciList);
GridLayout layout = new GridLayout();
layout.verticalSpacing = WidgetHelper.OUTER_SPACING;
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.numColumns = 2;
dialogArea.setLayout(layout);
final String[] columnNames = { Messages.get().DataSources_Pos,
Messages.get().DataSources_Node,
Messages.get().DataSources_Parameter,
Messages.get().DataSources_Label,
Messages.get().DataSources_Color };
final int[] columnWidths = { 40, 130, 200, 150, 50 };
viewer = new SortableTableViewer(dialogArea, columnNames, columnWidths,
0, SWT.UP, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
viewer.setContentProvider(new ArrayContentProvider());
viewer.setLabelProvider(labelProvider);
viewer.disableSorting();
viewer.getTable().addListener(SWT.PaintItem, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.index == COLUMN_COLOR)
drawColorCell(event);
}
});
viewer.setInput(dciList.toArray());
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.heightHint = 0;
gridData.horizontalSpan = 2;
viewer.getControl().setLayoutData(gridData);
/* buttons on left side */
Composite leftButtons = new Composite(dialogArea, SWT.NONE);
RowLayout buttonLayout = new RowLayout();
buttonLayout.type = SWT.HORIZONTAL;
buttonLayout.pack = false;
buttonLayout.marginWidth = 0;
buttonLayout.marginLeft = 0;
leftButtons.setLayout(buttonLayout);
gridData = new GridData();
gridData.horizontalAlignment = SWT.LEFT;
leftButtons.setLayoutData(gridData);
upButton = new Button(leftButtons, SWT.PUSH);
upButton.setText(Messages.get().DataSources_Up);
RowData rd = new RowData();
rd.width = WidgetHelper.BUTTON_WIDTH_HINT;
upButton.setLayoutData(rd);
upButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
public void widgetSelected(SelectionEvent e) {
moveUp();
}
});
upButton.setEnabled(false);
downButton = new Button(leftButtons, SWT.PUSH);
downButton.setText(Messages.get().DataSources_Down);
rd = new RowData();
rd.width = WidgetHelper.BUTTON_WIDTH_HINT;
downButton.setLayoutData(rd);
downButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
public void widgetSelected(SelectionEvent e) {
moveDown();
}
});
downButton.setEnabled(false);
/* buttons on right side */
Composite rightButtons = new Composite(dialogArea, SWT.NONE);
buttonLayout = new RowLayout();
buttonLayout.type = SWT.HORIZONTAL;
buttonLayout.pack = false;
buttonLayout.marginWidth = 0;
buttonLayout.marginRight = 0;
rightButtons.setLayout(buttonLayout);
gridData = new GridData();
gridData.horizontalAlignment = SWT.RIGHT;
rightButtons.setLayoutData(gridData);
addButton = new Button(rightButtons, SWT.PUSH);
addButton.setText(Messages.get().DataSources_Add);
rd = new RowData();
rd.width = WidgetHelper.BUTTON_WIDTH_HINT;
addButton.setLayoutData(rd);
addButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
public void widgetSelected(SelectionEvent e) {
addItem();
}
});
editButton = new Button(rightButtons, SWT.PUSH);
editButton.setText(Messages.get().DataSources_Modify);
rd = new RowData();
rd.width = WidgetHelper.BUTTON_WIDTH_HINT;
editButton.setLayoutData(rd);
editButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
public void widgetSelected(SelectionEvent e) {
editItem();
}
});
editButton.setEnabled(false);
deleteButton = new Button(rightButtons, SWT.PUSH);
deleteButton.setText(Messages.get().DataSources_Delete);
rd = new RowData();
rd.width = WidgetHelper.BUTTON_WIDTH_HINT;
deleteButton.setLayoutData(rd);
deleteButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
@Override
public void widgetSelected(SelectionEvent e) {
deleteItems();
}
});
deleteButton.setEnabled(false);
viewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
editButton.notifyListeners(SWT.Selection, new Event());
}
});
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) viewer
.getSelection();
editButton.setEnabled(selection.size() == 1);
deleteButton.setEnabled(selection.size() > 0);
upButton.setEnabled(selection.size() == 1);
downButton.setEnabled(selection.size() == 1);
}
});
return dialogArea;
}
/**
* @param event
*/
private void drawColorCell(Event event) {
TableItem item = (TableItem) event.item;
ChartDciConfig dci = (ChartDciConfig) item.getData();
if (dci.color.equalsIgnoreCase(ChartDciConfig.UNSET_COLOR))
return;
int width = viewer.getTable().getColumn(COLUMN_COLOR).getWidth();
Color color = ColorConverter.colorFromInt(dci.getColorAsInt(),
colorCache);
event.gc.setForeground(colorCache.create(0, 0, 0));
event.gc.setBackground(color);
event.gc.setLineWidth(1);
event.gc.fillRectangle(event.x + 3, event.y + 2, width - 7,
event.height - 5);
event.gc.drawRectangle(event.x + 3, event.y + 2, width - 7,
event.height - 5);
}
/**
* Add new item
*/
private void addItem() {
SelectDciDialog dlg = new SelectDciDialog(getShell(), 0);
if (dlg.open() == Window.OK) {
List<DciValue> selection = dlg.getSelection();
List<ChartDciConfig> select = new ArrayList<ChartDciConfig>();
for (DciValue item : selection) {
ChartDciConfig dci = new ChartDciConfig(item);
select.add(dci);
labelProvider.addCacheEntry(dci.nodeId, dci.dciId, dci.name);
dciList.add(dci);
}
viewer.setInput(dciList.toArray());
viewer.setSelection(new StructuredSelection(select));
}
}
/**
* Edit selected item
*/
private void editItem() {
IStructuredSelection selection = (IStructuredSelection) viewer
.getSelection();
ChartDciConfig dci = (ChartDciConfig) selection.getFirstElement();
if (dci == null)
return;
DataSourceEditDlg dlg = new DataSourceEditDlg(getShell(), dci, false);
if (dlg.open() == Window.OK) {
viewer.update(dci, null);
}
}
/**
* Delete selected item(s)
*/
private void deleteItems() {
IStructuredSelection selection = (IStructuredSelection) viewer
.getSelection();
for (Object o : selection.toList())
dciList.remove(o);
viewer.setInput(dciList.toArray());
}
/**
* Move selected item up
*/
private void moveUp() {
final IStructuredSelection selection = (IStructuredSelection) viewer
.getSelection();
if (selection.size() == 1) {
Object element = selection.getFirstElement();
int index = dciList.indexOf(element);
if (index > 0) {
Collections.swap(dciList, index - 1, index);
viewer.setInput(dciList.toArray());
viewer.setSelection(new StructuredSelection(element));
}
}
}
/**
* Move selected item down
*/
private void moveDown() {
final IStructuredSelection selection = (IStructuredSelection) viewer
.getSelection();
if (selection.size() == 1) {
Object element = selection.getFirstElement();
int index = dciList.indexOf(element);
if ((index < dciList.size() - 1) && (index >= 0)) {
Collections.swap(dciList, index + 1, index);
viewer.setInput(dciList.toArray());
viewer.setSelection(new StructuredSelection(element));
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.preference.PreferencePage#performOk()
*/
@Override
public boolean performOk() {
config.setDciList(dciList.toArray(new ChartDciConfig[dciList.size()]));
return true;
}
}
|
C++
|
UTF-8
| 2,697
| 2.71875
| 3
|
[] |
no_license
|
#include "Volume.h"
#include <GraphicsLibrary/TexPart.h>
#include "ClassContainer.h"
Volume::Volume()
{
level = 3;
btnUp = NULL;
btnDown = NULL;
for (unsigned i = 0; i < 5; i++)
imgLevel[i] = NULL;
}
Volume *Volume::Create()
{
ClassContainer *cc = ClassContainer::GetInstance();
Volume *ret = new Volume();
if (ret != NULL)
{
ret ->x = 0;
ret ->y = 0;
ret ->width = 0; // set layter!
ret ->height = 0;
TexPart tpVolIcon[5];
TexPart tpPlus = cc->GetClass<TexPart>("guimap_opt_plus");
TexPart tpPlusDown = cc->GetClass<TexPart>("guimap_opt_plus_down");
TexPart tpMinus = cc->GetClass<TexPart>("guimap_opt_minus");
TexPart tpMinusDown = cc->GetClass<TexPart>("guimap_opt_minus_down");
tpVolIcon[0] = cc->GetClass<TexPart>("guimap_opt_volume_1");
tpVolIcon[1] = cc->GetClass<TexPart>("guimap_opt_volume_2");
tpVolIcon[2] = cc->GetClass<TexPart>("guimap_opt_volume_3");
tpVolIcon[3] = cc->GetClass<TexPart>("guimap_opt_volume_4");
tpVolIcon[4] = cc->GetClass<TexPart>("guimap_opt_volume_5");
unsigned xShift = 0;
ret->btnDown = new AnimButton(xShift,
(tpVolIcon[4].ImageRect.Height - tpMinus.ImageRect.Height) / 2 + 5,
tpMinus,
tpMinusDown);
xShift += tpPlus.ImageRect.Width;
for (unsigned i = 0; i < 5; i++)
{
ret->imgLevel[i] = new Control(xShift,
0,
tpVolIcon[i]);
xShift += ((unsigned)(float)tpVolIcon[i].ImageRect.Width * 0.85f);
ret->AddChild(ret->imgLevel[i]);
}
xShift += 10;
ret->btnUp = new AnimButton(xShift,
(tpVolIcon[4].ImageRect.Height - tpPlus.ImageRect.Height) / 2 + 5,
tpPlus,
tpPlusDown);
xShift += tpMinus.ImageRect.Width;
ret->width = xShift;
ret->height = tpVolIcon[4].ImageRect.Height;
ret ->AddChild(ret->btnUp);
ret ->AddChild(ret->btnDown);
ObsCast(ITouchObserver, ret ->btnUp) ->AddObserver(ret);
ObsCast(ITouchObserver, ret ->btnDown) ->AddObserver(ret);
ret->SetLevel(ret->level);
}
return ret;
}
void Volume::TouchPressed(Control *control, int x, int y)
{
if (control == btnUp)
{
SetLevel(fminf(level + 1, 5));
ObsCast(IPropertyObserver, this)->NotifyObservers(&IPropertyObserver::PropertyChanged, "u", this);
}
else if (control == btnDown)
{
SetLevel(fmaxf((int)level - 1, 0));
ObsCast(IPropertyObserver, this)->NotifyObservers(&IPropertyObserver::PropertyChanged, "d", this);
}
}
void Volume::SetLevel(unsigned level)
{
this->level = level;
for (unsigned i = 0; i < 5; i++)
if ((int)i <= (int)level - 1)
imgLevel[i]->SetOpacity(0.9f);
else
imgLevel[i]->SetOpacity(0.4f);
}
unsigned Volume::GetLevel() const
{
return level;
}
|
TypeScript
|
UTF-8
| 324
| 2.703125
| 3
|
[] |
no_license
|
import { Address } from "./types";
export interface Allocator<Data> {
getData(addr: Address, size: number): Data;
setData(addr: Address, data: Data, size: number): void;
memAlloc(size: number): Address | null;
memRealloc(addr: Address, size: number): Address | null;
memFree(addr: Address): void;
}
|
C++
|
UTF-8
| 1,199
| 2.78125
| 3
|
[] |
no_license
|
#include <queue>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
int target_int = stoi(target);
bool visited[10000] = {false};
for (auto dd : deadends) {
visited[stoi(dd)] = true;
}
queue<int> bfs;
bfs.push(0);
int shortest_length = 0;
while (!bfs.empty())
{
size_t bfs_size = bfs.size();
for (size_t i = 0; i < bfs_size; ++i)
{
int cur_pt = bfs.front(); bfs.pop();
if (cur_pt == target_int) {
return shortest_length;
}
if (visited[cur_pt]) continue;
visited[cur_pt] = true;
for (int mask = 1; mask <= 1000; mask *= 10)
{
for (int diff = 1; diff <= 9; diff += 8) {
int next = (cur_pt + ((cur_pt/mask + diff) % 10 - (cur_pt/mask) % 10) * mask);
bfs.push(next);
}
}
}
++shortest_length;
}
return -1;
}
};
|
JavaScript
|
UTF-8
| 697
| 3.109375
| 3
|
[] |
no_license
|
// in the 01_simplest_webServer we didn't used any file, so in this section we read a html file and show it on the web page
const http = require('http');
const fs = require('fs'); // for read file
const hostname = '127.0.0.1';
const port = 3000;
fs.readFile('index.html', (err, html) =>{
if (err){
throw err;
}
// else
const server = http.createServer((req, res)=> {
res.statusCode = 200;
res.setHeader('Content-type', 'text/html'); // be aware of put text/html for translate html to the text in web page
res.write(html);
res.end();
});
server.listen(port, hostname, () => {
console.log("Server started on port "+ port);
});
});
|
Markdown
|
UTF-8
| 4,067
| 3.125
| 3
|
[] |
no_license
|
# ScrollMonitor-React
This is a React component that provides an API to the [scrollMonitor](https://github.com/stutrek/scrollMonitor).
It can call methods when a watched element enters or exits the viewport and adds `isInViewport`, `isAboveViewport`, `isBelowViewport`, and `isFullyInViewport` to `this.props`.
## Usage
Include it in your project
```
npm install scrollmonitor-react
```
Then use it to wrap your own component.
```javascript
import React from 'react';
import { Watch, ScrollContainer } from 'scrollmonitor-react';
export default Watch(class MyComponent extends React.Component {
// This part is optional, see Locking on the scrollMonitor's readme.
componentWillReceiveProps (props) {
if (props.watcherShouldLock) {
this.props.lockWatcher();
} else {
this.props.unlockWatcher();
}
}
render () {
var text;
if (this.props.isInViewport) {
text = 'I AM in the viewport!';
} else {
text = 'You will never see this because it gets replaced when it enters the viewport.'
}
return (<span>{text}</span>);
}
});
```
You can also pass methods with the scrollMonitor event names as props to your component.
```javascript
import React from 'react';
import MyComponent from './the/example/above';
export default MyParentComponent extends React.Component {
receiveStateChange (watcher) {
console.log('state changed!', watcher)
}
render () {
return (<MyComponent stateChange={this.receiveStateChange} />)
}
}
```
If you have a scroll container, use the scroll container component.
```javascript
import React from 'react';
import { render } from 'react-dom';
import { ScrollContainer, Watch } from 'scrollmonitor-react/index';
// Your component works just like it does above
class Box extends React.Component {
render () {
var style = {}
if (this.props.isAboveViewport) {
style.backgroundColor = '#ffc';
} else if (this.props.isBelowViewport) {
style.backgroundColor = '#ccf';
}
return (<span className="box" style={style}>{this.props.children}</span>);
}
}
var WatchedBox = Watch(Box);
// Your container gets this.props.scrollContainer, which it must pass to the child components.
var Container = ScrollContainer(ContainerComponent extends React.Component {
render () {
i = 1;
return (<div className="container-scroll">
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
<WatchedBox scrollContainer={this.props.scrollContainer}>{i++}</WatchedBox>
</div>);
}
}
```
|
Java
|
UTF-8
| 583
| 2.234375
| 2
|
[] |
no_license
|
package hibernateTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.man.spring.hibernate.entity.User;
import com.man.spring.hibernate.service.UserService;
public class hibernateTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("application-config.xml");
UserService us=(UserService) context.getBean("userService");
User user=new User();
user.setName("xiaoxiao");
user.setAge(25);
us.addUser(user);
}
}
|
Java
|
UTF-8
| 8,078
| 2.78125
| 3
|
[] |
no_license
|
package com.yubin.homework.utils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import java.sql.*;
/**
* @program: homework
* @description:测试100万数据不同方式插入效率
* @author: Yu Bin
* @create: 2021-06-20 13:35
**/
@Slf4j
public class TestJdbcUtil {
//创建一些静态成员变量,用来存储数据库的连接信息
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/geek?rewriteBatchedStatements=true";
private static String user = "root";
private static String password = "12345678";
static {
//1.注册驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
log.error("load mysql driver error", e);
}
}
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new RuntimeException("数据库连接异常" + e);
}
return conn;
}
/**
* 释放资源
*
* @param conn
* @param stat
* @param rs
*/
public static void close(Connection conn, Statement stat, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.error("ResultSet close error", e);
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
log.error("Statement close error", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.error("Connection close error", e);
}
}
}
/**
* 释放资源
*
* @param conn
* @param pstat
* @param rs
*/
public static void close(Connection conn, PreparedStatement pstat, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.error("ResultSet close error", e);
}
}
if (pstat != null) {
try {
pstat.close();
} catch (SQLException e) {
log.error("Statement close error", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.error("Connection close error", e);
}
}
}
public static void normalInsert() {
//获取连接
Connection conn = getConnection();
//获取执行sql语句的执行者对象Statement
PreparedStatement pstm = null;
try {
String sql = "INSERT INTO geek.order_info" +
"(user_id, order_number, order_time, receive_name, receive_mobile, receive_address, order_status, deleted, add_time, add_user_id, update_user_id, update_time)" +
"VALUES(?, ?, ?, '', '', '', 0, 0, now(), ?, ?, now());";
pstm = conn.prepareStatement(sql);
long start = System.currentTimeMillis();
for (int i = 1; i <= 1000000; i++) {
pstm.setLong(1, i % 10000);
pstm.setString(2, "202106" + String.format("%07d", i));
pstm.setString(3, DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
pstm.setLong(4, i % 10000);
pstm.setLong(5, i % 10000);
pstm.executeUpdate();
}
log.info("cost:{}", (System.currentTimeMillis() - start));
} catch (SQLException e) {
log.error("normalInsert SQLException error", e);
} finally {
close(conn, pstm, null);
}
}
public static void batchInsert() {
//获取连接
Connection conn = getConnection();
//获取执行sql语句的执行者对象Statement
PreparedStatement pstm = null;
try {
String sql = "INSERT INTO geek.order_info" +
"(user_id, order_number, order_time, receive_name, receive_mobile, receive_address, order_status, deleted, add_time, add_user_id, update_user_id, update_time)" +
"VALUES(?, ?, ?,'', '', '', 0, 0, now(), ?, ?, now())";
pstm = conn.prepareStatement(sql);
long start = System.currentTimeMillis();
for (int i = 1; i <= 1000000; i++) {
pstm.setLong(1, i % 10000);
pstm.setString(2, "202106" + String.format("%07d", i));
pstm.setString(3, DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
pstm.setLong(4, i % 10000);
pstm.setLong(5, i % 10000);
pstm.addBatch();
}
pstm.executeBatch();
log.info("cost:{}", (System.currentTimeMillis() - start));
} catch (SQLException e) {
log.error("normalInsert SQLException error", e);
} finally {
close(conn, pstm, null);
}
}
public static void transactionInsert() {
//获取连接
Connection conn = getConnection();
//获取执行sql语句的执行者对象Statement
PreparedStatement pstm = null;
try {
String sql = "INSERT INTO geek.order_info" +
"(user_id, order_number, order_time, receive_name, receive_mobile, receive_address, order_status, deleted, add_time, add_user_id, update_user_id, update_time)" +
"VALUES(?, ?, ?, '', '', '', 0, 0, now(), ?, ?, now());";
pstm = conn.prepareStatement(sql);
conn.setAutoCommit(false);
long start = System.currentTimeMillis();
for (int i = 1; i <= 1000000; i++) {
pstm.setLong(1, i % 10000);
pstm.setString(2, "202106" + String.format("%07d", i));
pstm.setString(3, DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
pstm.setLong(4, i % 10000);
pstm.setLong(5, i % 10000);
pstm.executeUpdate();
}
conn.commit();
log.info("cost:{}", (System.currentTimeMillis() - start));
} catch (SQLException e) {
log.error("normalInsert SQLException error", e);
} finally {
close(conn, pstm, null);
}
}
public static void transactionBatchInsert() {
//获取连接
Connection conn = getConnection();
//获取执行sql语句的执行者对象Statement
PreparedStatement pstm = null;
try {
String sql = "INSERT INTO geek.order_info" +
"(user_id, order_number, order_time, receive_name, receive_mobile, receive_address, order_status, deleted, add_time, add_user_id, update_user_id, update_time)" +
"VALUES(?, ?, ?,'', '', '', 0, 0, now(), ?, ?, now())";
pstm = conn.prepareStatement(sql);
conn.setAutoCommit(false);
long start = System.currentTimeMillis();
for (int i = 1; i <= 1000000; i++) {
pstm.setLong(1, i % 10000);
pstm.setString(2, "202106" + String.format("%07d", i));
pstm.setString(3, DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
pstm.setLong(4, i % 10000);
pstm.setLong(5, i % 10000);
pstm.addBatch();
}
pstm.executeBatch();
conn.commit();
log.info("cost:{}", (System.currentTimeMillis() - start));
} catch (SQLException e) {
log.error("normalInsert SQLException error", e);
} finally {
close(conn, pstm, null);
}
}
public static void main(String[] args) {
transactionBatchInsert();
}
}
|
JavaScript
|
UTF-8
| 1,241
| 2.75
| 3
|
[] |
no_license
|
/* This retuns the Resource Element Category
* @Author Yattong Wu
* @version 1.0.0
* @date 16/04/19
* @param {string} categoryPath - The Cateogry path for Resource Element.
* @return {resourceElementCategory} The Resource Element Category Object.
*/
// Set Standard Logging
var objType = "Action";
var objName = "restCall"; // This must be set to the name of the action
var Logger = System.getModule("london.clouding.logging").standardisedLogger(objType,objName);
var log = new Logger(objType, objName);
// Start logging
log.debug("------ Starting " + objType + " : " + objName + " ------");
// check input params
if (!categorypath) {
throw "The resource element category path must be provided.";
}
// execute
try {
log.debug("Getting resource element category from path: " + categoryPath);
var resourceElementCategory = Server.getResourceElementCategoryWithPath(categoryPath);
if (resourceElementCategory) {
categoryName = resourceElementCategory.name;
log.debug("Found resource element category: " + categoryName);
} else {
throw "Resource element category was not found.";
}
} catch (e) {
log.debug("Failed to get resource element category from provided path.", e);
}
// return
return resourceElementCategory;
|
Go
|
UTF-8
| 587
| 2.703125
| 3
|
[] |
no_license
|
package main
import "fmt"
func main() {
var n, k int
var s string
fmt.Scan(&n, &k, &s)
ans := 0
for l, r := -1, 0; r < len(s); r++ {
for r < len(s) && s[r] == '1' {
r++
}
for k > 0 {
k--
for r < len(s) && s[r] == '0' {
if r > len(s)-1 {
break
}
r++
}
for r < len(s) && s[r] == '1' {
if r > len(s)-1 {
break
}
r++
}
}
r--
//fmt.Println(l, r)
if v := r - l; v > ans {
ans = v
}
k++
l++
for l < len(s) && s[l] == '1' {
l++
}
for l < len(s) && s[l] == '0' {
l++
}
l--
}
fmt.Println(ans)
}
|
C++
|
UTF-8
| 2,529
| 3.484375
| 3
|
[
"MIT"
] |
permissive
|
#include"alert.h"
#include<vector>
#include<string>
#include<iostream>
using namespace std;
System AlertSystem;
struct vital
{
string vital_id;
float minLimit;
float maxLimit;
};
struct vital_array
{
string string_id;
float val;
};
class VitalList
{
vector<vital> vital_list;
public:
void addVital(string string_id, float min, float max);
bool checkVital(string string_id, float val);
bool isOk(int string_index, float val);
int getIndex(string string_id);
int addVital(string string_id);
bool checkVital(vital_array vt_array[],int size);
};
void VitalList::addVital(string string_id, float min, float max)
{
vital_list.push_back({ string_id,min,max });
}
bool VitalList::checkVital(string string_id, float val)
{
int index = getIndex(string_id);
if (index != -1)
{
return isOk(index, val);
}
else
{
int index_of_added;
index_of_added =addVital(string_id);
return isOk(index_of_added, val);
}
}
bool VitalList::isOk(int string_index, float val)
{
//return(val >= vital_list[id].minLimit && val <= vital_list[id].maxLimit);
if (val < vital_list[string_index].minLimit)
{
string message="";
message = message + "Patients " + vital_list[string_index].vital_id + " is low:" + to_string(val);;
AlertSystem.alertNow(message);
return false;
}
else if (val > vital_list[string_index].maxLimit)
{
string message = "";
message = message + "Patients " + vital_list[string_index].vital_id + " is high:"+to_string(val);
AlertSystem.alertNow(message);
return false;
}
return true;
}
int VitalList::getIndex(string string_id)
{
int id = -1;
for (unsigned int i = 0; i < vital_list.size(); i++)
{
if (vital_list[i].vital_id == string_id)
{
id = i;
break;
}
}
return id;
}
int VitalList::addVital(string string_id)
{
float min, max;
cout << "Enter min limit of vital:enterd 100" << endl;
//cin >> min;
min = 100;
max = 200;
cout << "Enter max limit of vital:enterd 200" << endl;
//cin >> max;
vital_list.push_back({ string_id,min,max });
return (vital_list.size()-1);
}
bool VitalList::checkVital(vital_array vt_array[],int size)
{
bool result = true;
for (int i = 0; i < size; i++)
{
if (checkVital(vt_array[i].string_id, vt_array[i].val) == false)
result = false;
}
return result;
}
|
Java
|
UTF-8
| 13,029
| 2.265625
| 2
|
[] |
no_license
|
package com.operation.business;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import com.cx.base.BasePage;
import com.cx.util.ConnectMySQL;
import com.cx.util.Log;
import com.cx.util.Util;
import com.operation.elements.Element_ReAndLogin_Page;
/**
* 常规登录注册页面
* @author gavin
*
*/
public class ReAndLogin_Page extends BasePage {
Element_ReAndLogin_Page ecp = new Element_ReAndLogin_Page(this.driver);
public ReAndLogin_Page(WebDriver driver) {
super(driver);
}
public static String phone = "";
/**
* 常规登录
* @param homePageURL 主站url
* @param userNam 登录用户名
* @param pwd 登录密码
* @param loginInfo 登录成功后主站右上角用户信息
* @return 返回登录成功状态
*/
public boolean commonLogin(String homePageURL,String userNam,String pwd,String loginInfo) {
boolean flag = false;
this.goTo(homePageURL);
Util.sleep(2);
Log.stepInfo("点击弹窗关闭按钮");
ecp.closeBtn().click();
Util.sleep(1);
Log.stepInfo("点击登录链接");
ecp.loginBtn().click();
Util.sleep(4);
Log.stepInfo("输入用户名:"+userNam);
ecp.userName().click();
ecp.userName().sendKeys(userNam);
Log.stepInfo("输入密码:"+pwd);
ecp.passwd().click();
ecp.passwd().sendKeys(pwd);
Log.stepInfo("输入验证码:1111");
ecp.valid().click();
ecp.valid().sendKeys("1111");
Log.stepInfo("点击登录按钮");
ecp.loginApply().click();
Util.sleep(4);
try {
if(ecp.userInfo().getText().startsWith(loginInfo))
flag = true;
}catch(NoSuchElementException e) {
Log.logError("可能登录失败,请看日志!");
}
return flag;
}
/**
* 快速登录
* url:http://car.sit.com/product/1010001665.htm
*/
public boolean quickLogin(String quickUrl,String quickUsername,String quickPassword) {
boolean flag = false;
this.goTo(quickUrl);
Log.stepInfo("点击立即下定按钮");
ecp.orderNowBtn().click();
Util.sleep(2);
driver.switchTo().frame("inneriframe");
Log.stepInfo("输入用户名:"+quickUsername);
ecp.quickUsername().click();
ecp.quickUsername().sendKeys(quickUsername);
Log.stepInfo("输入密码:"+quickPassword);
ecp.quickPassword().click();
ecp.quickPassword().sendKeys(quickPassword);
Log.stepInfo("点击登录按钮");
ecp.quickLoginBtn().click();
Util.sleep(2);
String topInfo = ecp.quickRegisterSuccessInfo().getText();
if(topInfo.startsWith("user")) {
flag = true;
}
return flag;
}
/**
* 常规注册
* @param homePageURL 主站URL
* @param accountNum 注册用户名
* @param setPwd 注册密码
* @param confirmPwd 注册密码确认
* @param validBtn 获取验证码按钮
* @return 返回注册状态
* @throws InterruptedException
* @throws AWTException
*/
public boolean commonRegister(String homePageURL,String setPwd,
String loginPage_url, String username,
String password, String loginInfo, String firstMenu,String secondMenu)
throws InterruptedException, AWTException {
boolean flag = false;
this.driver.get(homePageURL);
Log.stepInfo("获取当前窗口句柄");
String homeWindow = this.driver.getWindowHandle();
Log.logInfo("当前窗口句柄为:"+homeWindow);
Util.sleep(2);
Log.stepInfo("点击弹窗关闭按钮");
ecp.closeBtn().click();
Util.sleep(1);
Log.stepInfo("点击注册链接");
ecp.registerBtn().click();
Util.sleep(4);
this.phone = this.phoneNum();
Log.stepInfo("输入车享账号:"+phone);
ecp.accountNum().click();
ecp.accountNum().sendKeys(phone);
Log.stepInfo("输入设置密码:"+setPwd);
ecp.setPwd().click();
ecp.setPwd().sendKeys(setPwd);
Log.stepInfo("输入确认密码:"+setPwd);
ecp.confirmPwd().click();
ecp.confirmPwd().sendKeys(setPwd);
Log.stepInfo("输入图片验证码");
ecp.imageValid().click();
ecp.imageValid().sendKeys("1111");
Log.stepInfo("点击获取验证码按钮:");
ecp.validBtn().click();
Util.sleep(2);
this.driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
Set<String> windowHandles = this.driver.getWindowHandles();
for(String ss:windowHandles) {
if(!ss.equals(homeWindow)) {
this.driver.switchTo().window(ss);
}
}
String cscWindow = this.driver.getWindowHandle();
// this.driver.get(csc_url);
// String cscWindow = this.driver.getWindowHandle();
String validValue = this.getValidValue(loginPage_url, username, password,
loginInfo, firstMenu, secondMenu, phone);
Set<String> windowHandles1 = this.driver.getWindowHandles();
for(String ss:windowHandles1) {
if(!ss.equals(cscWindow)) {
this.driver.switchTo().window(ss);
}
}
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_CONTROL);
//输入获得的验证码
Util.sleep(1);
driver.switchTo().defaultContent();
Log.stepInfo("输入验证码:"+validValue);
ecp.validInput().click();
ecp.validInput().sendKeys(validValue);
Log.stepInfo("点击立即注册按钮");
ecp.registerNowBtn().click();
Util.sleep(4);
Log.stepInfo("获取成功注册后信息");
try {
String text = ecp.registerSuccessInfo().getText();
Log.logInfo(text);
if(text.equals("恭喜您成为车享会员")) {
flag = true;
}
}catch(NoSuchElementException e) {
e.printStackTrace();
}
return flag;
}
/**
* 快速注册
* @throws InterruptedException
* @throws AWTException
*/
public boolean quickRegister(String quickUrl,String quickRegPassword,
String loginPage_url, String username, String password,
String loginInfo, String firstMenu, String secondMenu) throws InterruptedException, AWTException {
boolean flag = false;
this.goTo(quickUrl);
String homeWindow = this.driver.getWindowHandle();
Log.stepInfo("点击立即下定按钮");
ecp.orderNowBtn().click();
Util.sleep(2);
Log.stepInfo("切换iframe");
this.driver.switchTo().frame("inneriframe");
Log.stepInfo("点击新用户快速注册tab");
ecp.quickRegTab().click();
Util.sleep(2);
this.phone = this.phoneNum();
Log.stepInfo("输入用户名"+phone);
ecp.quickRegUsername().click();
ecp.quickRegUsername().sendKeys(phone);
Log.stepInfo("输入设置密码");
ecp.quickRegPassword().click();
ecp.quickRegPassword().sendKeys(quickRegPassword);
Log.stepInfo("输入验证码1111");
ecp.quickRegImageVal().sendKeys("1111");
Log.stepInfo("点击获取验证码按钮");
ecp.qucikValidBtn().click();
Util.sleep(1);
this.driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
Set<String> windowHandles = this.driver.getWindowHandles();
for(String ss:windowHandles) {
if(!ss.equals(homeWindow)) {
this.driver.switchTo().window(ss);
}
}
String cscWindow = this.driver.getWindowHandle();
// this.driver.get(csc_url);
// String cscWindow = this.driver.getWindowHandle();
String validValue = this.getValidValue(loginPage_url, username, password,
loginInfo, firstMenu, secondMenu, phone);
Set<String> windowHandles1 = this.driver.getWindowHandles();
for(String ss:windowHandles1) {
if(!ss.equals(cscWindow)) {
this.driver.switchTo().window(ss);
}
}
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_CONTROL);
//输入获得的验证码
Util.sleep(1);
driver.switchTo().defaultContent();
driver.switchTo().frame("inneriframe");
Log.stepInfo("输入验证码:"+validValue);
ecp.quickValidInput().sendKeys(validValue);
//点击立即注册按钮
Util.sleep(1);
ecp.quickRegisterBtn().click();
// Util.sleep(1);
// this.driver.navigate().refresh();
Util.sleep(3);
String topInfo = ecp.quickRegisterSuccessInfo().getText();
Log.logInfo(topInfo);
if(topInfo.startsWith("user")) {
flag = true;
}
return flag;
}
/**
* 获取验证码
* @param loginPage_url cscurl
* @param username csc登录用户名
* @param password csc登录密码
* @param loginInfo csc登录成功信息
* @param firstMenu 一级菜单名称
* @param secondMenu 二级菜单名称
* @param accountSearNum 需要查找的手机号
* @return 返回查询得到的验证码
* @throws InterruptedException
*/
public String getValidValue(String loginPage_url,String username,
String password,String loginInfo,String firstMenu,String secondMenu,
String accountSearNum) throws InterruptedException {
String validValue = "";
CSC_LoginOutPage cl = new CSC_LoginOutPage(this.driver);
cl.LoginAndVerify(loginPage_url, username, password, loginInfo);
Util.sleep(3);
CSC_Page cp = new CSC_Page(this.driver);
cp.clickSecondMenu(firstMenu, secondMenu);
Util.sleep(3);
Log.stepInfo("输入需要查询的手机号:"+accountSearNum);
ecp.iphoneNum().click();
ecp.iphoneNum().sendKeys(accountSearNum);
Log.stepInfo("点击查询按钮");
ecp.searchBtn().click();
Util.sleep(2);
Log.stepInfo("获取验证码:");
validValue = ecp.validCSC().getAttribute("value");
Log.logInfo("验证码是:"+validValue);
return validValue;
}
public boolean forgotPsw(String forgotUrl,String forgotAccNo,
String newPsw) {
boolean flag = false;
this.goTo(forgotUrl);
String homeWindow = this.driver.getWindowHandle();
Log.stepInfo("输入忘记密码的账号");
ecp.forgotAccNo().click();
ecp.forgotAccNo().sendKeys(forgotAccNo);
Log.stepInfo("输入图形验证码");
ecp.forgotImageValid().click();
ecp.forgotImageValid().sendKeys("1111");
Log.stepInfo("点击下一步按钮");
ecp.forgotNextStep().click();
Util.sleep(2);
Log.stepInfo("点击获取验证码按钮");
ecp.getForgotValidBtn().click();
/**获取验证码*/
String validValue = "";
Log.stepInfo("输入验证码");
ecp.forgotValidInput().click();
ecp.forgotValidInput().sendKeys(validValue);
Log.stepInfo("点击下一步按钮");
ecp.forgotNextBtns().click();
Util.sleep(2);
Log.stepInfo("输入新密码");
ecp.newPsw().click();
ecp.newPsw().sendKeys(newPsw);
Log.stepInfo("再次确认密码");
ecp.confirmPsw().click();
ecp.confirmPsw().sendKeys(newPsw);
Log.stepInfo("点击下一步按钮");
ecp.nextBtna().click();
String successInfo = ecp.forgotSuccessInfo().getText();
String expectedsuccessInfo = "恭喜您!密码已为您找回咯";
if(successInfo.equals(expectedsuccessInfo)) {
flag = true;
}
return flag;
}
/**
* 清除注册后的数据,包括:
* SSO库:t_user,t_user_alias
* MDM库:t_phone,t_user,t_user_bind
* @param registerNum
* @return
* @throws SQLException
*/
public boolean dataClear(String registerNum) throws SQLException {
boolean flag = false;
String userIds = "select user_id from t_user_alias where alias_name='"+registerNum+"';";
ConnectMySQL
.connect("10.32.173.250/sso", "sso", "sso");
String userId = ConnectMySQL.query(userIds).get(0).get("user_id");
String[] sqlsSSO = new String[]{"delete from t_user_alias where user_id='"+userId+"';",
"delete from t_user where user_id='"+userId+"';"};
String[] sqlsMDM = new String[]{"delete from t_phone where user_id='"+userId+"';",
"delete from t_user where user_id='"+userId+"';",
"delete from t_user_bind where user_id='"+userId+"';",};
ConnectMySQL
.connect("10.32.173.250/sso", "sso", "sso");
int[] a = ConnectMySQL.dbExecute(sqlsSSO);
ConnectMySQL.close();
ConnectMySQL
.connect("10.32.173.250/mdmuser", "mdmuser", "mdmuser");
int[] b = ConnectMySQL.dbExecute(sqlsMDM);
if(a.length+b.length==5){
flag = true;
}
return flag;
}
/**
*
* @param args
* @throws SQLException
*/
public String phoneNum() {
String phone = "";
phone = "135"+((int)(Math.random()*89999999)+10000000);
String sql = "select * from t_user_alias where alias_name='"+phone+"';";
ConnectMySQL
.connect("10.32.173.250/sso", "sso", "sso");
List<HashMap<String,String>> ll = ConnectMySQL.query(sql);
if(!ll.isEmpty()) {
phone = "135"+(int)(Math.random()*100000000);
}
ConnectMySQL.close();
return phone;
}
public static void main(String[] args) throws SQLException {
//Log.logInfo(phoneNum());
}
}
|
Python
|
UTF-8
| 887
| 2.703125
| 3
|
[] |
no_license
|
dxy = [[1, 0], [0, 1], [-1, 0], [0, -1]]
def BFS(start_node, target_row, target_col, maps):
global discovered
queue = [start_node + (1,)]
discovered[start_node[0]][start_node[1]] = 1
while queue:
cr, cc, w = queue.pop(0)
for r, c in dxy:
nr = cr + r
nc = cc + c
if 0 <= nr <= target_row and 0 <= nc <= target_col and maps[nr][nc]:
if not discovered[nr][nc]:
if nr == target_row and nc == target_col:
return w + 1
discovered[nr][nc] = 1
queue.append((nr, nc, w + 1))
return -1
def solution(maps):
global discovered
# n, m 찾기
n = len(maps) - 1
m = len(maps[0]) - 1
discovered = [[0] * (m+1) for _ in range(n+1)]
answer = BFS((0,0), n, m, maps)
return answer
|
Markdown
|
UTF-8
| 4,291
| 2.71875
| 3
|
[
"CC-BY-4.0",
"CC-BY-NC-4.0",
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
---
layout: post
title: "De Android à iOS"
ref: android-ios
lang: fr
date: 2020-08-06 16:30:00 -0500
author: Guillaume Charest
excerpt_separator: <!--more-->
---
Depuis la sortie du Nexus One de Google, j'ai eu presque exclusivement des téléphones Android, avec de très courts essais de certains modèles de iPhones. Lorsque mes deux aînés ont été diagnostiqués avec le diabète de type 1, j'ai dû revoir mon allégeance au système d'opération de Google.
<!--more-->
Bon, je dois dire que le terme "allégeance" est un peu fort mais disons que j'ai longtemps préféré la grande flexibilité que Android offrait au niveau de la personnalisation de l'expérience.
Android étant à la base un projet de logiciel libre, de nombreuses compagnies de cellulaires et de développement de logiciels ont saisi l'occasion pour introduire des interfaces et des applications très variées, diversifiant ainsi l'expérience utilisateur.
De plus, le niveau de contrôle possible avec cette plateforme est très avancé, permettant de faire des changements au niveau du système d'opérations qui n'est pas possible avec un appareil iOS.
Puis, comme Apple a longtemps gardé un contrôle très serré sur les actions permises entre les applications sur les iPhones, il était parfois difficile d'arriver à faire exactement les mêmes opérations que sur un appareil Android, comme choisir avec qu'elle application recevoir et envoyer des courriels.
C'est donc en grande partie pourquoi je suis longtemps resté avec des appareils propulsés avec le système d'opération de Google.
À noter que je m'en suis principalement tenu aux appareils "vanille", n'ayant pas d'interfaces développées par les fabricants tels Samsung, HTC, Motorola, etc.
Ce faisant, j'avais l'expérience conçue par Google et les mises à jour rapides permettant d'avoir les toutes nouvelles fonctionnalités ou de fixer des problèmes dès que possible.
Cependant, lorsque mes fils ont commencé à utiliser le système de surveillance du glucose en continue (SGC) Dexcom G6, nous avons préféré aller avec des téléphones intelligents plutôt que le simple moniteur Bluetooth car nous voulions pouvoir suivre leur glycémie même s'ils n'étaient pas avec nous.
Au début, j'avais planifié réutiliser de vieux appareils Android mais je me suis rapidement frappé à un mur: impossible de créer un compte pour enfant avec Google au Québec....
Google offre bel et bien un service de compte pour enfants de moins de 13 ans mais celui-ci n'est pas conforme aux législations québécoises.
Il m'était donc impossible de l'utiliser, même après de nombreuses démarches auprès du service à la clientèle.
Il faut d'ailleurs noter que si Android est à la base un logiciel libre, l'expérience que la plupart du monde vit avec cette plateforme est beaucoup plus fermée, les services de Google n'étant après tout pas tous sous licence libre.
Finalement, ayant aussi quelques vieux iPhones à portée de main, j'ai tenté la création d'un compte pour enfant.
Quelques minutes plus tard, les appareils étaient fonctionnels et nous pouvions suivre leur glycémie même à distance, ce qui nous permettait d'être beaucoup plus proactifs dans nos interventions sur leur état de santé.
Pour faciliter la gestion de tous ces appareils, j'ai donc moi aussi changé pour un iPhone.
L'expérience a été relativement transparente, la majorité des applications étant maintenant disponibles sur les deux plateformes, contrairement à il y a quelques années.
De plus, iOS est devenu beaucoup plus flexible avec le temps, permettant de mieux personnaliser l'expérience de l'utilisateur.
Il reste quelques petits points un peu plus rigides, comme la fonction "Ne pas déranger", qui ne laisse pas autant de contrôle au niveau du comportement d'applications spécifiques.
Néanmoins, je suis bien heureux de pouvoir compter sur ces différents appareils pour aider nos garçons dans la gestion de leur diabète.
Et la technologie continue d'évoluer, introduisant de plus en plus de concepts intéressants comme l'arrêt automatique de l'insuline lorsque l'un d'eux est sur le point de tomber en hypoglycémie et bientôt, je l'espère, l'augmentation de l'insuline lorsque ceux-ci seront en hyperglycémie.
|
C
|
UTF-8
| 1,909
| 2.703125
| 3
|
[
"LicenseRef-scancode-dco-1.1",
"MIT"
] |
permissive
|
#include <aos/aos.h>
#include <spawn/process_manager.h>
/*------------------------------------------Implementations------------------------------------------------*/
/* private */
struct domain_info* process_manager_new_node(const char *name, coreid_t core, domainid_t domainid) {
assert(name != NULL);
assert(domainid >> 24 == 0);
struct domain_info *di = (struct domain_info *) malloc(sizeof(struct domain_info));
di->name = (char *) malloc(strlen(name));
strcpy(di->name, name);
di->pid = (core << 24) + domainid;
di->next = NULL;
return di;
}
domainid_t process_manager_pid_alloc(struct process_manager *pm) {
return pm->next_pid++;
}
/* public */
errval_t process_manager_init(struct process_manager *pm) {
pm->core = disp_get_core_id();
pm->head = process_manager_new_node("init", pm->core, 0);
pm->count = 1;
pm->next_pid = pm->count;
return SYS_ERR_OK;
}
domainid_t process_manager_add(struct process_manager *pm, const char *name) {
assert(pm->head != NULL);
domainid_t new_pid = process_manager_pid_alloc(pm);
struct domain_info *di = process_manager_new_node(name, pm->core, new_pid);
di->next = pm->head;
pm->head = di;
pm->count++;
return new_pid;
}
const char *process_manager_get_name(struct process_manager *pm, domainid_t pid) {
struct domain_info *p = pm->head;
while (p != NULL && p->pid != pid) { p = p->next; }
if (p == NULL) {
return NULL;
}
return p->name;
}
void process_manager_get_all_pids(struct process_manager *pm, domainid_t **arr, domainid_t *length) {
*arr = (domainid_t *) malloc(sizeof(domainid_t) * pm->count);
*length = pm->count;
domainid_t *ptr = *arr;
for (struct domain_info* di = pm->head; di != NULL; di = di->next, ++ptr) {
*ptr = di->pid;
}
}
coreid_t pid_get_core_id(domainid_t pid) {
return pid >> 24;
}
|
C
|
ISO-8859-1
| 1,997
| 3.734375
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <locale.h>
/*2.3.2 Em uma empresa de saneamento bsico os servios
recebem uma numerao de acordo com sua natureza: 1 para
troca de tubulao, 2 para verificao de problemas de
vazamento, 3 para ligao de gua e esgoto. De acordo com o
problema, o servio agendado para um determinado horrio do
dia. 8h da manh so agendados os servios 1, para s 11h so
agendados os servios 2 e para s 15h so agendados os servios
3. Voc, como programador de sistemas da empresa, foi
designado para fazer um programa que agende os servios em
seus respectivos horrios. O programa deve receber o numero do
servio e mostrar o seu horrio de agendamento. Use o comando
switch, com mensagem de erro caso o usurio digite um numero
invalido. Faa o algoritmo e o fluxograma antes do programa. */
int main(void)
{
int escolha, invalido=0;
setlocale(LC_ALL, "Portuguese");
printf("Bem vindo ao sistema de agendamento ao saneamento bsico. Digite o nmero referente ao seu problema, sendo: (1) para troca de tubulao, (2) para verificao de problemas devazamento e (3) para ligao de gua e esgoto.\nDigite: ");
scanf("%i", &escolha);
do
{
switch(escolha)
{
case 1:
printf("\ntimo, voc escolheu (1), Troca de tubulao, sua visita est agendada para as 08h.");
invalido=1;
break;
case 2:
printf("\ntimo, voc escolheu (2), Ligao de gua e Esgoto, sua visita est agendada para as 15h.");
invalido=1;
break;
case 3:
printf("\ntimo, voc escolheu (3), Troca de tubulao, sua visita est agendada para as 08h.");
invalido=1;
break;
default:
printf("Opo invalida, digite novamente\n");
scanf("%i", &escolha);
break;
}
}while(invalido==0);
printf("\n\nObrigado, at a visita! \n\n");
system("PAUSE");
}
|
Java
|
UTF-8
| 956
| 2.421875
| 2
|
[] |
no_license
|
package com.itsm.frontend.service;
import com.itsm.common.entity.Transaction;
import com.itsm.frontend.annotation.Auditable;
import com.itsm.frontend.storage.Storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.awt.*;
@Service
public class TransactionAddService implements AddServiceInterface<Transaction> {
@Autowired
private Storage<Transaction> transactionStorage;
@Override
@Transactional
@Auditable
public void add(Transaction transaction) throws Exception {
if(transaction.getPatient().getState().getId() != transaction.getProduct().getState().getId()) {
throw new Exception("Patient's state and Products State has to be the same!");
}
transactionStorage.add(transaction);
}
}
|
Ruby
|
UTF-8
| 666
| 2.765625
| 3
|
[] |
no_license
|
class Item::UserItemService
def initialize(player, user_item)
@player = player
@user_item = user_item
end
def name
return @user_item.item.name
end
def count
return @user_item.count
end
def sell_price
return @user_item.item.sell_price
end
# このアイテム売る
def sell
#先にアイテムを減らす。
after = @user_item.count - 1
if after < 0
return false
end
@user_item.count = after
# お金を増やす
@player.give_rails(@user_item.item.sell_price)
end
# トランザクション的にはこれ使ってね
def save!
@user_item.save!
@player.save!
end
end
|
Java
|
UTF-8
| 5,724
| 2.125
| 2
|
[] |
no_license
|
package com.ecocitycraft.shopdb.controllers;
import com.ecocitycraft.shopdb.database.ChestShop;
import com.ecocitycraft.shopdb.database.Player;
import com.ecocitycraft.shopdb.database.Region;
import com.ecocitycraft.shopdb.models.PaginatedResponse;
import com.ecocitycraft.shopdb.models.chestshops.*;
import com.ecocitycraft.shopdb.models.exceptions.ExceptionMessage;
import com.ecocitycraft.shopdb.models.exceptions.SDBIllegalArgumentException;
import com.ecocitycraft.shopdb.models.exceptions.SDBNotFoundException;
import com.ecocitycraft.shopdb.models.players.PlayerDto;
import com.ecocitycraft.shopdb.models.players.PlayerMapper;
import com.ecocitycraft.shopdb.models.players.PlayersQueryView;
import com.ecocitycraft.shopdb.models.regions.RegionDto;
import com.ecocitycraft.shopdb.models.regions.RegionMapper;
import com.ecocitycraft.shopdb.models.regions.RegionsQueryView;
import com.ecocitycraft.shopdb.services.Pagination;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.NoResultException;
import javax.transaction.Transactional;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
import java.util.stream.Collectors;
@Path("/players")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class PlayerController {
Logger LOGGER = LoggerFactory.getLogger(PlayerController.class);
@GET
@Transactional
public PaginatedResponse<PlayerDto> getPlayers(
@DefaultValue("1") @QueryParam("page") Integer page,
@DefaultValue("6") @QueryParam("pageSize") Integer pageSize,
@DefaultValue("") @QueryParam("name") String name,
@DefaultValue("name") @QueryParam("sortBy") SortBy sortBy
) {
LOGGER.info("GET /players");
if (page < 1) throw new SDBIllegalArgumentException(ExceptionMessage.INVALID_PAGE);
if (pageSize < 1 || pageSize > 100) throw new SDBIllegalArgumentException(ExceptionMessage.INVALID_PAGE_SIZE);
long totalResults = Player.count(name);
List<PlayersQueryView> players = Player.find(name, sortBy, page - 1, pageSize);
List<PlayerDto> results = players.stream().map(PlayerMapper::toPlayerDto).collect(Collectors.toList());
return new PaginatedResponse<>(page, Pagination.getNumPages(pageSize, totalResults), totalResults, results);
}
@GET
@Path("player-names")
public List<PanacheEntityBase> getPlayerNames() {
return Player.findPlayerNames();
}
@GET
@Path("{name}")
public PlayerDto getPlayer(@PathParam("name") String name) {
LOGGER.info("GET /players/" + name);
List<PlayersQueryView> players = Player.find(name, SortBy.NAME, 0, 10);
if (players.size() == 0 || !players.get(0).getName().equalsIgnoreCase(name)) {
throw new SDBNotFoundException(String.format(ExceptionMessage.PLAYER_NOT_FOUND, name));
}
return PlayerMapper.toPlayerDto(players.get(0));
}
@GET
@Path("{name}/regions")
public PaginatedResponse<RegionDto> getPlayerRegions(
@DefaultValue("1") @QueryParam("page") Integer page,
@DefaultValue("6") @QueryParam("pageSize") Integer pageSize,
@PathParam("name") String name
) {
LOGGER.info("GET /players/" + name + "/regions");
if (page < 1) throw new SDBIllegalArgumentException(ExceptionMessage.INVALID_PAGE);
if (pageSize < 1 || pageSize > 100) throw new SDBIllegalArgumentException(ExceptionMessage.INVALID_PAGE_SIZE);
if (name == null || name.isEmpty()) throw new SDBIllegalArgumentException(ExceptionMessage.EMPTY_PLAYER_NAME);
Long id;
try {
id = Player.id(name);
} catch (NoResultException e) {
throw new SDBNotFoundException(String.format(ExceptionMessage.PLAYER_NOT_FOUND, name));
}
long totalResults = Region.countByPlayerId(id);
List<RegionsQueryView> regions = Region.findByPlayerId(id, page - 1, pageSize);
List<RegionDto> results = regions.stream().map(RegionMapper::toRegionDto).collect(Collectors.toList());
return new PaginatedResponse<>(page, Pagination.getNumPages(pageSize, totalResults), totalResults, results);
}
@GET
@Path("{name}/chest-shops")
public PaginatedResponse<ChestShopDto> getPlayerChestShops(
@DefaultValue("1") @QueryParam("page") Integer page,
@DefaultValue("6") @QueryParam("pageSize") Integer pageSize,
@DefaultValue("buy") @QueryParam("tradeType") TradeType tradeType,
@PathParam("name") String name) {
LOGGER.info("GET /players/" + name + "/chest-shops");
if (page < 1) throw new SDBIllegalArgumentException(ExceptionMessage.INVALID_PAGE);
if (pageSize < 1 || pageSize > 100) throw new SDBIllegalArgumentException(ExceptionMessage.INVALID_PAGE_SIZE);
if (name == null || name.isEmpty()) throw new SDBIllegalArgumentException(ExceptionMessage.EMPTY_PLAYER_NAME);
Long id;
try {
id = Player.id(name);
} catch (NoResultException e) {
throw new SDBNotFoundException(String.format(ExceptionMessage.PLAYER_NOT_FOUND, name));
}
long totalResults = ChestShop.countByPlayerId(id, tradeType);
List<ChestShopsQueryView> chestShops = ChestShop.findByPlayerId(id, tradeType, page - 1, pageSize);
List<ChestShopDto> results = chestShops.stream().map(ChestShopMapper::toChestShopDto).collect(Collectors.toList());
return new PaginatedResponse<>(page, Pagination.getNumPages(pageSize, totalResults), totalResults, results);
}
}
|
JavaScript
|
UTF-8
| 4,623
| 3.1875
| 3
|
[] |
no_license
|
var library = {
tracks: { t01: { id: "t01",
name: "Code Monkey",
artist: "Jonathan Coulton",
album: "Thing a Week Three" },
t02: { id: "t02",
name: "Model View Controller",
artist: "James Dempsey",
album: "WWDC 2003"},
t03: { id: "t03",
name: "Four Thirty-Three",
artist: "John Cage",
album: "Woodstock 1952"}
},
playlists: { p01: { id: "p01",
name: "Coding Music",
tracks: ["t01", "t02"]
},
p02: { id: "p02",
name: "Other Playlist",
tracks: ["t03"]
}
},
// prints a list of all playlists, in the form:
// p01: Coding Music - 2 tracks
// p02: Other Playlist - 1 tracks
printPlaylists: function () {
const pl = this.playlists;
for (pID in pl) {
console.log(pID + ": " + pl[pID].name + " - " + pl[pID].tracks.length + " tracks");
//console.log(`${pID}: ${pl[pID].name} - ${pl[pID].tracks.length} tracks`);
}
},
// prints a list of all tracks, in the form:
// t01: Code Monkey by Jonathan Coulton (Thing a Week Three)
// t02: Model View Controller by James Dempsey (WWDC 2003)
// t03: Four Thirty-Three by John Cage (Woodstock 1952)
printTracks: function () {
const tr = this.tracks;
for (tID in tr) {
this.printTrack(tID);
// console.log(tID + ": " + tr[tID].name + " by " + tr[tID].artist + " (" + tr[tID].album + ")");
}
},
printTrack: function (trackId) {
if (this.tracks[trackId] !== undefined) {
const tr = this.tracks[trackId];
console.log(trackId + ": " + tr.name + " by " + tr.artist + " (" + tr.album + ")");
}
else {
console.log("Please enter a valide track ID");
}
},
// prints a list of tracks for a given playlist, in the form:
// p01: Coding Music - 2 tracks
// t01: Code Monkey by Jonathan Coulton (Thing a Week Three)
// t02: Model View Controller by James Dempsey (WWDC 2003)
printPlaylist: function (playlistId) {
if (this.playlists[playlistId] !== undefined) {
const pl = this.playlists[playlistId]
const trackList = pl.tracks;
console.log(playlistId + ": " + pl.name + " - " + pl.tracks.length + " tracks")
trackList.forEach(function(element) {
this.printTrack(element);
}, this);
}
else {
console.log("Please enter a valid playlist ID");
}
},
// adds an existing track to an existing playlist
addTrackToPlaylist: function (trackId, playlistId) {
if (this.tracks[trackId] !== undefined && this.playlists[playlistId] !== undefined){
this.playlists[playlistId].tracks.push(trackId);
}
else {
console.log("Please enter a valid track ID and a valid playlist ID");
}
},
// generates a unique id
// (use this for addTrack and addPlaylist)
uid: function() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
},
// adds a track to the library
addTrack: function (name, artist, album) {
const newID = "t" + this.uid();
const newTrack = {
id: newID,
name: name,
artist: artist,
album: album
}
this.tracks[newID] = newTrack;
},
// adds a playlist to the library
addPlaylist: function (name) {
const newID = "p" + this.uid();
const newPlaylist = {
id: newID,
name: name,
tracks: []
}
this.playlists[newID] = newPlaylist;
},
// STRETCH:
// given a query string string, prints a list of tracks
// where the name, artist or album contains the query string (case insensitive)
// tip: use "string".search("tri")
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
printSearchResults: function(query) {
const tr = this.tracks;
for (tID in tr){
let found = false;
if (tr[tID].name.search(query) !== -1){
found = true;
}
if (tr[tID].artist.search(query) !== -1){
found = true;
}
if (tr[tID].album.search(query) !== -1){
found = true;
}
if (found === true){
this.printTrack(tID);
}
}
}
}
library.printPlaylists();
library.printTracks();
library.printPlaylist("p02");
library.addTrackToPlaylist("t01", "p02");
library.printPlaylist("p02");
library.addTrack("trackName", "artistName", "albumName");
library.printTracks();
library.addPlaylist("New List");
library.printPlaylists();
library.printSearchResults("ames");
|
Java
|
UTF-8
| 2,220
| 2.296875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
*
*/
package com.yueny.rapid.email.sender.internals.tacitly;
import com.yueny.rapid.email.sender.entity.MessageData;
import com.yueny.rapid.email.sender.listener.ConsoleEmailSendListener;
import com.yueny.rapid.email.sender.listener.IEmailSendListener;
import com.yueny.rapid.lang.thread.executor.AsyncLoadExecutors;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
/**
* 抽象邮件发送服务
*
* @author yueny09 <yueny09@163.com>
*
* @DATE 2018年4月11日 下午11:13:42
*
*/
abstract class BaseEmailServer implements IEmailServer {
@Getter
private static final AsyncLoadExecutors executor = new AsyncLoadExecutors(2);
static{
// final Properties properties = SysConfig.getConfiguration();
executor.initital();
}
public BaseEmailServer(){
this.initital();
}
protected void initital() {
// 增加控制台输出
addListener(new ConsoleEmailSendListener());
}
/**
* 对邮件发送的全局列表
* @key 实例化的类名
* @value 监听器实例对象
*/
private final Map<String, IEmailSendListener> emailSendListeners = new HashMap<>();
protected void addListener(final IEmailSendListener emailSendListener) {
String listenerName = emailSendListener.getClass().getCanonicalName();
if(emailSendListeners.containsKey(listenerName)){
return;
}
this.emailSendListeners.putIfAbsent(listenerName, emailSendListener);
}
protected void doAfter(final MessageData messageData) {
for (final IEmailSendListener emailSendListener : this.emailSendListeners.values()) {
emailSendListener.after(messageData);
}
}
protected void doAfterThrowable(MessageData messageData, Throwable throwable) {
for (final IEmailSendListener emailSendListener : this.emailSendListeners.values()) {
emailSendListener.afterThrowable(messageData, throwable);
}
}
protected void doBefore(final MessageData messageData) {
for (final IEmailSendListener emailSendListener : this.emailSendListeners.values()) {
emailSendListener.before(messageData);
}
}
}
|
Python
|
UTF-8
| 5,070
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import os
import unittest
import shorttext
class TestVarNNEmbeddedVecClassifier(unittest.TestCase):
def setUp(self):
if not os.path.isfile("test_w2v_model"):
os.system("wget https://raw.githubusercontent.com/chinmayapancholi13/shorttext_test_data/master/test_w2v_model") # download w2v model
self.w2v_model = shorttext.utils.load_word2vec_model("test_w2v_model", binary=False) # load word2vec model
self.trainclass_dict = shorttext.data.subjectkeywords() # load training data
def tearDown(self):
if os.path.isfile("test_w2v_model"):
os.remove("test_w2v_model") # delete downloaded w2v model
def testCNNWordEmbedWithoutGensim(self):
# create keras model using `CNNWordEmbed` class
keras_model = shorttext.classifiers.frameworks.CNNWordEmbed(wvmodel=self.w2v_model, nb_labels=len(self.trainclass_dict.keys()), vecsize=100, with_gensim=False)
# create and train classifier using keras model constructed above
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model, with_gensim=False, vecsize=100)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
def testCNNWordEmbedWithGensim(self):
# create keras model using `CNNWordEmbed` class
keras_model = shorttext.classifiers.frameworks.CNNWordEmbed(wvmodel=self.w2v_model, nb_labels=len(self.trainclass_dict.keys()), vecsize=100, with_gensim=True)
# create and train classifier using keras model constructed above
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model, with_gensim=True, vecsize=100)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
def testDoubleCNNWordEmbedWithoutGensim(self):
# create keras model using `DoubleCNNWordEmbed` class
keras_model = shorttext.classifiers.frameworks.DoubleCNNWordEmbed(wvmodel=self.w2v_model, nb_labels=len(self.trainclass_dict.keys()), vecsize=100, with_gensim=False)
# create and train classifier using keras model constructed above
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model, with_gensim=False, vecsize=100)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
def testDoubleCNNWordEmbedWithGensim(self):
# create keras model using `DoubleCNNWordEmbed` class
keras_model = shorttext.classifiers.frameworks.DoubleCNNWordEmbed(wvmodel=self.w2v_model, nb_labels=len(self.trainclass_dict.keys()), vecsize=100, with_gensim=True)
# create and train classifier using keras model constructed above
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model, with_gensim=True, vecsize=100)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
def testCLSTMWordEmbedWithoutGensim(self):
# create keras model using `CLSTMWordEmbed` class
keras_model = shorttext.classifiers.frameworks.CLSTMWordEmbed(wvmodel=self.w2v_model, nb_labels=len(self.trainclass_dict.keys()), vecsize=100, with_gensim=False)
# create and train classifier using keras model constructed above
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model, with_gensim=False, vecsize=100)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
def testCLSTMWordEmbedWithGensim(self):
# create keras model using `CLSTMWordEmbed` class
keras_model = shorttext.classifiers.frameworks.CLSTMWordEmbed(wvmodel=self.w2v_model, nb_labels=len(self.trainclass_dict.keys()), vecsize=100, with_gensim=True)
# create and train classifier using keras model constructed above
main_classifier = shorttext.classifiers.VarNNEmbeddedVecClassifier(self.w2v_model, with_gensim=True, vecsize=100)
main_classifier.train(self.trainclass_dict, keras_model, nb_epoch=2)
# compute classification score
score_vals = main_classifier.score('artificial intelligence')
self.assertAlmostEqual(score_vals['mathematics'] + score_vals['physics'] + score_vals['theology'], 1.0, 1)
if __name__ == '__main__':
unittest.main()
|
Swift
|
UTF-8
| 357
| 2.53125
| 3
|
[] |
no_license
|
//
// Error.swift
// FlightSearch
//
// Created by Andrey Ovsyannikov on 19.02.2021.
// Copyright © 2021 home.com. All rights reserved.
//
import Foundation
enum LocalError: Error, LocalizedError {
case notFound
var errorDescription: String? {
switch self {
case .notFound:
return .flightsNotFound
}
}
}
|
Java
|
UTF-8
| 3,881
| 1.828125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package ru.ltst.u2020mvp.tests;
import android.test.ActivityInstrumentationTestCase2;
import com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers;
import com.squareup.spoon.Spoon;
import javax.inject.Inject;
import dagger.ObjectGraph;
import retrofit.MockRestAdapter;
import ru.ltst.u2020mvp.R;
import ru.ltst.u2020mvp.tests.util.ViewActions;
import ru.ltst.u2020mvp.ui.gallery.GalleryActivity;
import ru.ltst.u2020mvp.ui.gallery.GalleryModule;
import static com.google.android.apps.common.testing.ui.espresso.Espresso.onData;
import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isRoot;
import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
import static org.hamcrest.Matchers.anything;
public class GalleryActivityTest extends ActivityInstrumentationTestCase2<GalleryActivity> {
public static final int WAIT_DELAY = 5000;
GalleryActivity activity;
ObjectGraph graph;
@Inject MockRestAdapter mockRestAdapter;
@Inject GalleryActivity.Presenter presenter;
public GalleryActivityTest() {
super(GalleryActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
activity = getActivity();
graph = TestInjector.inject(activity, this, new Module());
mockRestAdapter.setDelay(0);
mockRestAdapter.setErrorPercentage(0);
mockRestAdapter.setVariancePercentage(0);
}
@Override
public void tearDown() throws Exception {
graph = null;
super.tearDown();
}
public void testGalleryLoadData() throws Throwable {
assertNotNull(activity);
assertNotNull(presenter);
String tag = "1. Root view visible, progress bar showing";
onView(isRoot()).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
screenshot(tag);
tag = "2. Grid shown with images loaded";
onView(isRoot()).perform(ViewActions.waitAtLeast(WAIT_DELAY));
onView(withId(R.id.gallery_grid)).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
screenshot(tag);
}
public void testFirstImageClickOpenImageActivity() throws Throwable {
String tag = "1. Grid shown with images loaded";
onView(isRoot()).perform(ViewActions.waitAtLeast(WAIT_DELAY));
screenshot(tag);
tag = "2. Opened imgur image activity with first image";
onData(anything()).inAdapterView(withId(R.id.gallery_grid)).atPosition(0).perform(click());
screenshot(tag);
}
public void testListScrolling() throws Throwable {
String tag = "1. Grid shown with images loaded";
onView(isRoot()).perform(ViewActions.waitAtLeast(WAIT_DELAY));
screenshot(tag);
onView(withId(R.id.gallery_grid)).perform(ViewActions.swipeTop());
tag = "2. Scrolled to bottom";
screenshot(tag);
tag = "3. Scrolled to top";
onView(withId(R.id.gallery_grid)).perform(ViewActions.swipeBottom());
screenshot(tag);
}
protected void screenshot(String description) throws Throwable {
Thread.sleep(100);
Spoon.screenshot(activity, description.replaceAll("[^a-zA-Z0-9_-]", "_"));
}
@dagger.Module(
injects = GalleryActivityTest.class,
addsTo = GalleryModule.class,
overrides = true,
complete = false
)
public static class Module {
}
}
|
Ruby
|
UTF-8
| 354
| 3.796875
| 4
|
[] |
no_license
|
print'Intro num_1: '
n1=gets.to_i
print'Intro num_2: '
n2=gets.to_i
print'Intro num_3: '
n3=gets.to_i
if n1 > n2 && n1>n3
print 'El mayor es: '
puts n1
else
if n2>n3
print 'El mayor es: '
puts n2
else
if n3>n1
print 'El mayor es: '
puts n3
end
end
end
|
Java
|
UTF-8
| 844
| 2.703125
| 3
|
[] |
no_license
|
package spittr.data;
import org.springframework.stereotype.Component;
import spittr.Spittle;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Component
public class Spittles implements SpittleRepository {
private List<Spittle> list = new ArrayList<>();
public Spittles() {
list.add(new Spittle(1L,"m1",new Date(),1.1,2.2));
list.add(new Spittle(2L, "m2",new Date(),1.1,2.2));
}
@Override
public List<Spittle> findSpittles(long max, int count) {
List<Spittle> l = new ArrayList<>();
for (Spittle s : list){
if (s.getId() < max) l.add(s);
}
return l;
}
@Override
public Spittle findOne(long spittleId) {
for (Spittle s : list){
if (s.getId() == spittleId) return s;
}
return null;
}
}
|
Ruby
|
UTF-8
| 267
| 2.59375
| 3
|
[] |
no_license
|
require './minion'
class SouthseaDeckhand < Minion
def initialize
super
self.name = "Southsea Deckhand"
self.cost = 1
self.attack = 2
self.max_health = 1
end
def charge
if owner.weapon
true
else
false
end
end
end
|
JavaScript
|
UTF-8
| 2,428
| 2.984375
| 3
|
[
"Apache-2.0"
] |
permissive
|
/**
* logger.js - HumanInput Logger: A really nice logging class
* Copyright (c) 2016, Dan McDougall
* @link https://github.com/liftoff/HumanInput/src/logger.js
* @license Apache-2.0
*/
import { noop, isFunction } from './utils';
const console = window.console;
const levels = {
40: 'ERROR', 30: 'WARNING', 20: 'INFO', 10: 'DEBUG', // Forward
'ERROR': 40, 'WARNING': 30, 'INFO': 20, 'DEBUG': 10 // Reverse
};
export class Logger {
constructor(lvl, prefix) {
this.prefix = prefix;
this.setLevel(lvl);
this.writeErr = this.fallback;
this.writeWarn = this.fallback;
this.writeInfo = this.fallback;
this.writeDebug = this.fallback;
if (isFunction(console.error)) { this.writeErr = console.error; }
if (isFunction(console.warn)) { this.writeWarn = console.warn; }
if (isFunction(console.info)) { this.writeInfo = console.info; }
if (isFunction(console.debug)) { this.writeDebug = console.debug; }
}
setLevel(level) {
level = level.toUpperCase();
this.error = this.write.bind(this, 40);
this.warn = this.write.bind(this, 30);
this.info = this.write.bind(this, 20);
this.debug = this.write.bind(this, 10);
this.logLevel = level;
if (isNaN(level)) { this.logLevel = level = levels[level]; }
// These conditionals are just a small performance optimization:
if (level > 40) { this.error = noop; }
if (level > 30) { this.warn = noop; }
if (level > 20) { this.info = noop; }
if (level > 10) { this.debug = noop; }
}
fallback(level) {
var args = Array.from(arguments);
args[0] = this.prefix + levels[level] + ' ' + args[0];
if (isFunction(console.log)) {
console.log.apply(console, args);
}
}
write(level) {
var logLevel = this.logLevel;
var args = Array.from(arguments).slice(1);
if (this.prefix.length) { args.unshift(this.prefix); }
if (level === 40 && logLevel <= 40) {
this.writeErr.apply(console, args);
} else if (level === 30 && logLevel <= 30) {
this.writeWarn.apply(console, args);
} else if (level === 20 && logLevel <= 20) {
this.writeInfo.apply(console, args);
} else if (level === 10 && logLevel <= 10) {
this.writeDebug.apply(console, args);
}
}
}
|
Java
|
UTF-8
| 61
| 2.078125
| 2
|
[] |
no_license
|
public interface Measurable {
public double getSize();
}
|
PHP
|
UTF-8
| 542
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Observers;
use App\Models\Config;
class ConfigObserver
{
public function created()
{
$this->saveConfigToCache();
}
public function updated()
{
$this->saveConfigToCache();
}
public function saveConfigToCache()
{
//pluck 手册地址:查询构造器
//pluck('data','value') 获取两列数据,data 作为键名 ,value 键值
//将配置项数据放入永久储存
\Cache::forever('config_cache', Config::pluck('data', 'title'));
}
}
|
Markdown
|
UTF-8
| 33,515
| 3.0625
| 3
|
[] |
no_license
|
<p data-nodeid="1077" class="">今天我想和你聊一聊怎么用 Serverless 开发一个服务端渲染(SSR)应用。</p>
<p data-nodeid="1078">对前端工程师来说,Serverless 最大的应用场景之一就是开发服务端渲染(SSR)应用。因为传统的服务端渲染应用要由前端工程师负责服务器的运维,但往往前端工程师并不擅长这一点,基于 Serverless 开发服务端渲染应用的话,就可以减轻这个负担。希望你学完今天的内容之后,能够学会如何去使用 Serverless 开发一个服务端渲染应用。</p>
<p data-nodeid="1079">话不多说,我们开始今天的学习。</p>
<h3 data-nodeid="1080">基于 Serverless 的服务端渲染架构</h3>
<p data-nodeid="1081">现在的主流前端框架是 React.js、Vue.js 等,基于这些框架开发的都是单页应用,其渲染方式都是客户端渲染:代码开发完成后,构建出一个或多个 JS 资源,页面渲染时加载这些 JS 资源,然后再执行 JS 渲染页面。虽然这些框架可以极大提升前端开发效率,但也带来了一些新的问题。</p>
<ul data-nodeid="1082">
<li data-nodeid="1083">
<p data-nodeid="1084"><strong data-nodeid="1219">不利于 SEO:</strong> 页面源码不再是HTML,而是渲染 HTML 的 JavaScript,这就导致搜索引擎爬虫难以解析其中的内容;</p>
</li>
<li data-nodeid="1085">
<p data-nodeid="1086"><strong data-nodeid="1224">初始化性能差:</strong> 通常单元应用的 JS 文件体积都比较大、加载耗时比较长,导致页面白屏。</p>
</li>
</ul>
<p data-nodeid="1087">为了解决这些问题,很多框架和开发者就开始尝试服务端渲染的方式:页面加载时,由服务端先生成 HTML 返回给浏览器,浏览器直接渲染 HTML。在传统的服务端渲染架构中,通常需要前端同学使用 Node.js 去实现一个服务端的渲染应用。在应用内,每个请求的 path 对应着服务端的每个路由,由该路由实现对应 path 的 HTML 文档渲染:</p>
<p data-nodeid="1088"><img src="https://s0.lgstatic.com/i/image/M00/94/3B/Ciqc1GAXxlCABEjhAAGFmUrRE68475.png" alt="Drawing 0.png" data-nodeid="1228"></p>
<div data-nodeid="1089"><p style="text-align:center">传统服务端渲染架构</p></div>
<p data-nodeid="1090">对前端工程师来说,要实现一个服务端渲染应用,通常面临着一些问题:</p>
<ul data-nodeid="1091">
<li data-nodeid="1092">
<p data-nodeid="1093">部署服务端渲染应用需要购买服务器,并配置服务器环境,要对服务器进行运维;</p>
</li>
<li data-nodeid="1094">
<p data-nodeid="1095">需要关注业务量,考虑有没有高并发场景、服务器有没有扩容机制;</p>
</li>
<li data-nodeid="1096">
<p data-nodeid="1097">需要实现负载均衡、流量控制等复杂后端能力等。</p>
</li>
</ul>
<p data-nodeid="1098">开篇我也提到,而且是服务端的工作,很多前端同学都不擅长,好在有了 Serverless。</p>
<p data-nodeid="1099">用 Serverless 做服务端渲染,就是将以往的每个路由,都拆分为一个个函数,再在 FaaS 上部署对应的函数,这样用户请求的 path,对应的就是每个单独的函数。通过这种方式,就将运维操作转移到了 FaaS 平台,前端同学开发服务端渲染应用,就再也不用关心服务端程序的运维部署了。并且在 FaaS 平台中运行的函数,天然具有弹性伸缩的能力,你也不用担心流量波峰波谷了。</p>
<p data-nodeid="1100"><img src="https://s0.lgstatic.com/i/image/M00/94/46/CgqCHmAXxluARkcHAAF-S8PNwUE730.png" alt="Drawing 1.png" data-nodeid="1237"></p>
<div data-nodeid="1101"><p style="text-align:center">基于 Serverless 的服务选渲染架构</p></div>
<p data-nodeid="1102">如图所示,FaaS 函数接收请求后直接执行代码渲染出 HTML 并返回给浏览器,这是最基本的架构,虽然它可以满足大部分场景,但要追求极致的性能,你通常要加入缓存。</p>
<p data-nodeid="1103"><img src="https://s0.lgstatic.com/i/image/M00/94/3B/Ciqc1GAXxmOATGYqAAGjC4CgYTw981.png" alt="Drawing 2.png" data-nodeid="1241"></p>
<div data-nodeid="1104"><p style="text-align:center">进阶版基于 Serverless 的服务端渲染架构</p></div>
<p data-nodeid="1105">首先我们会使用 CDN 做缓存,基于 CDN 的缓存可以减少函数执行次数,进而避免函数冷启动带来的性能损耗。如果 CDN 中没有 SSR HTML 页面的缓存,则继续由网关处理请求,网关再去触发函数执行。</p>
<p data-nodeid="1106">函数首先会判读缓存数据库中是否有 SSR HTML 的缓存,如果有直接返回;如果没有再渲染出 HTML 并返回。基于数据库的缓存,可以减少函数渲染 HTML 的时间,从而页面加载提升性能。</p>
<p data-nodeid="1107">讲了这么多,具体怎么基于 Serverless 实现一个服务端渲染应用呢?</p>
<h3 data-nodeid="1108">实现一个 Serverless 的服务端渲染应用</h3>
<p data-nodeid="1109">在 16 讲中,我们实现了一个内容管理系统的 Restful API,但没有前端界面,所以今天我们的目标就基于 Serverless 实现一个内容管理系统的前端界面(如图所示)。</p>
<p data-nodeid="1110"><img src="https://s0.lgstatic.com/i/image/M00/94/3B/Ciqc1GAXxoiANTROADtU9yybMQY209.gif" alt="ssr.gif" data-nodeid="1249"></p>
<p data-nodeid="1111">该应用主要包含两个页面:</p>
<ul data-nodeid="1112">
<li data-nodeid="1113">
<p data-nodeid="1114">首页,展示文章列表;</p>
</li>
<li data-nodeid="1115">
<p data-nodeid="1116">详情页,展示文章详情。</p>
</li>
</ul>
<p data-nodeid="1117">为了方便你进行实践,我为你提供了一份示例代码,你可以直接下载并使用:</p>
<pre class="lang-java" data-nodeid="1118"><code data-language="java"># 下载代码
$ git clone https://github.com/nodejh/serverless-class
# 进入服务端渲染应用目录
$ cd 16/serverless-ssr-cms
</code></pre>
<p data-nodeid="1119">代码结构如下:</p>
<pre class="lang-java" data-nodeid="1120"><code data-language="java">.
├── config.js
├── f.yml
├── <span class="hljs-keyword">package</span>-lock.json
├── <span class="hljs-keyword">package</span>.json
├── src
│ ├── api.ts
│ ├── config
│ │ └── config.<span class="hljs-keyword">default</span>.ts
│ ├── configuration.ts
│ ├── index.ts
│ ├── <span class="hljs-class"><span class="hljs-keyword">interface</span>
│ │ ├── <span class="hljs-title">detail</span>.<span class="hljs-title">ts</span>
│ │ └── <span class="hljs-title">index</span>.<span class="hljs-title">ts</span>
│ ├── <span class="hljs-title">mock</span>
│ │ ├── <span class="hljs-title">detail</span>.<span class="hljs-title">ts</span>
│ │ └── <span class="hljs-title">index</span>.<span class="hljs-title">ts</span>
│ ├── <span class="hljs-title">render</span>.<span class="hljs-title">ts</span>
│ └── <span class="hljs-title">service</span>
│ ├── <span class="hljs-title">detail</span>.<span class="hljs-title">ts</span>
│ └── <span class="hljs-title">index</span>.<span class="hljs-title">ts</span>
├── <span class="hljs-title">tsconfig</span>.<span class="hljs-title">json</span>
├── <span class="hljs-title">tsconfig</span>.<span class="hljs-title">lint</span>.<span class="hljs-title">json</span>
└── <span class="hljs-title">web</span>
├── @<span class="hljs-title">types</span>
│ └── <span class="hljs-title">global</span>.<span class="hljs-title">d</span>.<span class="hljs-title">ts</span>
├── <span class="hljs-title">common</span>.<span class="hljs-title">less</span>
├── <span class="hljs-title">components</span>
│ ├── <span class="hljs-title">layout</span>
│ │ ├── <span class="hljs-title">index</span>.<span class="hljs-title">less</span>
│ │ └── <span class="hljs-title">index</span>.<span class="hljs-title">tsx</span>
│ └── <span class="hljs-title">title</span>
│ ├── <span class="hljs-title">index</span>.<span class="hljs-title">less</span>
│ └── <span class="hljs-title">index</span>.<span class="hljs-title">tsx</span>
├── <span class="hljs-title">interface</span>
│ ├── <span class="hljs-title">detail</span>-<span class="hljs-title">index</span>.<span class="hljs-title">ts</span>
│ ├── <span class="hljs-title">index</span>.<span class="hljs-title">ts</span>
│ └── <span class="hljs-title">page</span>-<span class="hljs-title">index</span>.<span class="hljs-title">ts</span>
├── <span class="hljs-title">pages</span>
│ ├── <span class="hljs-title">detail</span>
│ │ ├── <span class="hljs-title">fetch</span>.<span class="hljs-title">ts</span>
│ │ ├── <span class="hljs-title">index</span>.<span class="hljs-title">less</span>
│ │ └── <span class="hljs-title">render</span>$<span class="hljs-title">id</span>.<span class="hljs-title">tsx</span>
│ └── <span class="hljs-title">index</span>
│ ├── <span class="hljs-title">fetch</span>.<span class="hljs-title">ts</span>
│ ├── <span class="hljs-title">index</span>.<span class="hljs-title">less</span>
│ └── <span class="hljs-title">render</span>.<span class="hljs-title">tsx</span>
└── <span class="hljs-title">tsconfig</span>.<span class="hljs-title">json</span>
</span></code></pre>
<p data-nodeid="1121">文件很多,不过不用担心,你只需重点关注 web/pages/ 和 src/service 两个目录:</p>
<ul data-nodeid="1122">
<li data-nodeid="1123">
<p data-nodeid="1124">web/ 目录中主要是前端页面的代码, web/pages/ 中的文件分别对应着我们要实现的 index(首页)和 detail(详情页)两个页面,这两个页面会使用到 components 目录中的公共组件;</p>
</li>
<li data-nodeid="1125">
<p data-nodeid="1126">src/ 目录中主要是后端代码,src/service 目录中的 index.ts 和 detail.ts 则定义了两个页面分别需要用到的接口,为了简单起见,接口数据我使用了 src/mock/ 目录中的 mock 数据。</p>
</li>
</ul>
<p data-nodeid="1127">当我一个人又负责前端页面也负责后端接口的开发时,通常习惯先实现接口,再开发前端页面,这样方便调试。接下来就让我们看一下具体是怎么实现的。</p>
<h4 data-nodeid="1128">首页接口的实现</h4>
<p data-nodeid="1129">其源码在 src/service/index.ts 文件中,代码如下:</p>
<pre class="lang-typescript" data-nodeid="1130"><code data-language="typescript"><span class="hljs-comment">// src/service/index.ts</span>
<span class="hljs-keyword">import</span> { provide } <span class="hljs-keyword">from</span> <span class="hljs-string">'@midwayjs/faas'</span>
<span class="hljs-keyword">import</span> { IApiService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../interface'</span>
<span class="hljs-keyword">import</span> mock <span class="hljs-keyword">from</span> <span class="hljs-string">'../mock'</span>
<span class="hljs-meta">@provide</span>(<span class="hljs-string">'ApiService'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ApiService <span class="hljs-keyword">implements</span> IApiService {
<span class="hljs-keyword">async</span> index (): <span class="hljs-built_in">Promise</span><<span class="hljs-built_in">any</span>> {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.resolve(mock)
}
}
</code></pre>
<p data-nodeid="1131">这段代码实现了一个 ApiService 类以及 index 方法,该方法会返回首页的文章列表。数据结构如下:</p>
<pre class="lang-json" data-nodeid="1132"><code data-language="json">{
<span class="hljs-attr">"data"</span>:[
{
<span class="hljs-attr">"id"</span>:<span class="hljs-string">"3f8a198c-60a2-11eb-8932-9b95cd7afc2d"</span>,
<span class="hljs-attr">"title"</span>:<span class="hljs-string">"开篇词:Serverless 大热,程序员面临的新机遇与挑战"</span>,
<span class="hljs-attr">"content"</span>:<span class="hljs-string">"可能你会认为 Serverless 是最近两年兴起的技术......"</span>,
<span class="hljs-attr">"date"</span>:<span class="hljs-string">"2020-12-23"</span>
},
{
<span class="hljs-attr">"id"</span>:<span class="hljs-string">"5158b100-5fee-11eb-9afa-9b5f85523067"</span>,
<span class="hljs-attr">"title"</span>:<span class="hljs-string">"基础入门:编写你的第一个 Serverless 应用"</span>,
<span class="hljs-attr">"content"</span>:<span class="hljs-string">"学习一门新技术,除了了解其基础概念,更重要的是把理论转化为实践..."</span>,
<span class="hljs-attr">"date"</span>:<span class="hljs-string">"2020-12-29"</span>
}
]
}
</code></pre>
<p data-nodeid="1133">在进行服务端渲染时,你可以通过 ctx 获取到 ApiService 实例,进而调用其中的方法,获取文章列表数据。此外,ApiService 也会被 src/api.ts 调用,src/api.ts 则直接对外提供了 HTTP 接口。</p>
<h4 data-nodeid="1134">首页页面的实现</h4>
<p data-nodeid="1135">有了接口后,我们就可以继续实现首页的前端页面了。首页页面的代码在 web/pages/ 目录中,该目录下有三个文件:</p>
<ul data-nodeid="1136">
<li data-nodeid="1137">
<p data-nodeid="1138">fetch.ts,获取首页数据;</p>
</li>
<li data-nodeid="1139">
<p data-nodeid="1140">render.tsx 首页页面 UI 组件代码;</p>
</li>
<li data-nodeid="1141">
<p data-nodeid="1142">index.less 样式代码。</p>
</li>
</ul>
<p data-nodeid="1143">首先来看一下 fetch.ts:</p>
<pre class="lang-typescript" data-nodeid="1144"><code data-language="typescript"><span class="hljs-comment">// web/pages/index/fetch.ts</span>
<span class="hljs-keyword">import</span> { IFaaSContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'ssr-types'</span>
<span class="hljs-keyword">import</span> { IndexData } <span class="hljs-keyword">from</span> <span class="hljs-string">'@/interface'</span>
<span class="hljs-keyword">interface</span> IApiService {
index: <span class="hljs-function"><span class="hljs-params">()</span> =></span> <span class="hljs-built_in">Promise</span><IndexData>
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> (ctx: IFaaSContext<{
apiService?: IApiService
}>) => {
<span class="hljs-keyword">const</span> data = __isBrowser__ ? <span class="hljs-keyword">await</span> (<span class="hljs-keyword">await</span> <span class="hljs-built_in">window</span>.fetch(<span class="hljs-string">'/api/index'</span>)).json() : <span class="hljs-keyword">await</span> ctx.apiService?.index()
<span class="hljs-keyword">return</span> {
indexData: data
}
}
</code></pre>
<p data-nodeid="1145"><strong data-nodeid="1277">这段代码的逻辑比较简单,核心点在第 10 行</strong>,如果是浏览器,就用浏览器自带的 fetch 方法请求<code data-backticks="1" data-nodeid="1273">/api/index</code>接口获取数据;如果不是浏览器,即服务端渲染,可以直接调用 apiService 中的 index 方法。获取到数据后,将其存入 state.indexData 中,这样在 UI 组件中就可以使用了。<br>
首页的 UI 组件 render.tsx 代码如下:</p>
<pre class="lang-javascript" data-nodeid="1146"><code data-language="javascript"><span class="hljs-comment">// web/pages/index/render.tsx</span>
<span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { SProps, IContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"ssr-types"</span>;
<span class="hljs-keyword">import</span> Navbar <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/navbar"</span>;
<span class="hljs-keyword">import</span> Header <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/header"</span>;
<span class="hljs-keyword">import</span> Item <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/item"</span>;
<span class="hljs-keyword">import</span> { IData } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/interface"</span>;
<span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"./index.less"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> (props: SProps) => {
<span class="hljs-keyword">const</span> { state } = useContext<IContext<IData>>(<span class="hljs-built_in">window</span>.STORE_CONTEXT);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Navbar</span> {<span class="hljs-attr">...props</span>} <span class="hljs-attr">isHomePage</span>=<span class="hljs-string">{true}</span>></span><span class="hljs-tag"></<span class="hljs-name">Navbar</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Header</span>></span><span class="hljs-tag"></<span class="hljs-name">Header</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.container}</span>></span>
{state?.indexData?.data.map((item) => (
<span class="hljs-tag"><<span class="hljs-name">Item</span>
{<span class="hljs-attr">...props</span>}
<span class="hljs-attr">id</span>=<span class="hljs-string">{item.id}</span>
<span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span>
<span class="hljs-attr">title</span>=<span class="hljs-string">{item.title}</span>
<span class="hljs-attr">content</span>=<span class="hljs-string">{item.content}</span>
<span class="hljs-attr">date</span>=<span class="hljs-string">{item.date}</span>
></span><span class="hljs-tag"></<span class="hljs-name">Item</span>></span>
))}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
};
</code></pre>
<p data-nodeid="1147">在 UI 组件中,我们可以通过 useContext 获取刚才由 fetch.ts 存入 state 的数据,然后利用数据渲染 UI。UI 组件主要由三部分组成。</p>
<ul data-nodeid="1148">
<li data-nodeid="1149">
<p data-nodeid="1150">Navbar:导航条。</p>
</li>
<li data-nodeid="1151">
<p data-nodeid="1152">Header:页面标题。</p>
</li>
<li data-nodeid="1153">
<p data-nodeid="1154">Item:每篇文章的简介。</p>
</li>
</ul>
<p data-nodeid="1155"><img src="https://s0.lgstatic.com/i/image/M00/94/46/CgqCHmAXx1WAV0BxAAM5rls-jc4377.png" alt="Drawing 4.png" data-nodeid="1284"></p>
<h4 data-nodeid="1156">详情页接口的实现</h4>
<p data-nodeid="1157">完成了首页后,就可以实现详情页了。详情页与首页整体类似,区别就在于详情页需要传入参数查询某条数据。</p>
<p data-nodeid="1158">详情页接口在 src/service/detail.ts 中 ,代码如下所示:</p>
<pre class="lang-typescript" data-nodeid="1159"><code data-language="typescript"><span class="hljs-comment">// src/service/detail.ts</span>
<span class="hljs-keyword">import</span> { provide } <span class="hljs-keyword">from</span> <span class="hljs-string">'@midwayjs/faas'</span>
<span class="hljs-keyword">import</span> { IApiDetailService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../interface/detail'</span>
<span class="hljs-keyword">import</span> mock <span class="hljs-keyword">from</span> <span class="hljs-string">'../mock/detail'</span>
<span class="hljs-meta">@provide</span>(<span class="hljs-string">'ApiDetailService'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ApiDetailService <span class="hljs-keyword">implements</span> IApiDetailService {
<span class="hljs-keyword">async</span> index (id): <span class="hljs-built_in">Promise</span><<span class="hljs-built_in">any</span>> {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.resolve(mock.data[id])
}
}
</code></pre>
<p data-nodeid="1160">在这段代码中,我们实现了一个 ApiDetailService 类以及 index 方法,index 方法的如参 id 即文章 ID,然后根据文章 ID 从 mock 数据中查询文章详情。</p>
<p data-nodeid="1161">文章详情数据如下:</p>
<pre class="lang-json" data-nodeid="1162"><code data-language="json">{
<span class="hljs-attr">"title"</span>:<span class="hljs-string">"Serverless 大热,程序员面临的新机遇与挑战"</span>,
<span class="hljs-attr">"wordCount"</span>:<span class="hljs-number">2540</span>,
<span class="hljs-attr">"readingTime"</span>:<span class="hljs-number">10</span>,
<span class="hljs-attr">"date"</span>:<span class="hljs-string">"2020-12-23 12:00:00"</span>,
<span class="hljs-attr">"content"</span>:<span class="hljs-string">"可能你会认为 Serverless 是最近两年兴起的技术,实际上,Serverless 概念从 2012 年就提出来了,随后 AWS 在 2014 年推出了第一款 Serverless 产品 Lambda,开启了 Serverless 元年... "</span>
}
</code></pre>
<h4 data-nodeid="1163">详情页页面的实现</h4>
<p data-nodeid="1164">和首页一样,详情页也包含数据请求、UI 组件和样式代码三个文件。</p>
<p data-nodeid="1165">数据请求代码文件的命名和首页一样,都是 fetch.ts。与首页不同的是,详情页我们需要从上下文(服务端渲染场景)或 URL 中(浏览器场景)获取到文章 ID,然后根据文章 ID 获取文章详情数据。代码如下:</p>
<pre class="lang-typescript" data-nodeid="1166"><code data-language="typescript"><span class="hljs-keyword">import</span> { RouteComponentProps } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> (ctx) => {
<span class="hljs-keyword">let</span> data;
<span class="hljs-keyword">if</span> (__isBrowser__) {
<span class="hljs-keyword">const</span> id = (ctx <span class="hljs-keyword">as</span> RouteComponentProps<{ id: <span class="hljs-built_in">string</span> }>).match.params.id;
data = <span class="hljs-keyword">await</span> (<span class="hljs-keyword">await</span> <span class="hljs-built_in">window</span>.fetch(<span class="hljs-string">`/api/detail/<span class="hljs-subst">${id}</span>`</span>)).json()
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">const</span> id = <span class="hljs-regexp">/detail\/(.*)(\?|\/)?/</span>.exec(ctx.req.path)[<span class="hljs-number">1</span>];
data = <span class="hljs-keyword">await</span> ctx.apiDeatilservice.index(id);
}
<span class="hljs-keyword">return</span> {
detailData: data,
};
};
</code></pre>
<p data-nodeid="1167">详情页的 UI 组件名称为<code data-backticks="1" data-nodeid="1294">render$id.tsx</code>的文件,<code data-backticks="1" data-nodeid="1296">$id</code>表示该组件的参数是 id,这样访问 /detail/ 这个路由(id 是变量)时,就会匹配到 web/pages/detail/render$id.tsx 这个页面了。</p>
<p data-nodeid="1168"><br>
<code data-backticks="1" data-nodeid="1300">render$id.tsx</code>详细代码如下:</p>
<pre class="lang-javascript" data-nodeid="1169"><code data-language="javascript"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { IContext, SProps } <span class="hljs-keyword">from</span> <span class="hljs-string">"ssr-types"</span>;
<span class="hljs-keyword">import</span> { Data } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/interface"</span>;
<span class="hljs-keyword">import</span> Navbar <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/navbar"</span>;
<span class="hljs-keyword">import</span> Content <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/content"</span>;
<span class="hljs-keyword">import</span> Title <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/title"</span>;
<span class="hljs-keyword">import</span> Tip <span class="hljs-keyword">from</span> <span class="hljs-string">"@/components/tip"</span>;
<span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"./index.less"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> (props: SProps) => {
<span class="hljs-keyword">const</span> { state } = useContext<IContext<Data>>(<span class="hljs-built_in">window</span>.STORE_CONTEXT);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Navbar</span> {<span class="hljs-attr">...props</span>}></span><span class="hljs-tag"></<span class="hljs-name">Navbar</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.container}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Title</span>></span>{state?.detailData?.title}<span class="hljs-tag"></<span class="hljs-name">Title</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Tip</span>
<span class="hljs-attr">date</span>=<span class="hljs-string">{state?.detailData?.date}</span>
<span class="hljs-attr">wordCount</span>=<span class="hljs-string">{state?.detailData?.wordCount}</span>
<span class="hljs-attr">readingTime</span>=<span class="hljs-string">{state?.detailData?.readingTime}</span>
/></span>
<span class="hljs-tag"><<span class="hljs-name">Content</span>></span>{state?.detailData?.content}<span class="hljs-tag"></<span class="hljs-name">Content</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
};
</code></pre>
<p data-nodeid="1170">详情页的 UI 组件由四部分组成。</p>
<ul data-nodeid="1171">
<li data-nodeid="1172">
<p data-nodeid="1173">Navbar:导航条。</p>
</li>
<li data-nodeid="1174">
<p data-nodeid="1175">Title:文章标题。</p>
</li>
<li data-nodeid="1176">
<p data-nodeid="1177">Tip:文章发布时间、字数等提示。</p>
</li>
<li data-nodeid="1178">
<p data-nodeid="1179">Content:文章内容。</p>
</li>
</ul>
<p data-nodeid="1180"><img src="https://s0.lgstatic.com/i/image/M00/94/3B/Ciqc1GAXx3GADE4AAAO-vJ2TBH0389.png" alt="Drawing 5.png" data-nodeid="1309"></p>
<h4 data-nodeid="1181">应用部署</h4>
<p data-nodeid="1182">代码开发完成后,你可以通过下面的命令在本地启动应用:</p>
<pre class="lang-java" data-nodeid="1183"><code data-language="java">$ npm start
...
[HPM] Proxy created: /asset-manifest -> http:<span class="hljs-comment">//127.0.0.1:8000</span>
Server is listening on http:<span class="hljs-comment">//localhost:3000</span>
</code></pre>
<p data-nodeid="1184">应用启动后就可以打开浏览器输入 <a href="http://localhost:3000" data-nodeid="1315">http://localhost:3000</a> 查看效果了。<br>
在本地开发测试完成后,接下来就需要将其部署到函数计算。你可以运行 npm run deploy 命令进部署:</p>
<pre class="lang-java" data-nodeid="1185"><code data-language="java">$ npm run deploy
...
service serverless-ssr-cms deploy success
......
The assigned temporary domain is http:<span class="hljs-comment">//41506101-1457216987974698.test.functioncompute.com,expired at 2021-02-04 00:35:01, limited by 1000 per day.</span>
......
Deploy success
</code></pre>
<p data-nodeid="1186"><code data-backticks="1" data-nodeid="1319">npm run deploy</code>其实是执行了构建代码和部署应用两个步骤,这两个步骤都是在本机执行的。但这就存在一个隐藏风险,如果团队同学本地开发环境不同,就可能导致构建产物不同,进而导致部署到线上的代码存在风险。<strong data-nodeid="1324">所以更好的实践是:实现一个业务的持续集成流程,统一构建部署。</strong></p>
<p data-nodeid="1187">应用部署成功后,会自动创建一个测试的域名,例如<a href="http://41506101-1457216987974698.test.functioncompute.com" data-nodeid="1328">http://41506101-1457216987974698.test.functioncompute.com</a>,我们可以打开该域名查看最终效果。</p>
<p data-nodeid="1188">讲到这儿,基于 Serverless 的服务端渲染应用就开发完成了。</p>
<h3 data-nodeid="1189">总结</h3>
<p data-nodeid="2149">总的来说,基于 Serverless 的服务端渲染应用实现也比较简单。如果你想要追求更好的用户体验,我也建议你对核心业务做服务端渲染的优化。基于 Serverless 的服务端渲染,可以让我们不用再像以前一样担心服务器的运维和扩容,大大提高了生产力。同时有了服务端渲染后,我也建议你完善业务的持续集成流程,将整个研发链路打通,降低代码构建发布的风险,提升从开发到测试再到部署的效率。</p>
<p data-nodeid="2150" class="te-preview-highlight"><img src="https://s0.lgstatic.com/i/image6/M00/04/7F/CioPOWAsxEeANlL-AAEkPyzgS2s711.png" alt="玩转 Serverless 架构17金句.png" data-nodeid="2154"></p>
<p data-nodeid="1880">当然,要达到页面的极致体验,我们还需要做很多工作,比如:</p>
<ul data-nodeid="1192">
<li data-nodeid="1193">
<p data-nodeid="1194">将静态资源部署到 CDN,提升资源加载速度;</p>
</li>
<li data-nodeid="1195">
<p data-nodeid="1196">针对页面进行缓存,减少函数冷启动对性能的影响;</p>
</li>
<li data-nodeid="1197">
<p data-nodeid="1198">对服务端异常进行降级处理等等。</p>
</li>
</ul>
<p data-nodeid="1199">但不管我们用不用 Serverless,都需要做这些工作。关于这一讲,我想要强调以下几点:</p>
<ul data-nodeid="1200">
<li data-nodeid="1201">
<p data-nodeid="1202">基于 Serverless 的服务端渲染应用,可以让我们不用关心服务器的运维,应用也天然具有弹性;</p>
</li>
<li data-nodeid="1203">
<p data-nodeid="1204">基于 Serverless 开发服务端渲染应用,建议你完善业务的持续集成流程;</p>
</li>
<li data-nodeid="1205">
<p data-nodeid="1206">要达到页面的极致性能,还需要考虑将静态资源部署到 CDN、对页面进行缓存等技术;</p>
</li>
<li data-nodeid="1207">
<p data-nodeid="1208">对于服务端渲染应用,建议你完善业务的服务降级能力,进一步提高稳定性。</p>
</li>
</ul>
<p data-nodeid="1209" class="">最后,我给你的作业是,实现一个服务端渲染应用。 我们下一讲见。</p>
---
### 精选评论
|
Markdown
|
UTF-8
| 1,218
| 3.015625
| 3
|
[] |
no_license
|
# ToyRobot
This is a happy path implementation of the [Toy Robot Problem](PROBLEM.md) written in Elixir.
## Compiling and running
Before starting ensure that you have the correct versions of Elixir and Erlang availble
```
elixir 1.12.2-otp-24
erlang 24.0.3
```
Tests can be run with with the following command
```
mix test
```
The script can be compiled with the following command
```
mix escript.build
```
This will create the `toy_robot` binary in the root directory.
This can be run by passing quoted commands separated by the `|` symbol to the flag `--commands` flag. `-c` is also accepted.
```
./toy_robot -c "PLACE 0,0,NORTH|MOVE|REPORT"
=> 0,1,NORTH
```
### Improvements
- The `call` function defined in the modules that give the toy robot behaviour could use better names.
- It would be good to separate the `Turn.call` into a `left` and `right` function to save passing in the command string.
- Also I would liek to look at a smarter way of changing the facing than just overloading the private function `Turn.turn` 8 times.
- Adding a flag that lets the user load commands from a file would be good.
- Accounting for unhappy paths, sucj as passing no commands or invalid commands would be good.
|
JavaScript
|
UTF-8
| 9,802
| 2.640625
| 3
|
[] |
no_license
|
var command_queue = [];
var action_queue = [];
var refresh_event = 100;
//===========================
// CORE: handle socket 'n update event queue
//===========================
function Core(socket, images, init) {
this.socket = socket;
this.images = images;
this.init = init;
this.modules = {
map: new MapData(this),
players: new PlayersData(this),
animations: new AnimationData(this)
};
var _this = this;
/* setInterval(function () {
while (action_queue.length > 0) {
_this.socket.emit('rts', action_queue.pop());
}
}, refresh_event);*/
}
function execute(modules, cmd) {
for (var name in modules) {
modules[name].applyListeners(cmd);
}
}
function startClient(host, images, init) {
console.log("start client on " + host);
var socket = io.connect(host);
var core = new Core(socket, images, init);
socket.on('commands', function (data) {
if (data == "BIENVENUE")
socket.emit('commands', "GRAPHIC\n");
else {
execute(core.modules, parseCommand(data))
}
});
}
//===========================
// LISTENER
//===========================
function Listener(name, foo) {
this.name = name;
this.foo = foo;
}
Listener.prototype.incorporate = function (obj, cmd) {
this.foo(obj, cmd);
};
//===========================
// MODULE: base class
//===========================
function Module(father, name) {
this.father = father;
this.name = name;
this.listeners = [];
}
Module.prototype.applyListeners = function (cmd) {
for (var i = 0; i < this.listeners.length; i++) {
if (this.listeners[i].name == cmd.name) {
this.listeners[i].incorporate(this, cmd);
}
}
};
////////////////////////////////////////
// MAP: module n' listeners
////////////////////////////////////////
function MapData(father) {
Module.call(this, father, "map");
this.size = {x: 0, y: 0};
this.tile = [];
var _this = this;
this.listeners.push(new Listener("bct", function (obj, cmd) {
if (cmd.args.length == 9) {
var x = parseInt(cmd.args[0], 10);
var y = parseInt(cmd.args[1], 10);
var content = {
'food': parseInt(cmd.args[2], 10),
'linemate': parseInt(cmd.args[3], 10),
'deraumere': parseInt(cmd.args[4], 10),
'sibur': parseInt(cmd.args[5], 10),
'mendiane': parseInt(cmd.args[6], 10),
'phiras': parseInt(cmd.args[7], 10),
'thystame': parseInt(cmd.args[8], 10)
};
obj.tile[y * obj.size.x + x] = content;
if (_this.father.graphical !== undefined)
_this.father.graphical.map.setTile(x, y, content);
}
else {
throw "MissingCommand";
}
}));
this.listeners.push(new Listener("msz", function (obj, cmd) {
if (cmd.args.length == 2) {
obj.size.x = parseInt(cmd.args[0], 10);
obj.size.y = parseInt(cmd.args[1], 10);
if (obj.size.x * obj.size.y > 10000) {
loader.addAlert("<b>Warning:</b> The map is huge (" + obj.size.x + "x" + obj.size.y + ")");
if (!confirm('Do you really want to show this game?')) {
loader.addAlert("<b>Info:</b> Drawing cancel.");
return;
}
}
_this.father.graphical = _this.father.init(_this.father, _this.father.images, obj.size);
}
else
throw "MissingCommand";
}));
}
MapData.prototype = new Module();
MapData.prototype.constructor = MapData;
//////////////////////////////////////////
// PLAYERS: module n' listeners
//////////////////////////////////////////
function PlayersData(father) {
Module.call(this, father, "players");
this.teams = [];
this.players = [];
var _this = this;
this.listeners.push(new Listener("tna", function (obj, cmd) {
if (cmd.args.length > 0) {
var name = cmd.args.join(" ");
for (var i = 0; i < obj.teams.length; i++) {
if (obj.teams[i] == name)
return;
}
obj.teams.push(name);
console.log(name);
_this.father.graphical.map.addTeam(name);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pdi", function (obj, cmd) {
if (cmd.args.length == 1) {
var id = getClientId(cmd.args[0]);
_this.father.graphical.map.removePlayer(id);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pnw", function (obj, cmd) {
if (cmd.args.length >= 6) {
var pl = {
'id': getClientId(cmd.args[0]),
'pos': {x: parseInt(cmd.args[1], 10), y: parseInt(cmd.args[2], 10)},
'direction': parseInt(cmd.args[3], 10),
'level': parseInt(cmd.args[4], 10),
'team': cmd.args.slice(5).join(" "),
'inventory': []
};
for (var i = 0; i < obj.players.length; i++) {
if (obj.players[i].id == pl.id) {
obj.players[i] = pl;
return;
}
}
obj.players.push(pl);
_this.father.graphical.map.eclosion(pl.team, pl.id, pl.pos, pl.direction);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pgt", function (obj, cmd) {
if (cmd.args.length == 2) {
var id = getClientId(cmd.args[0]);
var type = parseInt(cmd.args[1], 10);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pdr", function (obj, cmd) {
if (cmd.args.length == 2) {
var id = getClientId(cmd.args[0]);
var type = parseInt(cmd.args[1], 10);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pex", function (obj, cmd) {
if (cmd.args.length == 1) {
var id = getClientId(cmd.args[0]);
_this.father.graphical.map.expulse(id);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("ppo", function (obj, cmd) {
if (cmd.args.length == 4) {
var id = getClientId(cmd.args[0]);
for (var i = 0; i < obj.players.length; i++) {
if (obj.players[i].id == id) {
obj.players[i].pos.x = parseInt(cmd.args[1], 10);
obj.players[i].pos.y = parseInt(cmd.args[2], 10);
obj.players[i].direction = parseInt(cmd.args[3], 10);
_this.father.graphical.map.movePlayer(obj.players[i].id, obj.players[i].pos.x, obj.players[i].pos.y, obj.players[i].direction);
return;
}
}
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("plv", function (obj, cmd) {
if (cmd.args.length == 2) {
var id = getClientId(cmd.args[0]);
for (var i = 0; i < obj.players.length; i++) {
if (obj.players[i].id == id) {
obj.players[i].level = parseInt(cmd.args[1], 10);
return;
}
}
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pin", function (obj, cmd) {
if (cmd.args.length == 10) {
var id = getClientId(cmd.args[0]);
for (var i = 0; i < obj.players.length; i++) {
if (obj.players[i].id == id) {
obj.players[i].inventory = {
'food': parseInt(cmd.args[3], 10),
'linemate': parseInt(cmd.args[4], 10),
'deraumere': parseInt(cmd.args[5], 10),
'sibur': parseInt(cmd.args[6], 10),
'mendiane': parseInt(cmd.args[7], 10),
'phiras': parseInt(cmd.args[8], 10),
'thystame': parseInt(cmd.args[9], 10)
};
return;
}
}
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pbc", function (obj, cmd) {
if (cmd.args.length >= 2) {
var id = getClientId(cmd.args[0]);
_this.father.graphical.map.broadcast(id, cmd.args.slice(1).join(" "));
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("enw", function (obj, cmd) {
if (cmd.args.length == 4) {
var id = getClientId(cmd.args[0]);
var pl_id = parseInt(cmd.args[1], 10);
var pos = {
x: parseInt(cmd.args[2], 10),
y: parseInt(cmd.args[3], 10)
};
_this.father.graphical.map.addEggs(pos, id, pl_id);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("eht", function (obj, cmd) {
if (cmd.args.length == 1) {
var id = getClientId(cmd.args[0]);
//_this.father.graphical.map.eclosion(id);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pie", function (obj, cmd) {
if (cmd.args.length == 3) {
var pos = {
x: parseInt(cmd.args[0], 10),
y: parseInt(cmd.args[1], 10)
};
var stat = parseInt(cmd.args[2], 10);
_this.father.graphical.map.addIncante(pos, stat);
}
else
throw "MissingCommand";
}));
this.listeners.push(new Listener("pic", function (obj, cmd) {
if (cmd.args.length >= 4) {
var pos = {
x: parseInt(cmd.args[0], 10),
y: parseInt(cmd.args[1], 10)
};
var lvl = parseInt(cmd.args[2], 10);
_this.father.graphical.map.addIncanteTell(pos, lvl);
}
else
throw "MissingCommand";
}));
}
PlayersData.prototype = new Module();
PlayersData.prototype.constructor = PlayersData;
//////////////////////////////////////////
// ANIMATION: module n' listeners
// each cmd is push in a queue: this
// is the actions you should animate
//////////////////////////////////////////
function AnimationData(father) {
Module.call(this, father, "animation");
this.queue = [];
var actions = ['plv', 'ppo', 'pex', 'pbc', 'pic', 'pie', 'pfk', 'pdr', 'pgt', 'pdi', 'eht', 'enw', 'ebo', 'edi', 'seg'];
for (var i = 0; i < actions.length; i++) {
this.listeners.push(new Listener(actions[i], function (obj, cmd) {
obj.queue.push(cmd);
}));
}
}
AnimationData.prototype = new Module();
AnimationData.prototype.constructor = AnimationData;
//////////////////////////////////////////
// ACTIONS: module n'emitters
//////////////////////////////////////////
/*
function Actions() {
call(this, "actions");
}
Actions.prototype = new Module();
Actions.prototype.constructor = Actions;
Actions.prototype.move = function (x, y) {
action_queue.push({action: 'ppo', args: })
}
*/
//===========================
// UTILS
//===========================
function parseCommand(data) {
var elms = data.split(" ");
return ({name: elms[0], args: elms.slice(1)});
}
function getClientId(str) {
if (str.length >= 1) {
return (parseInt(str, 10));
}
else
throw "NotAClientId";
}
|
Python
|
UTF-8
| 5,429
| 2.6875
| 3
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
import torch
from torch import nn
from torchtuples import tuplefy
def init_embedding(emb):
"""Weight initialization of embeddings (in place).
Best practise from fastai
Arguments:
emb {torch.nn.Embedding} -- Embedding
"""
w = emb.weight.data
sc = 2 / (w.shape[1]+1)
w.uniform_(-sc, sc)
def _accuracy(input, target):
"""Accuracy, i.e. mean(input == target)"""
return input.eq(target.view_as(input)).float().mean()
def accuracy_binary(input, target):
"""Accuracy for binary models on input for logit models in (-inf, inf).
Do not used for models with sigmoid output activation.
"""
if len(input.shape) == 1:
raise NotImplementedError(f"`accuracy_argmax` not implemented for shape {input.shape}")
assert (target.min() == 0) and (target.max() == 1), 'We have binary classfication so we need 0/1'
pred = torch.zeros_like(input).to(target.dtype)
pred[input >= 0.] = 1
return _accuracy(pred, target)
def accuracy_argmax(input, target):
"""Accuracy after argmax on input for logit models in (-inf, inf).
Do not used for models with sigmoid/softmax output activation.
Tupycally used as a metric passed to Model.fit()
If input is one dimensional, we assume we have binary classification.
"""
if len(input.shape) == 1:
raise NotImplementedError(f"`accuracy_argmax` not implemented for shape {input.shape}")
if input.shape[1] == 1:
raise NotImplementedError("`accuracy_argmax` not for binary data. See `accuracy_binary` instead.")
else:
pred = input.argmax(dim=1, keepdim=True)
return _accuracy(pred, target)
class DenseVanillaBlock(nn.Module):
def __init__(self, in_features, out_features, bias=True, batch_norm=True, dropout=0., activation=nn.ReLU,
w_init_=lambda w: nn.init.kaiming_normal_(w, nonlinearity='relu')):
super().__init__()
self.linear = nn.Linear(in_features, out_features, bias)
if w_init_:
w_init_(self.linear.weight.data)
self.activation = activation()
self.batch_norm = nn.BatchNorm1d(out_features) if batch_norm else None
self.dropout = nn.Dropout(dropout) if dropout else None
def forward(self, input):
input = self.activation(self.linear(input))
if self.batch_norm:
input = self.batch_norm(input)
if self.dropout:
input = self.dropout(input)
return input
class MLPVanilla(nn.Module):
def __init__(self, in_features, num_nodes, out_features, batch_norm=True, dropout=None, activation=nn.ReLU,
output_activation=None, output_bias=True,
w_init_=lambda w: nn.init.kaiming_normal_(w, nonlinearity='relu')):
super().__init__()
num_nodes = tuplefy(in_features, num_nodes).flatten()
if not hasattr(dropout, '__iter__'):
dropout = [dropout for _ in range(len(num_nodes)-1)]
net = []
for n_in, n_out, p in zip(num_nodes[:-1], num_nodes[1:], dropout):
net.append(DenseVanillaBlock(n_in, n_out, True, batch_norm, p, activation, w_init_))
net.append(nn.Linear(num_nodes[-1], out_features, output_bias))
if output_activation:
net.append(output_activation)
self.net = nn.Sequential(*net)
def forward(self, input):
return self.net(input)
class EntityEmbeddings(nn.Module):
def __init__(self, num_embeddings, embedding_dims, dropout=0.):
super().__init__()
if not hasattr(num_embeddings, '__iter__'):
num_embeddings = [num_embeddings]
if not hasattr(embedding_dims, '__iter__'):
embedding_dims = [embedding_dims]
if len(num_embeddings) != len(embedding_dims):
raise ValueError("Need 'num_embeddings' and 'embedding_dims' to have the same length")
self.embeddings = nn.ModuleList()
for n_emb, emb_dim in zip(num_embeddings, embedding_dims):
emb = nn.Embedding(n_emb, emb_dim)
init_embedding(emb)
self.embeddings.append(emb)
self.dropout = nn.Dropout(dropout) if dropout else None
def forward(self, input):
if input.shape[1] != len(self.embeddings):
raise RuntimeError(f"Got input of shape '{input.shape}', but need dim 1 to be {len(self.embeddings)}.")
input = [emb(input[:, i]) for i, emb in enumerate(self.embeddings)]
input = torch.cat(input, 1)
if self.dropout:
input = self.dropout(input)
return input
class MixedInputMLP(nn.Module):
def __init__(self, in_features, num_embeddings, embedding_dims, num_nodes, out_features,
batch_norm=True, dropout=None, activation=nn.ReLU, dropout_embedding=0.,
output_activation=None, output_bias=True,
w_init_=lambda w: nn.init.kaiming_normal_(w, nonlinearity='relu')):
super().__init__()
self.embeddings = EntityEmbeddings(num_embeddings, embedding_dims, dropout_embedding)
input_mlp = in_features + sum(embedding_dims)
self.mlp = MLPVanilla(input_mlp, num_nodes, out_features, batch_norm, dropout, activation,
output_activation, output_bias, w_init_)
def forward(self, input_numeric, input_categoric):
input = torch.cat([input_numeric, self.embeddings(input_categoric)], 1)
return self.mlp(input)
|
Ruby
|
UTF-8
| 741
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'facter/util/blockdevices/linux'
require 'facter/util/blockdevices/freebsd'
module Facter::Util::Blockdevices
IMPLEMENTATIONS = {
'FreeBSD' => FreeBSD,
'Linux' => Linux
}
module NoImplementation
def self.devices
[]
end
end
def self.implementation
IMPLEMENTATIONS[Facter.value(:kernel)] || NoImplementation
end
def self.devices
implementation.devices
end
def self.device_model(device_name)
implementation.device_model(device_name)
end
def self.device_vendor(device_name)
implementation.device_vendor(device_name)
end
def self.device_size(device_name)
implementation.device_size(device_name)
end
def self.available?
!self.devices.empty?
end
end
|
Markdown
|
UTF-8
| 3,904
| 3.15625
| 3
|
[] |
no_license
|
+++
title = "零和博弈与囚徒困境"
postid = 2488
date = 2016-04-03T10:23:55+08:00
isCJKLanguage = true
toc = false
type = "post"
slug = "zreo-sum-game-and-prisoners-dilemma"
aliases = [ "/post/2488.html",]
category = [ "impressions",]
tag = [ "reading",]
lastmod = 2016-04-03T10:23:55+08:00
attachments = [ "2487",]
+++
![零和博弈][51]
[零和博弈][2]([Zero-sum game][1]),也叫零和游戏。它的原理如下:
> 两人对弈,总会有一个赢,一个输,如果我们把获胜计算为得1分,而输棋为-1分。则若A获胜次数为N,B的失败次数必然也为N。若A失败的次数为M,则B获胜的次数必然为M。这样,A的总分为(N-M),B的总分为(M-N),显然(N-M)+(M-N)=0,这就是零和游戏的数学表达式。
简单的说,在零和博弈中,总有一方是绝对赢家,另一方是绝对输家。 <!--more-->
[囚徒困境][4]([Prisoner's dilemma][3])的原理如下:
> 两个共谋犯罪的人被关入监狱,不能互相沟通情况。如果两个人都不揭发对方,则由于证据不确定,每个人都坐牢一年;若一人揭发,而另一人沉默,则揭发者因为立功而立即获释,沉默者因不合作而入狱五年;若互相揭发,则因证据确实,二者都判刑两年。由于囚徒无法信任对方,因此倾向于互相揭发,而不是同守沉默。
囚徒困境是博弈论的非零和博弈中具代表性的例子,博弈的双方存在“双赢”的可能性。所以,囚徒困境也可能称为“正和博弈”。
扑克是一种零和游戏。从对局的双方来看,只有获胜的一方才能获得最大的利益。但扑克有很多种玩法,起源于“跑得快”玩法的“斗地主”,为什么能从武汉快速传播到全国?就是因为在打法中的“合作双赢”。“斗地主”每一局中需要二人配合对付一人,下一局时互相配合的人又会变化。这促成了一种快速的合作。玩家不但要熟悉合作者的打法和特点,还需要避免自己的特点被他人看透。因为到了下一局,谁也不知道自己是“地主”还是“佃户”。
我们在2015年看到的[滴滴和快的][5]合并、[美团和大众点评][6]合并、[58同城和赶集网][7]合并,都是“双赢”的例子。在资本收紧的寒冬,何必拼个你死我活?不如合在一起有钱大家赚嘛。我甚至在想,会不会哪天Intel和AMD见了个面说:“反正通用CPU现在都过得挺辛苦的,要不就合并吧!一起赚他们的钱呗。X86架构没人做的过我们两家啊。”当然了,美国政府可能不会答应就是了。 :)
企业如此,团队亦是如此。一些大型企业会设置只能类似的多个团队(产品团队),使之互相竞争,从而达到快速高效创新的结果。这种竞争一定不能是零和博弈,否则最终的结果就是两败俱伤。
在职能不同的团队之间,也可能存在竞争关系。例如资源的竞争(多个团队竞争公共资源)、人才的竞争(优秀人才在职能部门之间的流转)等等。团队间唯有互相了解,才能做到共生共赢。
离职的员工和公司之间,也并非对立关系。作为企业,永远不能让员工“负气出走”,要让员工准确理解企业的发展目标和文化,让员工认同企业的理念和观点。即使不能做朋友,也绝不能成为敌人。
**聚是一团火,散作满天星**,就是这个道理。
(全文完)
[1]: https://en.wikipedia.org/wiki/Zero-sum_game
[2]: http://baike.baidu.com/view/196849.htm
[3]: https://en.wikipedia.org/wiki/Prisoner's_dilemma
[4]: http://baike.baidu.com/view/316629.htm
[5]: http://tech.sina.com.cn/z/didikuaidi/
[6]: http://tech.sina.com.cn/zt_d/combine
[7]: http://tech.sina.com.cn/z/58ganji/
[51]: /uploads/2016/04/zero-sum.jpg
|
C#
|
UTF-8
| 1,228
| 2.796875
| 3
|
[
"Unlicense"
] |
permissive
|
using Ryujinx.Graphics.Gal;
using Ryujinx.Graphics.Gal.Shader;
using System;
using System.IO;
namespace Ryujinx.ShaderTools
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 2)
{
GlslDecompiler Decompiler = new GlslDecompiler();
GalShaderType ShaderType = GalShaderType.Vertex;
switch (args[0].ToLower())
{
case "v": ShaderType = GalShaderType.Vertex; break;
case "tc": ShaderType = GalShaderType.TessControl; break;
case "te": ShaderType = GalShaderType.TessEvaluation; break;
case "g": ShaderType = GalShaderType.Geometry; break;
case "f": ShaderType = GalShaderType.Fragment; break;
}
byte[] Binary = File.ReadAllBytes(args[1]);
GlslProgram Program = Decompiler.Decompile(Binary, ShaderType);
Console.WriteLine(Program.Code);
}
else
{
Console.WriteLine("Usage: Ryujinx.ShaderTools [v|tc|te|g|f] shader.bin");
}
}
}
}
|
C++
|
UTF-8
| 441
| 3.328125
| 3
|
[] |
no_license
|
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int i;
int len = nums.size();
for (i = 0; i < len; i++)
if (target <= nums[i])
break;
return i;
}
};
int main()
{
Solution sol;
vector<int> vec = { 1,3,5,6 };
cout << sol.searchInsert(vec, 7) << endl;;
system("pause");
return 0;
}
|
PHP
|
UTF-8
| 757
| 3.46875
| 3
|
[] |
no_license
|
<?php
class Post
{
private $title;
private $text;
public function __construct($title, $text)
{
$this->title = $title;
$this->text = $text;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getText()
{
return $this->text;
}
public function setText($text)
{
$this->text = $text;
}
}
$post = new Post('Lorem ipsum dolor', 'Nunc accumsan in ipsum a mattis...');
// $post->title; //=> Fatal error: Uncaught Error: Cannot access private property Post::$title
var_dump($post->getTitle()); //=> string(17) "Lorem ipsum dolor"
$post->setTitle('Dolor');
var_dump($post->getTitle()); //=> string(5) "Dolor"
|
Java
|
UTF-8
| 963
| 1.945313
| 2
|
[] |
no_license
|
package com.glacier.frame.dao.basicdatas;
import com.glacier.frame.entity.basicdatas.ParSellType;
import com.glacier.frame.entity.basicdatas.ParSellTypeExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ParSellTypeMapper {
int countByExample(ParSellTypeExample example);
int deleteByExample(ParSellTypeExample example);
int deleteByPrimaryKey(String sellTypeId);
int insert(ParSellType record);
int insertSelective(ParSellType record);
List<ParSellType> selectByExample(ParSellTypeExample example);
ParSellType selectByPrimaryKey(String sellTypeId);
int updateByExampleSelective(@Param("record") ParSellType record, @Param("example") ParSellTypeExample example);
int updateByExample(@Param("record") ParSellType record, @Param("example") ParSellTypeExample example);
int updateByPrimaryKeySelective(ParSellType record);
int updateByPrimaryKey(ParSellType record);
}
|
C
|
UTF-8
| 694
| 3.359375
| 3
|
[] |
no_license
|
#include<stdio.h>
int main()
{
int n, sum, dig, t, temp;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
temp=n;
while(temp!=1)
{
sum=0;
if(temp<10)
{
temp=temp*temp;
}
while(temp!=0)
{
dig = temp%10;
sum = sum + dig*dig;
temp = temp/10;
}
temp = sum;
}
if(sum==1)
{
printf("%d is a happy number\n",n);
}
else
{
printf("%d is a unhappy number\n",n);
}
}
return 0;
}
|
PHP
|
UTF-8
| 1,581
| 2.9375
| 3
|
[] |
no_license
|
<?php
session_start ();
$login = htmlspecialchars($_POST['login']);
$password = htmlspecialchars($_POST['password']);
// Si le visiteur a bien entré un login et un mot de passe
if (isset($login) && isset($password)) {
// On ouvre la BDD pour consulter les clés login/password
include('head_and_footer/open_database.php');
$statement = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) AS name, login, password, rights FROM users;");
$statement->execute();
$connexion = $statement->fetchAll(PDO::FETCH_ASSOC);
$pdo = null;
// Pour chacune des paires login/password de la BDD
for ($index = 0; $index < sizeof($connexion); $index++) {
// Si la paire entrée correspond à une des paires de la BDD:
if(
($login == $connexion[$index]['login']) &&
(password_verify($password, $connexion[$index]['password']))
) {
// On démarre la session
session_start ();
// On enregistre les paramètres du visiteur comme variables de session
$_SESSION['login'] = $login;
$_SESSION['password'] = $password;
$_SESSION['name'] = $connexion[$index]['name'];
$_SESSION['logged_in'] = true;
$_SESSION['rights'] = $connexion[$index]['rights'];
if ($_SESSION['rights'] == 'admin') {
header('Location: admin.php');
} else {
header('Location: my_profile.php');
}
}
}
} else {
header('Location: login.phtml');
}
|
Python
|
UTF-8
| 1,629
| 2.828125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pytest
from warnings import warn
from .context import apisample
from apisample.config import Config
from apisample.task import Task
from apisample.task_runner import TaskRunner
@pytest.fixture
def data():
try:
data = dict()
config = Config('./config.ini')
runner = TaskRunner()
data['config'] = config
data['runner'] = runner
return data
except Exception as e:
warn('Failed to instantiate TaskRunner. {}'.format(e))
def test_append(data):
runner = data['runner']
len_tasks = len(runner.tasks)
config = data['config']
task = Task('append_test', config)
runner.append(task)
assert task.name == 'append_test'
assert len(runner.tasks) == len_tasks + 1
def test_pop(data):
runner = data['runner']
config = data['config']
runner.append(Task('left', config))
runner.append(Task('middle', config))
runner.append(Task('right', config))
len_tasks = len(runner.tasks)
popped = runner.pop()
assert isinstance(popped, Task)
assert popped.name == 'right'
assert len(runner.tasks) == len_tasks - 1
def test_popleft(data):
runner = data['runner']
config = data['config']
runner.append(Task('left', config))
runner.append(Task('middle', config))
runner.append(Task('right', config))
len_tasks = len(runner.tasks)
popped = runner.popleft()
assert isinstance(popped, Task)
assert popped.name == 'left'
assert len(runner.tasks) == len_tasks - 1
def test_run(data):
assert data['runner'].run() == 'Run task.'
|
Java
|
UTF-8
| 2,410
| 2.515625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-symphonysoft"
] |
permissive
|
package org.mule.ide.core.samples;
/**
* Holds details about a sample project that can be loaded at Mule project creation.
*
* @author Derek Adams
*/
public class Sample {
/** Unique id for contributing plugin */
private String pluginId;
/** Description of the sample */
private String description;
/** Plugin-relative sample root directory */
private String root;
/** Root-relative path to the source directory */
private String sourcePath;
/** Root-relative path to the configuratino directory */
private String configPath;
/** Config set data to be added for the sample */
private ConfigSet[] configSets;
/**
* Gets the configPath
*
* @return returns the configPath
*/
public String getConfigPath() {
return configPath;
}
/**
* Sets the configPath.
*
* @param configPath
* the configPath
*/
public void setConfigPath(String configPath) {
this.configPath = configPath;
}
/**
* Gets the configSets
*
* @return returns the configSets
*/
public ConfigSet[] getConfigSets() {
return configSets;
}
/**
* Sets the configSets.
*
* @param configSets
* the configSets
*/
public void setConfigSets(ConfigSet[] configSets) {
this.configSets = configSets;
}
/**
* Gets the description
*
* @return returns the description
*/
public String getDescription() {
return description;
}
/**
* Sets the description.
*
* @param description
* the description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the pluginId
*
* @return returns the pluginId
*/
public String getPluginId() {
return pluginId;
}
/**
* Sets the pluginId.
*
* @param pluginId
* the pluginId
*/
public void setPluginId(String pluginId) {
this.pluginId = pluginId;
}
/**
* Gets the root
*
* @return returns the root
*/
public String getRoot() {
return root;
}
/**
* Sets the root.
*
* @param root
* the root
*/
public void setRoot(String root) {
this.root = root;
}
/**
* Gets the sourcePath
*
* @return returns the sourcePath
*/
public String getSourcePath() {
return sourcePath;
}
/**
* Sets the sourcePath.
*
* @param sourcePath
* the sourcePath
*/
public void setSourcePath(String sourcePath) {
this.sourcePath = sourcePath;
}
}
|
C#
|
UTF-8
| 942
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Xaml;
namespace Microsoft.Maui.Controls.ControlGallery.GalleryPages.DragAndDropGalleries
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DragPaths : ContentPage
{
public DragPaths()
{
InitializeComponent();
}
void OnMonkeyDragStarting(object sender, DragStartingEventArgs e)
{
e.Data.Text = "Monkey";
}
void OnCatDragStarting(object sender, DragStartingEventArgs e)
{
e.Data.Text = "Cat";
}
async void OnDrop(object sender, DropEventArgs e)
{
string text = await e.Data.GetTextAsync();
if (text.Equals("Cat"))
{
await DisplayAlert("Correct", "Congratulations!", "OK");
}
else if (text.Equals("Monkey"))
{
await DisplayAlert("Incorrect", "Try again.", "OK");
}
}
}
}
|
Java
|
UTF-8
| 1,853
| 2.625
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package os.Clases;
/**
*
* @author Oscar
*/
public class Cliente {
private String nombre;
private String NIT;
private String direccion;
private String municipio;
private String departamento;
public Cliente(String nombre, String nit, String direccion, String municipio, String departamento) {
try {
this.nombre = nombre;
this.NIT = nit;
this.direccion = direccion;
this.municipio = municipio;
this.departamento = departamento;
} catch (NumberFormatException e) {
}
}
public Cliente(String nombre, String nit, String direccion) {
try {
this.nombre = nombre;
this.NIT = nit;
this.direccion = direccion;
} catch (NumberFormatException e) {
}
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getNIT() {
return NIT;
}
public void setNIT(String NIT) {
try {
this.NIT = NIT;
} catch (NumberFormatException e) {
}
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getMunicipio() {
return municipio;
}
public void setMunicipio(String municipio) {
this.municipio = municipio;
}
public String getDepartamento() {
return departamento;
}
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
}
|
Java
|
UTF-8
| 1,871
| 3.140625
| 3
|
[] |
no_license
|
package cscd210Lab9;
import java.util.Scanner;
import cscd210Methods.CSCD210Lab9Methods;
import cscd210Methods.gameMethods.GuessTheWordGameMethods;
/**
* The CSCD210Lab9 class that contains the main method for playing the guess the word game
* <br> You may not change this class or the main method in any fashion
* <br> Remember all parameters will be final
*/
public class CSCD210Lab9
{
public static void main(String [] args)
{
char guess;
boolean guessed;
int incorrectGuesses;
Scanner kb = new Scanner(System.in);
String player1 = null, player2 = null, theWord = null;
char [] wordToGuess = null, guessedLetters = null, displayGuessedLettersWordToGuess = null;
do
{
incorrectGuesses = 0;
guessed = false;
player1 = CSCD210Lab9Methods.readName(kb);
player2 = CSCD210Lab9Methods.readName(kb);
theWord = CSCD210Lab9Methods.readWord(kb, player1);
wordToGuess = CSCD210Lab9Methods.convertWordToArray(theWord);
displayGuessedLettersWordToGuess = GuessTheWordGameMethods.initializeDisplay(wordToGuess);
guessedLetters = GuessTheWordGameMethods.initializeDisplay(26);
do
{
guess = GuessTheWordGameMethods.readGuess(kb, player2);
incorrectGuesses = GuessTheWordGameMethods.checkGuess(guess, wordToGuess, incorrectGuesses);
guessed = GuessTheWordGameMethods.display(guess, wordToGuess, guessedLetters,
displayGuessedLettersWordToGuess, incorrectGuesses);
}while(!guessed && incorrectGuesses < GuessTheWordGameMethods.TOTAL);
}while(CSCD210Lab9Methods.goAgain(kb));
}// end main
}// end class
|
C#
|
UTF-8
| 1,588
| 2.75
| 3
|
[] |
no_license
|
using System.Collections.Generic;
using System.Linq;
using ANTIL.Domain.Core.Entities.Common;
using ANTIL.Domain.Dao.Interfaces.Common;
namespace ANTIL.Domain.Dao.Implementations.Common
{
public class GenericDao<T> : IGenericDao<T> where T : DomainObject
{
private readonly IDataAccessObject _dao;
public GenericDao(IDataAccessObject dao)
{
this._dao = dao;
}
protected IDataAccessObject Dao
{
get { return _dao; }
}
public IList<T> Get()
{
return Dao.Query<T>().ToList();
}
public IList<T> Get(ICollection<int> ids)
{
return Dao.Query<T>().Where(x => ids.Contains(x.Id)).ToList();
}
public T Get(int id)
{
return Dao.Load<T>(id);
}
public int Count()
{
return Dao.Query<T>().Count();
}
public virtual void Delete(T entity)
{
Dao.Delete(entity);
}
public virtual void BulkDelete(ICollection<T> entities)
{
Dao.BulkDelete(entities);
}
public virtual void Delete(int id)
{
var entity = Get(id);
Dao.Delete(entity);
}
public T Save(T entity)
{
return Dao.Save(entity);
}
public void BulkSave(ICollection<T> entities)
{
Dao.BulkSave(entities);
}
public IQueryable<T> CreateQuery()
{
return Dao.Query<T>();
}
}
}
|
Markdown
|
UTF-8
| 1,979
| 2.640625
| 3
|
[] |
no_license
|
# Laravel + GraphQL + MongoDB Example
### About Project
The application was developed using Docker, PHP, MongoDB and GraphQL. To start you only need [docker](https://docs.docker.com/engine/install/ubuntu/)
and [docker-compose](https://docs.docker.com/compose/install/) installed on your machine.
#### How to start
```
cp .env.example .env
docker-compose up -d
docker-compose exec app composer install
docker-compose exec app php artisan key:generate
docker-compose exec app php artisan migrate
docker-compose exec app php artisan db:seed
```
#### How to run tests
```
docker-compose exec app php artisan migrate --database=mongo_testing
docker-compose exec app vendor/bin/phpunit
```
#### How to use
**POST** http://0.0.0.0:8888/graphql
```
query FetchAllRestaurants {
Restaurants {
tradingName,
coverageArea {
coordinates
}
}
}
query FindRestaurantByUuid {
Restaurants(id: "52643fae-0feb-3262-a393-7eb4aa1821c2") {
ownerName,
address {
type,
coordinates
}
}
}
query FindRestaurantByLocation {
Restaurants(lng: -38.59826, lat:-3.774186) {
document,
address {
type,
coordinates
}
}
}
mutation restaurants {
CreateRestaurant(
tradingName: "Pokemon bar & lanches LTDA",
ownerName: "Ash Ketchup",
document: "33.416.178/0001-77",
address: {
type: "Point",
coordinates: [-46.57421, -21.785741]
},
coverageArea: {
type: "MultiPolygon",
coordinates: [
[[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],
[[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
[[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]
]
}
) {
id,
coverageArea {
type
}
}
}
```
### Todo
* Authentication with JWT.
* Documentation files.
* Refactor messages error in GraphQL.
* Create an update mutation.
* Add more tests.
#
Made with love by [me](https://victorhugo.dev).
|
Rust
|
UTF-8
| 4,587
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
//! Similar to `Arc<T>`, but is not allocated on heap.
//! This type panics if it gets dropped before all `Ref<T>`/`RefMut<T>` drops.
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;
use core::sync::atomic::{AtomicUsize, Ordering};
use super::strong_pin::StrongPinMut;
const BORROWED_MUT: usize = usize::MAX;
/// # Safety
///
/// * If `refcnt` equals `BORROWED_MUT`, a single `RefMut` refers to `self`.
/// * If `refcnt` equals n where n < `BORROWED_MUT`, n `Ref`s refer to `self`.
/// * `RefMut` can mutate both `data` and `refcnt`.
/// * `Ref` can mutate `refcnt` and read `data`.
pub struct StaticArc<T> {
data: T,
refcnt: AtomicUsize,
}
/// # Safety
///
/// * It holds a valid pointer.
#[repr(transparent)]
pub struct Ref<T>(NonNull<StaticArc<T>>);
/// # Safety
///
/// * It holds a valid pointer.
#[repr(transparent)]
pub struct RefMut<T>(NonNull<StaticArc<T>>);
impl<T> StaticArc<T> {
pub const fn new(data: T) -> Self {
Self {
data,
refcnt: AtomicUsize::new(0),
}
}
#[allow(clippy::needless_lifetimes)]
fn rc<'s>(self: StrongPinMut<'s, Self>) -> &'s AtomicUsize {
// SAFETY: invariant of StrongPinMut
unsafe { &(*self.ptr().as_ptr()).refcnt }
}
pub fn is_borrowed(self: StrongPinMut<'_, Self>) -> bool {
self.rc().load(Ordering::Acquire) > 0
}
#[allow(clippy::needless_lifetimes)]
pub fn get_mut<'s>(mut self: StrongPinMut<'s, Self>) -> Option<&'s mut T> {
if self.as_mut().is_borrowed() {
None
} else {
// SAFETY: no `Ref` nor `RefMut` points to `self`.
Some(unsafe { &mut (*self.ptr().as_ptr()).data })
}
}
#[allow(clippy::needless_lifetimes)]
pub unsafe fn get_mut_unchecked<'s>(self: StrongPinMut<'s, Self>) -> &'s mut T {
// SAFETY: no `Ref` nor `RefMut` points to `self`.
unsafe { &mut (*self.ptr().as_ptr()).data }
}
pub fn try_borrow(mut self: StrongPinMut<'_, Self>) -> Option<Ref<T>> {
loop {
let r = self.as_mut().rc().load(Ordering::Acquire);
if r >= BORROWED_MUT - 1 {
return None;
}
if self
.as_mut()
.rc()
.compare_exchange(r, r + 1, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
{
return Some(Ref(self.ptr()));
}
}
}
pub fn borrow(self: StrongPinMut<'_, Self>) -> Ref<T> {
self.try_borrow().expect("already mutably borrowed")
}
pub unsafe fn borrow_unchecked(mut self: StrongPinMut<'_, Self>) -> Ref<T> {
let _ = self.as_mut().rc().fetch_add(1, Ordering::Relaxed);
Ref(self.ptr())
}
}
impl<T> Drop for StaticArc<T> {
fn drop(&mut self) {
assert_eq!(
self.refcnt.load(Ordering::Acquire),
0,
"dropped while borrowed"
);
}
}
impl<T> Ref<T> {
fn rc(&self) -> &AtomicUsize {
// SAFETY: invariant
unsafe { &(*self.0.as_ptr()).refcnt }
}
pub fn into_mut(self) -> Result<RefMut<T>, Self> {
if self
.rc()
.compare_exchange(1, BORROWED_MUT, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return Err(self);
}
let ptr = self.0;
core::mem::forget(self);
Ok(RefMut(ptr))
}
}
impl<T> Deref for Ref<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: `Ref` can read `data`.
unsafe { &(*self.0.as_ptr()).data }
}
}
impl<T> Clone for Ref<T> {
fn clone(&self) -> Self {
let _ = self.rc().fetch_add(1, Ordering::Relaxed);
Self(self.0)
}
}
impl<T> Drop for Ref<T> {
fn drop(&mut self) {
let _ = self.rc().fetch_sub(1, Ordering::Release);
}
}
impl<T> RefMut<T> {
fn rc(&self) -> &AtomicUsize {
// SAFETY: invariant
unsafe { &(*self.0.as_ptr()).refcnt }
}
pub fn cell(&self) -> *mut StaticArc<T> {
self.0.as_ptr()
}
}
impl<T> Deref for RefMut<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: `RefMut` can read `data`.
unsafe { &(*self.0.as_ptr()).data }
}
}
impl<T> DerefMut for RefMut<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: `RefMut` can mutate `data`.
unsafe { &mut (*self.0.as_ptr()).data }
}
}
impl<T> Drop for RefMut<T> {
fn drop(&mut self) {
self.rc().store(0, Ordering::Release);
}
}
|
Java
|
UTF-8
| 234
| 1.78125
| 2
|
[] |
no_license
|
package com.hrishikeshmishra.sb.spel;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hrishikesh.mishra on 30/08/16.
*/
public class Simple {
public List<Boolean> booleanList = new ArrayList<Boolean>();
}
|
C
|
UTF-8
| 1,399
| 3.75
| 4
|
[] |
no_license
|
#include <stdio.h>
// SWEA_1970 쉬운 거스름돈
// 루프를 돌면서 마이너스 해주는 방법도 있으나
// 나눈다음 그 나온 몫 만큼 현재 금액에 곱하여 전체 금액에서 빼주는 방법이 더 효율적이다.
int main(void) {
int N;
scanf("%d",&N);
for(int i = 0 ; i<N ; i++){
int arr[8] = {0,};
int inp;
scanf("%d",&inp);
while(1){
if(inp == 0){ // ** break문을 맨처음에 걸지 않으면 inp == 0 일때는 나머지값이 항상 0 이므로 무한 루프에 빠진다!! ** //
break;
}
if(inp % 50000 == 0){
inp = inp - 50000;
arr[0]++;
continue;
}
else if(inp % 10000 == 0){
inp = inp - 10000;
arr[1]++;
continue;
}
else if(inp % 5000 == 0){
inp = inp - 5000;
arr[2]++;
continue;
}
else if(inp % 1000 == 0){
inp = inp - 1000;
arr[3]++;
continue;
}
else if(inp % 500 == 0){
inp = inp - 500;
arr[4]++;
continue;
}
else if(inp % 100 == 0){
inp = inp - 100;
arr[5]++;
continue;
}
else if(inp % 50 == 0){
inp = inp - 50;
arr[6]++;
continue;
}
else if(inp % 10 == 0){
inp = inp - 10;
arr[7]++;
continue;
}
}
printf("#%d\n",i+1);
for(int j = 0 ; j < 8 ; j++){
printf("%d ",arr[j]);
}
printf("\n");
}
return 0;
}
|
Java
|
UTF-8
| 651
| 2.484375
| 2
|
[] |
no_license
|
package com.henteko07.androidlabteressampleapp.Model;
import com.henteko07.androidlabteressampleapp.Model.Blood;
import java.io.Serializable;
/**
* Created by kenta.imai on 2014/09/02.
*/
public class User implements Serializable {
public static final String USER_KEY = "first_user";
public static final String SECOND_USER_KEY = "second_user";
public final String name;
public final Blood blood;
public final Sex sex;
public User(String name, Blood blood, Sex sex) {
String prefix = (sex == Sex.Man) ? "♂" : "♀";
this.name = prefix + name;
this.blood = blood;
this.sex = sex;
}
}
|
TypeScript
|
UTF-8
| 17,555
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
import { Component, Vue } from "vue-property-decorator";
import { DesktopFile, DesktopParser } from './DesktopParser';
import { readdir, readFile } from 'fs';
import fs from "fs";
import { exec } from "child_process";
import { ipcRenderer, app } from 'electron';
@Component({
components: {}
})
export default class AppViewModel extends Vue {
public selectionIndex = 0
public searchTerm: string = "";
public themeName: string | undefined;
public username: string = null!;
// already sorted by name desc
public applicationSuggestions: ApplicationSuggestion[] = [];
public filteredApplicationSuggestions: ApplicationSuggestion[] = [];
public lastSelectedSuggestionBySearchTerm: Record<string, string> = {};
private isVisible = false;
public async mounted(): Promise<void> {
this.themeName = await this.getThemeNameAsync()
this.username = await this.getUsernameAsync()
await this.loadSuggestionWeightsAsync();
await this.loadApplicationSuggestionsAsync();
ipcRenderer.on('hide', () => {
this.isVisible = false;
});
ipcRenderer.on('show', () => {
this.isVisible = true;
setTimeout(() => {
if (this.$refs.searchInput) {
this.updateSearch("");
(this.$refs.searchInput as HTMLInputElement).focus();
}
}, 0);
});
Vue.nextTick(() => (this.$refs.searchInput as HTMLInputElement).focus());
}
public hide(): void {
ipcRenderer.send("hide-me");
}
public title(suggestion: ApplicationSuggestion): string {
return "" +
"exec: " + suggestion.exec + "\n" +
"icon: " + suggestion.iconPath + "\n" +
"categories: " + suggestion.categories.join(", ") + "\n" +
"description: " + suggestion.description + "\n" +
"location of desktop file: " + suggestion.desktopFileLocation;
}
public async exec(suggestion: ApplicationSuggestion): Promise<void> {
if (!this.isVisible) {
return;
}
if (suggestion.isInternal) {
this.execInternalAction(suggestion);
}
const ignoreFieldCodes = (exec: string) => {
return exec
.replace("%f", "")
.replace("%u", "")
.replace("%F", "")
.replace("%U", "");
};
exec(ignoreFieldCodes(suggestion.exec), { cwd: "/home/" + this.username });
if (this.searchTerm !== "") {
this.lastSelectedSuggestionBySearchTerm[this.searchTerm] = suggestion.name;
await this.writeFileAsync("/home/" + this.username + "/.StartMenu/lastSelectedSuggestionBySearchTerm.json", this.lastSelectedSuggestionBySearchTerm);
}
}
public isPartOfMatch(index: number, suggestion: ApplicationSuggestion): boolean {
for (const match of suggestion.matches) {
if (match.matchingIndexes.indexOf(index) !== -1) {
return true;
}
}
return false;
}
public updateSearch(searchTerm: string): void {
this.searchTerm = searchTerm;
const lowerSearchTerm = searchTerm.toLocaleLowerCase();
if (this.searchTerm.trim() != "") {
const newFilteredApplicationSuggestions: Array<ApplicationSuggestion | null> = [];
// find sequence matches like "Telegr[A]m Deskt[O]p" for the search term "ao"
for (const suggestion of this.applicationSuggestions) {
suggestion.matches.splice(0);
const matchingIndexes: number[] = [];
let index = 0
for (; index < lowerSearchTerm.length; index++) {
const char = lowerSearchTerm[index];
const lastMatchIndex = matchingIndexes.length === 0 ? 0 : matchingIndexes[matchingIndexes.length - 1];
const charIndex = suggestion.name.toLocaleLowerCase().indexOf(char, lastMatchIndex + 1);
if (charIndex === -1) {
break
}
matchingIndexes.push(charIndex);
if (index === lowerSearchTerm.length - 1) {
suggestion.matches.push({ matchingIndexes })
newFilteredApplicationSuggestions.push(suggestion);
}
}
}
const range = (start: number, count: number) => {
const indexes: number[] = [];
for (let i = start; i <= start + count; i++) {
indexes.push(i);
}
return indexes;
}
// find contains matches like "Tele[GRAM] Desktop" for the search term "gram"
for (const suggestion of this.applicationSuggestions) {
const newValueIndex = suggestion.name.indexOf(lowerSearchTerm);
if (suggestion.name.toLocaleLowerCase().indexOf(lowerSearchTerm) === -1) {
continue;
}
const matchingIndexes = range(newValueIndex, lowerSearchTerm.length);
suggestion.matches.push({ matchingIndexes })
newFilteredApplicationSuggestions.push(suggestion);
}
// find starting letter matches like "[T]elegram [D]esktop" for the search term "TD" (lowercase letters count as starting letter too)
for (const suggestion of this.applicationSuggestions) {
let startingLetters = "";
let startingLetterIndexes: number[] = [];
for (let index = 0; index < suggestion.name.length; index++) {
const char = suggestion.name[index];
const isUpperCase = char === char.toUpperCase();
const charCode = char.charCodeAt(0);
const isLetter = (charCode >= 65 && charCode < 91) || (charCode >= 97 && charCode < 123)
if (isUpperCase && isLetter) {
startingLetters += char.toLocaleLowerCase(); // "VisualStudio" = vs
startingLetterIndexes.push(index)
continue;
}
if (index > 0 && suggestion.name[index - 1] === " ") {
const char = suggestion.name[index - 1];
const charCode = char.charCodeAt(0);
const isLetter = (charCode >= 65 && charCode < 91) || (charCode >= 97 && charCode < 123)
if (isLetter) {
startingLetters += suggestion.name[index - 1].toLocaleLowerCase(); // "VisualStudio code" = vsc
startingLetterIndexes.push(index - 1)
}
}
}
const newValueIndex = startingLetters.indexOf(lowerSearchTerm);
if (newValueIndex !== -1) {
const matchingIndexes = startingLetterIndexes.filter((_, index) => index >= newValueIndex && index <= newValueIndex + lowerSearchTerm.length);
suggestion.matches.push({ matchingIndexes })
newFilteredApplicationSuggestions.push(suggestion);
}
}
if (this.lastSelectedSuggestionBySearchTerm[searchTerm]) {
const lastSelectedSuggestionBySearchTerm = this.applicationSuggestions.find(x => x.name == this.lastSelectedSuggestionBySearchTerm[searchTerm]);
if (lastSelectedSuggestionBySearchTerm) {
newFilteredApplicationSuggestions.push(lastSelectedSuggestionBySearchTerm);
}
}
var seenMatches = new Set<ApplicationSuggestion>();
for (let index = newFilteredApplicationSuggestions.length - 1; index >= 0; index--) {
if (seenMatches.has(newFilteredApplicationSuggestions[index]!)) {
newFilteredApplicationSuggestions[index] = null;
continue;
}
seenMatches.add(newFilteredApplicationSuggestions[index]!);
}
this.filteredApplicationSuggestions = newFilteredApplicationSuggestions.filter(x => x != null) as ApplicationSuggestion[];
}
else {
const newFilteredApplicationSuggestions: Array<ApplicationSuggestion> = [];
for (const suggestion of this.applicationSuggestions) {
suggestion.matches.splice(0);
newFilteredApplicationSuggestions.push(suggestion);
}
this.filteredApplicationSuggestions = newFilteredApplicationSuggestions;
}
this.selectionIndex = this.filteredApplicationSuggestions.length - 1;
Vue.nextTick(() => (this.$refs.suggestionContainer as HTMLElement).scrollTop = (this.$refs.suggestionContainer as HTMLElement).scrollHeight)
}
public updateSelectionIndex(event: KeyboardEvent): void {
if (event.key === "ArrowUp") {
if (this.selectionIndex <= 0) {
return;
}
this.selectionIndex--;
return;
}
if (event.key === "ArrowDown") {
if (this.selectionIndex >= this.filteredApplicationSuggestions.length - 1) {
return;
}
this.selectionIndex++;
}
if (event.key === "Enter") {
this.exec(this.filteredApplicationSuggestions[this.selectionIndex]);
this.hide();
}
}
private execInternalAction(suggestion: ApplicationSuggestion): void {
switch (suggestion.name) {
case "refresh-suggestion-list":
this.loadApplicationSuggestionsAsync();
break
case "restart-start-menu":
app.relaunch();
app.exit();
break;
case "shutdown-start-menu":
app.exit();
break;
}
}
private async loadSuggestionWeightsAsync(): Promise<void> {
if (!await this.existsAsync("/home/" + this.username + "/.StartMenu/")) {
await this.mkdirAsync("/home/" + this.username + "/.StartMenu/");
await this.writeFileAsync("/home/" + this.username + "/.StartMenu/lastSelectedSuggestionBySearchTerm.json", {});
}
const buffer = await this.readFileAsync("/home/" + this.username + "/.StartMenu/lastSelectedSuggestionBySearchTerm.json");
const lastSelectedSuggestionBySearchTerm = JSON.parse(buffer.toString());
this.lastSelectedSuggestionBySearchTerm = lastSelectedSuggestionBySearchTerm;
}
private async loadApplicationSuggestionsAsync(): Promise<void> {
this.applicationSuggestions.splice(0);
const desktopFiles = await this.readDesktopFilesAsync();
for (const desktopFile of desktopFiles.map(x => x)) {
if (desktopFile.noDisplay === true) {
continue;
}
if (desktopFile.notShowIn.some(x => x.toLocaleLowerCase().indexOf("kde") !== -1)) {
continue;
}
if (desktopFile.onlyShowIn.length > 0 && !desktopFile.onlyShowIn.some(x => x.toLocaleLowerCase().indexOf("kde") !== -1)) {
continue;
}
if (this.applicationSuggestions.find(x => x.name === desktopFile.name && x.exec === desktopFile.exec)) {
continue;
}
this.applicationSuggestions.push({
isInternal: false,
desktopFileLocation: desktopFile.location,
name: desktopFile.name,
exec: desktopFile.exec,
iconPath: await this.iconPath(desktopFile),
description: desktopFile.description,
categories: desktopFile.categories,
comment: desktopFile.comment,
matches: []
});
}
this.applicationSuggestions.push({
isInternal: true,
exec: "",
name: "refresh-suggestion-list",
matches: [],
categories: []
});
this.applicationSuggestions.push({
isInternal: true,
exec: "",
name: "restart-start-menu",
matches: [],
categories: []
});
this.applicationSuggestions.push({
isInternal: true,
exec: "",
name: "shutdown-start-menu",
matches: [],
categories: []
});
this.applicationSuggestions.sort((a, b) => a.name.localeCompare(b.name)).reverse()
}
private async iconPath(desktopFile: DesktopFile): Promise<string> {
const isPath = desktopFile.icon?.indexOf("/") != -1;
if (isPath) {
return desktopFile.icon!;
}
const basePaths = ["/usr/share/icons/", "/home/" + this.username + "/.local/share/icons/"];
const sizes = ["128x128", "64x64", "32x32", "16x16"];
const categories = ["apps", "panel"];
const extensions = ["svg", "png", "jpg", "jpeg", "gif", "bmp"];
const themes: string[] = ["hicolor"];
if (this.themeName) {
themes.unshift(this.themeName);
}
for (const theme of themes) {
for (const size of sizes) {
for (const basePath of basePaths) {
for (const category of categories) {
for (const extension of extensions) {
const location = basePath + theme + "/" + size + "/" + category + "/" + desktopFile.icon + "." + extension;
if (await this.existsAsync(location)) {
return location;
}
}
}
}
}
}
return "";
}
private async existsAsync(path: string): Promise<boolean> {
let resolve: (result: boolean) => void;
const promise = new Promise<boolean>((_resolve) => resolve = _resolve);
fs.access(path, (error) => {
resolve(error == undefined);
});
return promise;
}
private async mkdirAsync(path: string): Promise<void> {
let resolve: () => void;
const promise = new Promise<void>((_resolve) => resolve = _resolve);
fs.mkdir(path, () => resolve());
return promise;
}
private async writeFileAsync(path: string, data: object): Promise<void> {
let resolve: () => void;
const promise = new Promise<void>((_resolve) => resolve = _resolve);
fs.writeFile(path, JSON.stringify(data), () => resolve());
return promise;
}
private async getThemeNameAsync(): Promise<string | undefined> {
let resolve: (stdout: string | undefined) => void;
const promise = new Promise<string | undefined>((_resolve) => resolve = _resolve);
exec(`kreadconfig5 --group "Icons" --key "Theme"`, (_, result) => {
resolve(result.substring(0, result.length - 1));
});
return promise;
}
private async getUsernameAsync(): Promise<string> {
let resolve: (stdout: string) => void;
const promise = new Promise<string>((_resolve) => resolve = _resolve);
exec("whoami", (_, result) => {
resolve(result.substring(0, result.length - 1));
});
return promise;
}
private async readDesktopFilesAsync(): Promise<DesktopFile[]> {
const applicationPaths = [
"/usr/share/applications/",
"/var/lib/snapd/desktop/applications/",
"/home/" + this.username + "/Desktop/",
"/home/" + this.username + "/.local/share/applications/",
"/usr/local/share/applications/",
"/var/lib/flatpak/exports/share/applications/"
];
const result: DesktopFile[] = [];
for (const applicationPath of applicationPaths) {
if (!await this.existsAsync(applicationPath)) {
continue;
}
const files = await this.readdirAsync(applicationPath);
for (const file of files) {
if (!file.endsWith(".desktop")) {
continue;
}
const data = await this.readFileAsync(applicationPath + file);
result.push(DesktopParser.parseDesktopFile(applicationPath + file, data));
}
}
return result;
}
private async readdirAsync(path: string): Promise<string[]> {
let resolve: (files: string[]) => void;
const promise = new Promise<string[]>((_resolve) => resolve = _resolve);
readdir(path, (_, files) => {
resolve(files);
});
return promise;
}
private async readFileAsync(path: string): Promise<Buffer> {
let resolve: (data: Buffer) => void;
const promise = new Promise<Buffer>((_resolve) => resolve = _resolve);
readFile(path, (_, data) => {
resolve(data);
})
return promise;
}
}
interface ApplicationSuggestion {
isInternal: boolean;
desktopFileLocation?: string;
name: string;
exec: string;
iconPath?: string;
description?: string;
comment?: string;
categories: string[]
matches: Array<{ matchingIndexes: number[] }>
}
|
C
|
UTF-8
| 6,437
| 2.875
| 3
|
[] |
no_license
|
/*
** TIME_MAKE derive 32-bit time value from TMX structure.
**
** Copyright (c) 1980, 1987 by Ken Harrenstien, SRI International.
**
** This code is quasi-public; it may be used freely in like software.
** It is not to be sold, nor used in licensed software without
** permission of the author.
** For everyone's benefit, please report bugs and improvements!
** (Internet: <KLH@SRI-NIC.ARPA>)
**
** Usage:
** #include <timex.h>
** time_t time_make(struct tmx *tp);
**
** Returns:
** A time_t value.
** Will fail if parameters are out of range or nonsensical; the
** return value will be (time_t)-1 and tmx_err will be set in the
** tmx structure to point at a constant error-message string.
*/
#include <timex.h>
/* Days in year thus far, indexed by month (0-12!!) Assumes non-leap year. */
static int daytb[] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
#define TERR(str) { tp->tmx_err = str; return -1; }
time_t
time_make(tp)
register struct tmx *tp;
{
register int i;
struct tm *tmp;
int year, mon, day, yday, wday, dst, leap;
time_t tres, curtim;
if (tp->tm.tm_year == TMX_NULL
|| tp->tm.tm_mon == TMX_NULL
|| tp->tm.tm_mday == TMX_NULL) {
time(&curtim);
tmp = localtime(&curtim); /* Get breakdowns of current time */
year = tmp->tm_year; /* Get defaults to use */
mon = tmp->tm_mon;
day = tmp->tm_mday;
#ifdef DEBUG
printf("first YMD: %d %d %d, T=%ld\n",year,mon,day,curtim);
#endif
}
/* First must find date, using specified year, month, day.
* If one of these is unspecified, it defaults either to the
* current date (if no more global spec was given) or to the
* zero-value for that spec (i.e. a more global spec was seen).
* Start with year... note 32 bits can only handle 135 years.
*/
if (tp->tm.tm_year == TMX_NULL)
tp->tm.tm_year = year; /* Set to default */
else {
if ((year = tp->tm.tm_year) >= 1900) /* Allow full yr # */
year = (tp->tm.tm_year -= 1900); /* by making kosher */
mon = 0; /* Since year was given, default */
day = 1; /* for remaining specs is zero */
}
if (year < 70 || 70+134 < year) /* Check range */
TERR("year out of range")
leap = year&03 ? 0 : 1; /* See if leap year */
year -= 70; /* UNIX time starts at 1970 */
/*
* Find day of year.
* YDAY is used only if it exists and either the month or day-of-month
* is missing.
*/
if (tp->tm.tm_yday != TMX_NULL
&& (tp->tm.tm_mon == TMX_NULL || tp->tm.tm_mday == TMX_NULL))
yday = tp->tm.tm_yday;
else {
if (tp->tm.tm_mon == TMX_NULL)
tp->tm.tm_mon = mon; /* Set month from default */
else {
mon = tp->tm.tm_mon; /* Month was specified */
day = 1; /* so set remaining default */
}
if (mon < 0 || 11 < mon)
TERR("month out of range")
if (tp->tm.tm_mday == TMX_NULL)
tp->tm.tm_mday = day; /* Set day from default */
else day = tp->tm.tm_mday;
if (day < 1
|| (((daytb[mon+1]-daytb[mon]) < day)
&& (day!=29 || mon!=1 || !leap) ))
TERR("day out of range")
yday = daytb[mon] /* Add # of days in months so far */
+ ((leap /* Leap year, and past Feb? If */
&& mon>1)? 1:0) /* so, add leap day for this year */
+ day-1; /* And finally add # days this mon */
#if 1 /* Optional */
if (tp->tm.tm_yday == TMX_NULL) /* Confirm that YDAY correct */
tp->tm.tm_yday = yday; /* Not specified, just set */
else if (tp->tm.tm_yday != yday)
TERR("yday conflict")
#endif
}
if (yday < 0 || (leap?366:365) <= yday)
TERR("yday out of range") /* ERR: bad YDAY or maketime bug */
tres = year*365 /* Get # days of years so far */
+ ((year+1)>>2) /* plus # of leap days since 1970 */
+ yday; /* and finally add # days this year */
#if 1 /* Optional */
wday = (tres+4)%7; /* Derive day-of-week */
if ((i = tp->tm.tm_wday) != TMX_NULL) { /* Check WDAY if present */
if (i < 0 || 6 < i /* Ensure within range */
|| i != wday) /* Matches? Jan 1,1970 was Thu = 4 */
TERR("wday conflict")
} else tp->tm.tm_wday = wday;
#endif
#ifdef DEBUG
printf("YMD: %d %d %d, T=%ld\n",year,mon,day,tres);
#endif
/*
* Now determine time. If not given, default to zeros
* (since time is always the least global spec)
*/
tres *= 86400L; /* Get # seconds (24*60*60) */
if ((i = tp->tm.tm_min) == TMX_NULL) tp->tm.tm_min = i = 0;
if (i < 0 || 60 <= i) TERR("min out of range")
if ((i = tp->tm.tm_sec) == TMX_NULL) tp->tm.tm_sec = i = 0;
if (i < 0 || 60 <= i) TERR("sec out of range")
if ((i = tp->tm.tm_hour) == TMX_NULL) tp->tm.tm_hour = i = 0;
if (i < 0 || 24 <= i)
if (i != 24 || (tp->tm.tm_min+tp->tm.tm_sec) !=0) /* 24:00 OK */
TERR("hour out of range")
#ifdef DEBUG
printf("HMS: %d %d %d T=%ld\n",
tp->tm.tm_hour, tp->tm.tm_min, tp->tm.tm_sec, tres);
#endif
tres += tp->tm.tm_sec /* Add in # secs of time */
+ 60L * (tp->tm.tm_min + 60L * tp->tm.tm_hour);
/*
** We now have the local date/time and must make final
** adjustment for the specified time zone, to get GMT.
** If no zone is specified, the local time-zone is assumed.
*/
if (tp->tmz.tmz_secwest == TMX_NULL) { /* If unspecified */
if ((i = tp->tmz.tmz_minwest)==TMX_NULL)
i = 1; /* Use local zone */
tp->tmz.tmz_secwest = (i == 1 ? 1 : i*60L);
}
if (tp->tmz.tmz_secwest == 1) { /* Forcing use of local zone? */
time_lzone(&tp->tmz); /* then set to local zone */
}
if (tp->tmz.tmz_secwest < -(12*60*60L)
|| 12*60*60L < tp->tmz.tmz_secwest)
TERR("zone out of range")
/* See if must apply Daylight Saving Time shift.
* Note that if DST is specified, validity is not checked.
*/
if((dst = tp->tm.tm_isdst) == TMX_NULL) { /* Must we figure it out? */
struct tmz lz;
time_lzone(&lz); /* Get our local tz stuff */
if (lz.tmz_secwest == tp->tmz.tmz_secwest) { /* Same as local? */
curtim = tres + lz.tmz_secwest; /* Yes, get equiv local */
dst = localtime(&curtim)->tm_isdst; /* time, and ask. */
} else dst = 0; /* No, cannot determine if OK. */
tp->tm.tm_isdst = dst;
}
tres += tp->tmz.tmz_secwest - (dst==1 ? 3600 : 0); /* Add in zone adj */
tp->tmx_err = 0; /* Won! Clear error message ptr */
return tres;
}
|
JavaScript
|
UTF-8
| 927
| 4.6875
| 5
|
[] |
no_license
|
/**Common Suffix
constantly seeks words that end with the same letters. Write a function that, when given a word array, returns the largest suffix (word-end) common to all words in the array.
For inputs ["deforestation", "citation","conviction", "incarceration"], return "tion" (not all that creative a rhyming point). If it is ["nice", "ice", "baby"], return "", because that’s just … not. */
function commonSuffix(arr){
var hashmap={};
for(var i=0; i<arr.length; i++){
for(var j=0; j<arr[i].length; j++){
var substr = arr[i].substring(j);
if( substr in hashmap){
hashmap[substr] = hashmap[substr] + 1;
}
else{
hashmap[substr] = 1;
}
}
}
for(var key in hashmap){
if(hashmap[key] == arr.length){
return key;
}
}
}
var arr = ["deforestation", "citation","conviction", "incarceration"];
console.log(commonSuffix(arr));
|
C#
|
UTF-8
| 993
| 2.671875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BookShop
{
class NameRepository : Container
{
insert insert = new insert();
public static string []names = { "Secret Message", "Cendrela Secrete", "Boys Over Flowers", "BTS"};
// public static string[] names = { "select Name,Price from BooksDetails" };
public Iterator getIterator()
{
return new NameIterator();
}
private class NameIterator:Iterator
{
int index;
public bool hasNext()
{
if(index < names.Length)
{ return true; }
return false;
}
public object next()
{
if(this.hasNext())
{ return names[index++]; }
return null;
}
}
}
}
|
JavaScript
|
UTF-8
| 651
| 2.609375
| 3
|
[] |
no_license
|
const request = require('request')
const geocode = (address,callback)=>{
const url = "https://api.mapbox.com/geocoding/v5/mapbox.places/"+ encodeURIComponent(address)+ ".json?access_token=pk.eyJ1Ijoic3Vib2RoMTgiLCJhIjoiY2szNGptZjgzMDJ0MzNjbXYzMnpjbXZzciJ9.orvc9OFTHcRJuU7ec_ltig"
request({ url:url ,json: true },(err,res)=>{
if(err){
callback('unable to connect to the internet -.- ',undefined)
}else{
callback(undefined,{
lati: res.body.features[0].center[1],
long: res.body.features[0].center[0],
loc : res.body.features[0].place_name
})
}
})
}
module.exports = geocode
|
PHP
|
UTF-8
| 1,240
| 2.53125
| 3
|
[] |
no_license
|
<?php
session_start();
include("config.php");
$username = mysql_real_escape_string($_POST['username']);
$realpassword = mysql_real_escape_string($_POST['password']);
$password = md5(mysql_real_escape_string($_POST['password']));
if (!isset($username) || !isset($password)) {
header("Location: logincriteria.php");
}
elseif (empty($username) || empty($password)) {
header("Location: logincriteria.php");
}
elseif ($username == NULL || $realpassword == NULL) {
header("Location: logincriteria.php");
} else {
$result = mysql_query("select * from login where username='$username'");
$rowCheck = mysql_num_rows($result);
if ($rowCheck > 0) {
while ($row = mysql_fetch_array($result)) {
$username = $row;
header("Location: existingusername.php");
}
} else {
$query2 = "insert into login values ('$username', '$password')";
$result2 = mysql_query($query2);
$_SESSION['id'] = $username;
header("Location: index.php");
// echo "<p>You have successfully created a new login. Please go back and login</p>";
// echo "<p>Username is: ".$username."</p>";
// echo "<p>Password: ".$realpassword."</p>";
// echo "<p>Encoded Password: ".$password."</p>";
}
}
?>
|
Java
|
UTF-8
| 1,386
| 2.59375
| 3
|
[] |
no_license
|
package ru.otus.dao;
import org.springframework.beans.factory.annotation.Autowired;
import ru.otus.datasets.*;
import java.util.*;
public class DBPreparation {
@Autowired
public DBPreparation(DBService dbService) {
UserDataSet user1 = new UserDataSet("tully", Collections.singletonList(new AddressDataSet("Mira")),
new PhoneDataSet("+1 234 567 8018"), new PhoneDataSet("+7 987 645 4545"));
List<AddressDataSet> addresses = new ArrayList<>();
addresses.add(new AddressDataSet("Truda"));
addresses.add(new AddressDataSet("Moskovskaya"));
UserDataSet user2 = new UserDataSet(
"sully",
addresses,
new PhoneDataSet("+67 890 344 4422")
);
UserDataSet user3 = new UserDataSet(
"bobby",
Collections.singletonList(new AddressDataSet("Borskayaa")),
new PhoneDataSet("+54 500 711 2088")
);
UserDataSet user4 = new UserDataSet(
"molly",
Arrays.asList(new AddressDataSet("Krasnaya"), new AddressDataSet("Podvodnikov")),
new PhoneDataSet("+99 000 999 8709")
);
CompanyDataSet anex = new CompanyDataSet("Anex");
CompanyDataSet biblio = new CompanyDataSet("Biblio");
dbService.save(anex);
dbService.save(biblio);
anex.addEmployees(Arrays.asList(user1, user2));
biblio.addEmployees(Arrays.asList(user3, user4));
dbService.save(user1);
dbService.save(user2);
dbService.save(user3);
dbService.save(user4);
}
}
|
Java
|
UTF-8
| 1,375
| 2.171875
| 2
|
[] |
no_license
|
package com.tiger.golf.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
public class CustomerBodyInfo implements Serializable {
private Integer id;
private Integer cid;
private Integer height;
private Double weight;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", cid=").append(cid);
sb.append(", height=").append(height);
sb.append(", weight=").append(weight);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
Java
|
UTF-8
| 133
| 1.867188
| 2
|
[] |
no_license
|
package com.baiyu.java;
public class Test04 {
public static void main(String[] args) {
System.out.println(7/2);
}
}
|
Python
|
UTF-8
| 1,694
| 2.640625
| 3
|
[] |
no_license
|
import time
import json
from flask import Flask, request
from flask import jsonify
import os
import subprocess
app = Flask(__name__)
current_angle = 0
@app.route('/')
def homepage():
return "HI MAN HERRO"
@app.route('/api/v1/setup/camera')
def setup_camera():
if request.method == 'POST':
call(["./serv","0"])
return jsonify({"Status":"Success"})
else: return jsonify({"Status":"Failure"})
@app.route('/api/v1/camera',methods=['GET','POST'])
def camera_control():
if request.method == 'POST':
servo_req = request.json
key = servo_req['key']
os.system("./serv 180")
subprocess.call(['/var/www/FlaskApp/FlaskApp/.serv','180'],shell=True)
#cmd = ["./serv","180"]
#p = subprocess.Popen(cmd,stdout = subprocess.PIPE,stderr = subprocess.PIPE, stdin = subprocess.PIPE)
#out , err = p.communicate()
#if key == 'left':
# if current_angle != 0:
# current_angle = current_angle - 30
# call(["./serv",str(current_angle)])
# return jsonify({"Status":"Success"})
#elif key == 'right':
# if current_angle != 180:
# current_angle = current_angle + 30
# call(["./serv",str(current_angle)])
# return jsonify({"Status","Success"})
#return jsonify({"Status":"Failure"})
@app.route('/api/v1/motors', methods=['GET','POST'])
def motor_control():
if request.method == 'POST':
motor_req = request.json
key = motor_req['key']
dev = os.open("/dev/memory",os.O_RDWR)
if key == 'left':
data = "L"
os.write(dev,data)
return jsonify({"Status":"success"})
elif key == 'right':
data = "R"
os.write(dev,data)
return jsonify({"Status":"success"})
return jsonify({"Status":"Failure"})
if __name__ == "__main__":
app.run()
|
Python
|
UTF-8
| 942
| 3.078125
| 3
|
[] |
no_license
|
import spacy
nlp = spacy.load('en')
#apply the pipeline to the sample sentence
doc = nlp(u'I want to place an order for a pizza.')
# extract the direct object and its transitive verb
dobj = ''
tverb = ''
for token in doc:
if token.dep_ == 'dobj':
dobj = token
tverb = token.head
# extract the verb for the intent's definition
intentVerb = ''
verbList = ['want', 'like', 'need', 'order']
if tverb.text in verbList:
intentVerb = tverb
else:
if tverb.head.dep_ == 'ROOT':
intentVerb = tverb.head
# extract the object for the intent's definition
intentObj = ''
objList = ['pizza', 'cola']
if dobj.text in objList:
intentObj = dobj
else:
for child in dobj.children:
if child.dep_ == 'prep':
intentObj = list(child.children)[0]
break
elif child.dep_ == 'compound':
intentObj = child
break
# print the intent expressed in the sample sentence
print(intentVerb.text + intentObj.text.capitalize())
|
C#
|
UTF-8
| 944
| 2.890625
| 3
|
[] |
no_license
|
using ClassLibrary1;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
public static Test Test;
public static BackgroundWorker worker = new BackgroundWorker();
public static void OnWorkerChanged(object sender, EventArgs args)
{
Console.WriteLine(Test.ConsoleText);
}
public static void worker_DoWork(object sender, DoWorkEventArgs e)
{
Test.Run();
}
static void Main(string[] args)
{
Test = new Test();
Test.ConsoleChanged += OnWorkerChanged;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
Console.ReadKey(true);
}
}
}
|
Markdown
|
UTF-8
| 1,795
| 3
| 3
|
[] |
no_license
|
---
layout: post
title: Ch 13 Discussion
---
A group decision system is being built over a network, which has inherent delays due to network lag. Suggest the longest acceptable amount of time the delay could last without affecting the user negatively. Provide an argument for the time you selected.
System confirming the user's password when logging on.
I believe that from my own experience logging in to systems, thirty seconds is when I begin to become very frustrated.
Synchronous group editing of a document.
Editing of a document should be almost instantaneous. If there are many delays over half a second long, I believe users would become frustrated.
Asynchronous critiquing of other participants' work.
Because the system is asynchronous, network lag doesn't matter so much. Even if the network lag is very long, the users will still be able to critique their partner's work in a timely manner.
Voting on serious issues.
For something the user perceives to be serious, the lag shouldn't exceed fifteen seconds or else they might begin to become impatient or frustrated.
Discuss three human values that are necessary to be understood by interface designers in order to ensure a timely user experience.
People value feedback, familiarity, and speed.
Provide an argument explaining why delays should be kept short for everyday tasks of a user, using short-term and working memory as the basis for your argument.
Because short-term memory has a very short lifespan, delays must be kept low so that users don't forget what they are doing.
State a few system response time (SRT) guidelines.
Users prefer shorter response times, longer response times (greater than fifteen seconds) are disruptive, Users' usage profiles change as a function of response time, etc.
|
Java
|
UTF-8
| 3,768
| 2.859375
| 3
|
[] |
no_license
|
package com.cao.balance;
import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.common.utils.AtomicPositiveInteger;
import com.alibaba.dubbo.rpc.Invoker;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author 曹文艳 (caowy@cloud-young.com)
* @version V1.0
* @description
* @date 2019年05月10日 09:55
*/
public class RoundRobinTest {
private static final ConcurrentMap<String, AtomicPositiveInteger> sequences = new ConcurrentHashMap<String, AtomicPositiveInteger>();
private static final ConcurrentMap<String, AtomicPositiveInteger> indexSeqs = new ConcurrentHashMap<String, AtomicPositiveInteger>();
static String key = "api.method";
public static void main(String[] args) throws Exception {
List<WeightC> list = new ArrayList<WeightC>();
list.add(getWeight("A", 5));
list.add(getWeight("B", 2));
list.add(getWeight("C", 1));
for( int i = 0 ; i < 8 ; i ++ ) {
System.out.println(doSelect(list).toString());
}
System.out.println(indexSeqs.get(key).get());
}
protected static WeightC doSelect(List<WeightC> invokers) {
int length = invokers.size();
int maxWeight = 0;
int minWeight = Integer.MAX_VALUE;
final List<WeightC> invokerToWeightList = new ArrayList();
// 查找最大和最小权重
for (int i = 0; i < length; i++) {
int weight = invokers.get(i).weight;
maxWeight = Math.max(maxWeight, weight);
minWeight = Math.min(minWeight, weight);
if (weight > 0) {
invokerToWeightList.add(invokers.get(i));
}
}
// 获取当前服务对应的调用序列对象 AtomicPositiveInteger
AtomicPositiveInteger sequence = sequences.get(key);
if (sequence == null) {
// 创建 AtomicPositiveInteger,默认值为0
sequences.putIfAbsent(key, new AtomicPositiveInteger());
sequence = sequences.get(key);
}
// 获取下标序列对象 AtomicPositiveInteger
AtomicPositiveInteger indexSeq = indexSeqs.get(key);
if (indexSeq == null) {
// 创建 AtomicPositiveInteger,默认值为 -1
indexSeqs.putIfAbsent(key, new AtomicPositiveInteger(-1));
indexSeq = indexSeqs.get(key);
}
if (maxWeight > 0 && minWeight < maxWeight) {
length = invokerToWeightList.size();
while (true) {
int index = indexSeq.incrementAndGet() % length;
int currentWeight = sequence.get() % maxWeight;
// 每循环一轮(index = 0),重新计算 currentWeight
if (index == 0) {
currentWeight = sequence.incrementAndGet() % maxWeight;
}
// 检测 Invoker 的权重是否大于 currentWeight,大于则返回
if (invokerToWeightList.get(index).weight > currentWeight) {
return invokerToWeightList.get(index);
}
}
}
// 所有 Invoker 权重相等,此时进行普通的轮询即可
return invokers.get(sequence.incrementAndGet() % length);
}
public static WeightC getWeight (String name, int weight) {
WeightC weightC = new WeightC();
weightC.name = name;
weightC.weight = weight;
return weightC;
}
static class WeightC {
String name;
int weight;
public WeightC(){};
@Override
public String toString() {
return "WeightC [name: " +name+ ", weight : " + weight + "]";
}
}
}
|
Java
|
UTF-8
| 1,865
| 1.773438
| 2
|
[] |
no_license
|
package com.duoweidu.cases.hsq.openapi;
import com.duoweidu.cases.interfaces.HsqInterfaceTest;
import com.duoweidu.config.sql.SqlDetail;
import com.duoweidu.model.hsq.UserEditcartskuData;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.testng.annotations.Test;
import java.util.LinkedList;
import java.util.List;
public class UserEditcartsku extends HsqInterfaceTest {
private UserEditcartskuData model;
@Test(dependsOnGroups = "addskutocart", description = "编辑购物车", groups = "editsku")
public void userEditcartsku(){
setUrl("user.editcartsku.uri");
List<NameValuePair> list = new LinkedList<>();
list.add(new BasicNameValuePair("Content-Type", SqlDetail.getInstance().getParamValue(0,"Content-Type")));
list.add(new BasicNameValuePair("skuId",SqlDetail.getInstance().getParamValue("goskuId")));
list.add(new BasicNameValuePair("newSkuId",SqlDetail.getInstance().getParamValue("gonewskuId")));
list.add(new BasicNameValuePair("amount",SqlDetail.getInstance().getParamValue("gonewamount")));
process(list,true,false);
// model = sparseJson(UserEditcartskuData.class);
// detailAssert();
}
private void detailAssert() {
detailAssertTest("type", model.type);
detailAssertTest("item.id", model.item.id);
detailAssertTest("item.sku_id", model.item.sku_id);
detailAssertTest("item.name", model.item.name);
detailAssertTest("item.pic", model.item.pic);
detailAssertTest("item.attrs", model.item.attrs);
detailAssertTest("item.price", model.item.price);
detailAssertTest("item.amount", model.item.amount);
detailAssertTest("item.max_cart_nums", model.item.max_cart_nums);
detailAssertTest("item.active", model.item.active);
}
}
|
Markdown
|
UTF-8
| 7,748
| 2.703125
| 3
|
[] |
no_license
|
# Robot Framework General Notes
A generic test automation framework for acceptance testing
Acceptance test-driven development (ATDD)
utilizes keyword-driven testing approach
Essentially, the script that is written in the IDE will be given to a webdriver which will then connect with the web for testing the script
Note: for pycharm IDE we need to install Intellibot plugin
## Setup:
> * Install python
> * Download python from python.org
> * On Windows, go to c: drive and find the download python folder (most likely in Program Files x86 folder)
> * Go to the scripts folder inside and copy the file path
> * Right click on 'This PC' > click on properties
> * Click on advanced system settings > Advanced tab > Environment variables
> * Under 'System Variables' click on 'Path' > edit > new
> * Past the copied file path and click 'Ok' to exit all windows
> * Pip should be installed with python, to check if python and pip is properly installed, go to terminal and type in 'python --version' and 'pip --version' which should give us the version numbers for each
> * Install Pycharm IDE
> * Install Selenium - optional
> * `pip install selenium`
> * Install robot framework
> * `pip install robotframework`
> * Install robot framework selenium library
> * `pip install robotframework-seleniumlibrary`
>
> Note: we can check if these are installed by typing in `pip list` which will show a list of python packages installed
>
> Inside pycharm, create a project
>
> * Go to file > settings > Project: 'name_of_project' > Python interpreter
> * Click on the '+'
> * Search for selenium (if installed), robotframework, and robotframework-seleniumlibrary and install those packages
>
> Note: for every new project created, we need to do this step if we want to use robotframework
>
> Now go to plugins
>
> * Install 'Intellibot @Selenium...'
Note: for test cases using this framework will be `.robot`
## Multiple Sections (Multiple Test Cases)
First section is the settings: `*** Settings ***`
> Here we add libraries by importing
>
> Ex: `Library SeleniumLibrary`
Next section is variables: `*** Variables ***`
> Here we defined variables that are commonly used in each test case
>
> Ex: `${var_name} <tab> value`
>
> `${browser} chrome`
Test case section: `*** Test Cases ***`
> Here we can write multiple test cases
>
> Layout:
>
> ```python
> *** Test Cases ***
> name_of_test_case
> create webdriver browser <tab> executable_path="path_of_driver_on_local_machine\driver_name"
> keyword <tab space> parameter <tab space> browser <tab>
> ```
>
> Note: for browser, if using chrome, firefox, edge, etc. We need to download driver from selenium's website > https://www.selenium.dev/downloads/
>
> > should keep a drivers folder and store the different drivers in there
>
> Note: instead of adding `create webdriver broser....` to every test case, we can add the `.exe` file of the webdriver to the python/scripts folder to avoid writing that line (but we must make sure that we added the PATH in our PC from the setup stage)
>
> Ex:
>
> ```python
> *** Test Cases ***
> LoginTest
> #if we did NOT add the driver to our Python/scripts folder, otherwise we can ignore it
> create webdriver chrome executable_path="C:\drivers\chromedriver.exe"
> open browser https://www.nopcommerce.com/en/demo chrome
> click link xpath://a[contains(text(),'Log in')] #get the xpath from inspection
> input text id:Email pavanoltraining@gmail.com #get id from inspection
> input text id:Password Test@123 #get id from inspection
> click element xpath://body/div[6]/section[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[2]/form[1]/div[2]/div[4]/input[1]
> close browser #closes the browser
>
> ```
>
> Note: to get xpath, we need to inspect the page and copy the xpath url link (easier way is to get the chropath extension)
>
> For testing text boxes (username, password, etc) we use `input text` keyword
keywords section: `*** Keywords ***`
> Here we defined our own keywords
>
> Ex:
>
> ```python
> new_keyword
> #we can add steps to a test case
> #ex
> loginToApp
> #if we did NOT add the driver to our Python/scripts folder, otherwise we can ignore it
> create webdriver chrome executable_path="C:\drivers\chromedriver.exe"
> click link xpath://a[contains(text(),'Log in')] #get the xpath from inspection
> input text id:Email pavanoltraining@gmail.com #get id from inspection
> input text id:Password Test@123 #get id from inspection
> click element xpath://body/div[6]/section[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[2]/form[1]/div[2]/div[4]/input[1]
>
>
> #now we can do
> *** Test Cases ***
> LoginTest
> open browser ${url} ${browser}
> loginToApp
> close browser
>
> ```
>
> Note: think of keywords as functions in programming
>
> More selenium keywords in references
## Running the test case
To run our test cases, we go in the terminal and type in `robot directory\filename.robot`
> More detailed:
>
> `robot -d nameOfFolderToStoreResults <path>\nameOfFile.robot`
>
> ex:
>
> `robot -d results testCases\websiteTest.robot`
>
> This will store the results (log and report.html files) in a 'results' folder and run the test case
We can see a report of our results from our test cases by going into our 'venv' folder and open the 'report.html' in the browser
## Working with Text Box/Input Box
### Testing visibility of input box
> `element should be visible` and `element should be enable`
>
> Ex:
>
> ```python
> testingInputBox
> open browser ${url} ${browser}
> title should be titleOfPage
> #creating a variable
> ${"email_txt"} set variable id:email
>
> element should be visible ${"email_text"}
> element should be enable ${"email_text"}
>
> #initializing the variable
> input text ${"email_txt"} someemail@gmail.com
> ```
>
> Note: we also have `element should not be visible/enable`
## Notes on `set variable`
Note: go to ex in Working with text box/input box section to see the usage of `set variable`
> We can think of `${"email_txt"} set variable id:email` in terms of c++ as:
>
> > `email email_txt` or as `varType varName`
>
> Then initializing `input text ${"email_txt"} someemail@gmail.com` in terms of c++:
>
> > `email_txt = someemail@gmail.com`
## Selecting Radio Buttons & Check Boxes
`select radio button` keyword
> Get the name and the value by inspecting page
>
> `select radio button name value`
>
> ex:
>
> `select radio button sex Female`
`select checkbox`
> Get name/id of checkbox element
>
> `select checkbox name/id`
>
> ex:
>
> `select checkbox here`
>
> Note: if it is already checked, then it will do nothing
`unselect checkbox`
> same concept as checking checkbox but we just use the `unselect` keyword
## Keywords
### title should be
> `title should be <tab> <title_of_page>`
> Need to inspect page and get <title> element
>
> Verifies the title of the page
### maximize browser window
> maximizes the browser
### sleep value
> `sleep 5`
>
> this will put a pause for 5 seconds before continuing to the next test step
### set selenium speed time
> `set selenium speed time` will set a pace for each step being executed
>
> ex:
>
> `set selenium speed 2seconds` will set a 2 second pace for each statement
## References
Robot framework BuiltIn Documentation: https://robotframework.org/robotframework/2.1.2/libraries/BuiltIn.html
Link to see selenium keywords: http://robotframework.org/SeleniumLibrary/SeleniumLibrary.html#Keywords
|
C++
|
SHIFT_JIS
| 2,194
| 3.03125
| 3
|
[] |
no_license
|
#include "CSVConverter.h"
#include<fstream>
#include<sstream>
#include<stdexcept>
CSVConverter::CSVConverter(const std::string fileName) :
file_name_{ fileName }
{
Load();
}
void CSVConverter::Load()
{
std::ifstream file(file_name_);
//t@Cǂݍ߂Ȃ
if (!file)throw std::runtime_error("CSVt@CI[vł܂ł");
std::string line;
int line_count = 0;
Data data_;
std::ofstream test("output/test.txt");
//sǂݍ
while (std::getline(file, line))
{
if (!one_) {
std::istringstream streng_stream_i(line);
std::string value;
int count = 0;
//J}œǂݍ
while (std::getline(streng_stream_i, value, ','))
{
switch (count)
{
case 0:output_file_name_ = value; break;
case 1:bpm_ = atoi(value.c_str());
default:
break;
}
count++;
}
one_ = true;
continue;
}
int rane_count = 1;
std::istringstream streng_stream_i(line);
std::string value;
//J}œǂݍ
while (std::getline(streng_stream_i, value, ','))
{
//b̌vZ@K
if (atoi(value.c_str()) > 0) {
time_ = 60 * line_count / bpm_ * atoi(value.c_str());
//ǂݍi珇jɃ[Ƃ̔zɊi[Ă
switch (rane_count)
{
case 1: rane_1.push_back(time_); break;
case 2: rane_2.push_back(time_); break;
case 3: rane_3.push_back(time_); break;
case 4: rane_4.push_back(time_); break;
default:break;
}
data_.lane_ = rane_count;
data_.time_ = time_;
note_data_.push_back(data_);
test <<
data_.lane_ << "," <<
data_.time_ << "\n";
}
rane_count++;
}
line_count++;
}
std::ofstream output("output/" + output_file_name_ + ".txt");
Output(output, rane_1);
Output(output, rane_2);
Output(output, rane_3);
Output(output, rane_4);
output.close();
test.close();
}
void CSVConverter::Output(std::ofstream & outputFile, std::list<float> rane)
{
int count = 0;
for (float c : rane)
{
count++;
outputFile << c;
if (count == (int)rane.size())
outputFile << "\n";
else
outputFile << ",";
}
}
|
Markdown
|
UTF-8
| 2,997
| 2.6875
| 3
|
[] |
no_license
|
# Customer Management System
このアプリケーションは顧客管理を目的としたアプリです。
氏名・住所・年齢などの情報や個人ごとにメモを残したりすることができます。
### 機能一覧
管理ユーザー登録機能/管理ユーザーログイン機能/顧客登録機能/顧客詳細表示機能/顧客編集機能/顧客検索機能/メモ投稿機能/地図表示機能/単体テスト機能
## 本番環境
URL: https://cm-system.herokuapp.com/<br>email: test@gmail.com<br>pass: test11
## DEMO
##### 顧客検索とメモ機能


## 制作背景
このアプリは私が前職で営業をやっていた時に感じた不便さを解消してみたいという思いから作成しました。
できるだけシンプルにわかりやすく設計しつつ、必要な機能はきちんと盛り込んである。そんなアプリを目指しました。
## 使用技術
Ruby
Ruby on Rails
javascript
Github
MySQL
## 工夫したポイント
使い方が直感でわかるようシンプルな設計に、それでいて痒いところには手が届く機能を盛り込みました。
## 今後実装したい機能
今は地図を検索フォームに入れて入力することで表示させているが、DBの登録住所から表示できるように仕様変更する。
## DB設計
### users テーブル
| Column | Type | Options |
| ----------- | ------ | ----------- |
| name | string | null: false |
| email | string | null: false |
| password | string | null: false |
#### Association
- has_many :cusotmers
- has_one :comments
### customers テーブル
| Column | Type | Options |
| ---------------- | ------ | ----------- |
| family_name | string | null: false |
| first_name | string | null: false |
| family_name_kana | string | null: false |
| first_name_kana | string | null: false |
| birthday | date | null: false |
| gender | string | null: false |
| age | string | null: false |
| postal_code | string | null: false |
| address | string | null: false |
| building_name | string | |
| phone_number | string | null: false |
| e-mail | string | |
#### Association
- belongs_to :user
- has_many :comments
### comments テーブル
| Column | Type | Options |
| ------------ | ---------- | ------------------------------ |
| content | string | null: false |
| customer_id | references | null: false, foreign_key: true |
| user_id | references | null: false, foreign_key: true |
#### Association
- belongs_to :customer
- belongs_to :user
|
Python
|
UTF-8
| 3,187
| 2.546875
| 3
|
[] |
no_license
|
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import RMSprop, Adam, SGD
from tensorflow import keras
import tensorflow as tf
import numpy as np
print("Importing Done...")
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
if logs is None:
logs = {}
if logs.get("accuracy") > 0.985:
print("\nReached 99.8% accuracy so cancelling training!")
self.model.stop_training = True
callback = myCallback()
def build(h, w, d, classes=1):
model = keras.Sequential([
keras.layers.Conv2D(32, (5, 5), activation="relu", padding="same", input_shape=(h, w, d)),
keras.layers.BatchNormalization(axis=-1),
keras.layers.MaxPool2D((2, 2)),
keras.layers.Conv2D(32, (3, 3),padding="same", activation="relu"),
keras.layers.BatchNormalization(axis=-1),
keras.layers.MaxPool2D((2, 2)),
keras.layers.Conv2D(32, (3, 3),padding="same", activation="relu"),
keras.layers.BatchNormalization(axis=-1),
keras.layers.MaxPool2D((2, 2)),
# keras.layers.Conv2D(32, (5, 5), activation="relu"),
# keras.layers.BatchNormalization(axis=-1),
# keras.layers.MaxPool2D((2, 2)),
keras.layers.Flatten(),
keras.layers.Dense(256, activation="relu"),
keras.layers.Dropout(0.3),
keras.layers.Dense(32, activation="relu"),
keras.layers.Dropout(0.3),
# keras.layers.Dense(16, activation="relu"),
# keras.layers.Dropout(0.3),
keras.layers.Dense(1, activation="sigmoid"),
])
return model
train_path = "Datasets/train/"
validation_path = "Datasets/validation/"
BATCH_SIZE = 64
NUM_EPOCH = 100
EPOCH_PER_STEP = 8
HEIGHT = 256
WIDTH = 256
DEPTH = 3
classes = 2
learn = 0.01
print("Data Generating...")
train_datagen = ImageDataGenerator(rescale=1 / 255, rotation_range=30,
zoom_range=0.15, width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.15,
horizontal_flip=True,
fill_mode="nearest")
vaildation_datagen = ImageDataGenerator(rescale=1 / 255)
print("Data loading...")
train_generator = train_datagen.flow_from_directory(
'Datasets/train',
target_size=(256, 256),
batch_size=BATCH_SIZE,
class_mode='binary')
validation_generator = vaildation_datagen.flow_from_directory(
'Datasets/validation',
target_size=(256, 256),
batch_size=BATCH_SIZE,
class_mode='binary')
print("Model Building...")
model = build(HEIGHT, WIDTH, DEPTH, classes)
print("Compling.....")
model.compile(loss='binary_crossentropy',
optimizer="adam",
metrics=["accuracy"])
print("Traning Started...")
history = model.fit(
train_generator,
steps_per_epoch=EPOCH_PER_STEP,
epochs=NUM_EPOCH,
verbose=1,
validation_data=validation_generator,
validation_steps=EPOCH_PER_STEP,
callbacks=[callback])
print("Saving Model...")
model.save("model1.h5")
print("Program Done!")
|
Python
|
UTF-8
| 308
| 3.421875
| 3
|
[
"MIT"
] |
permissive
|
#ENTRADA
algo = input('\033[35mDigite qualquer coisa: ')
print(type(algo))
#SAÍDA DE DADOS
print(algo.isupper())
print(algo.isnumeric())
print(algo.isalpha())
print(algo.islower())
print(algo.isascii())
print(algo.isdigit())
print(algo.isspace())
print(algo.isidentifier())
print(algo.istitle())
|
Go
|
UTF-8
| 42,119
| 2.96875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package parser_test
import (
"strings"
"github.com/bytesparadise/libasciidoc/pkg/parser"
"github.com/bytesparadise/libasciidoc/pkg/types"
. "github.com/bytesparadise/libasciidoc/testsupport"
log "github.com/sirupsen/logrus"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("tables", func() {
Context("in final documents", func() {
It("1-line table with 2 cells and custom border styling", func() {
source := `[frame=ends,grid=rows]
|===
| *cookie* cookie | _pasta_
|===
`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrFrame: "ends",
types.AttrGrid: "rows",
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.QuotedText{
Kind: types.SingleQuoteBold,
Elements: []interface{}{
&types.StringElement{
Content: "cookie",
},
},
},
&types.StringElement{
Content: " cookie",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.QuotedText{
Kind: types.SingleQuoteItalic,
Elements: []interface{}{
&types.StringElement{
Content: "pasta",
},
},
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("1-line table with 3 cells", func() {
source := `|===
| *cookie* cookie | _pasta_ | chocolate
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.QuotedText{
Kind: types.SingleQuoteBold,
Elements: []interface{}{
&types.StringElement{
Content: "cookie",
},
},
},
&types.StringElement{
Content: " cookie",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.QuotedText{
Kind: types.SingleQuoteItalic,
Elements: []interface{}{
&types.StringElement{
Content: "pasta",
},
},
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "chocolate",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("2-line table with 3 cells", func() {
source := `|===
| some cookies | some chocolate | some pasta
| more cookies | more chocolate | more pasta
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "some cookies",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "some chocolate",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "some pasta",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "more cookies",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "more chocolate",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "more pasta",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with compact rows", func() {
source := `|===
|h1|h2|h3
|one|two|three
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "h1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "h2",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "h3",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "one",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "two",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "three",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with title, headers and 1 line per cell", func() {
source := `.table title
|===
|header 1 |header 2
|row 1, column 1
|row 1, column 2
|row 2, column 1
|row 2, column 2
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrTitle: "table title",
},
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "header 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "header 2",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 1, column 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 1, column 2",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 2, column 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 2, column 2",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with title, headers, id and multiple roles, stretch", func() {
source := `.table title
[#anchor.role1%autowidth.stretch]
|===
|header 1 |header 2
|row 1, column 1
|row 1, column 2
|row 2, column 1
|row 2, column 2
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrTitle: "table title",
types.AttrOptions: types.Options{"autowidth"},
types.AttrRoles: types.Roles{"role1", "stretch"},
types.AttrID: "anchor",
},
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "header 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "header 2",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 1, column 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 1, column 2",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 2, column 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 2, column 2",
},
},
},
},
},
},
},
},
},
},
ElementReferences: types.ElementReferences{
"anchor": "table title",
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with unseparated rows", func() {
source := `|===
|header 1 |header 2
|row 1, column 1
|row 1, column 2
|row 2, column 1
|row 2, column 2
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "header 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "header 2",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 1, column 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 1, column 2",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 2, column 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 2, column 2",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with unbalanced rows", func() {
source := `|===
|header 1 |header 2
|row 1, column 1
|row 1, column 2
|row 2, column 1 |row 2, column 2
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "header 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "header 2",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 1, column 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 1, column 2",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 2, column 1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "row 2, column 2",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("empty table ", func() {
source := `|===
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with cols attribute", func() {
source := `[cols="2*^.^,<,.>"]
|===
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrCols: []interface{}{
&types.TableColumn{
Multiplier: 2,
HAlign: types.HAlignCenter,
VAlign: types.VAlignMiddle,
Weight: 1,
},
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
},
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignBottom,
Weight: 1,
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("columns as document attribute", func() {
source := `:cols: pass:[2*^.^d,<e,.>s]
[cols={cols}]
|===
|===`
expected := &types.Document{
Elements: []interface{}{
&types.AttributeDeclaration{
Name: "cols",
Value: []interface{}{
&types.InlinePassthrough{
Kind: types.PassthroughMacro,
Elements: []interface{}{
&types.StringElement{
Content: "2*^.^d,<e,.>s",
},
},
},
},
},
&types.Table{
Attributes: types.Attributes{
types.AttrCols: []interface{}{
&types.TableColumn{
Multiplier: 2,
HAlign: types.HAlignCenter,
VAlign: types.VAlignMiddle,
Style: types.DefaultStyle,
Weight: 1,
},
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Style: types.EmphasisStyle,
Weight: 1,
},
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignBottom,
Style: types.StrongStyle,
Weight: 1,
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with header option", func() {
source := `[cols="3*^",options="header"]
|===
|Dir (X,Y,Z) |Num Cells |Size
|X |10 |0.1
|Y |5 |0.2
|Z |10 |0.1
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrCols: []interface{}{
&types.TableColumn{
Multiplier: 3,
HAlign: types.HAlignCenter,
VAlign: types.VAlignTop,
Weight: 1,
},
},
types.AttrOptions: types.Options{"header"},
},
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Dir (X,Y,Z)",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Num Cells",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Size",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "X",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "10",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "0.1",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Y",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "5",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "0.2",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Z",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "10",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "0.1",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with header col option", func() {
source := `[cols="h,>,>",options="header"]
|===
|Dir (X,Y,Z) |Num Cells |Size
|X |10 |0.1
|Y |5 |0.2
|Z |10 |0.1
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrCols: []interface{}{
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignDefault,
VAlign: types.VAlignDefault,
Weight: 1,
Style: types.HeaderStyle,
},
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignRight,
VAlign: types.VAlignDefault,
Weight: 1,
},
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignRight,
VAlign: types.VAlignDefault,
Weight: 1,
},
},
types.AttrOptions: types.Options{"header"},
},
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Dir (X,Y,Z)",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Num Cells",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Size",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
// Format: string(types.HeaderStyle),
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "X",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "10",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "0.1",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
// Format: string(types.HeaderStyle),
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Y",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "5",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "0.2",
},
},
},
},
},
},
},
{
Cells: []*types.TableCell{
{
// Format: string(types.HeaderStyle),
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Z",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "10",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "0.1",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with header and footer options", func() {
source := `[%header%footer,cols="2,2,1"]
|===
|Column 1, header row
|Column 2, header row
|Column 3, header row
|Cell in column 1, row 2
|Cell in column 2, row 2
|Cell in column 3, row 2
|Column 1, footer row
|Column 2, footer row
|Column 3, footer row
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrCols: []interface{}{
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 2,
},
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 2,
},
&types.TableColumn{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
},
},
types.AttrOptions: types.Options{"header", "footer"},
},
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Column 1, header row",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Column 2, header row",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Column 3, header row",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Cell in column 1, row 2",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Cell in column 2, row 2",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Cell in column 3, row 2",
},
},
},
},
},
},
},
},
Footer: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Column 1, footer row",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Column 2, footer row",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "Column 3, footer row",
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("columns with header and alignment changes", func() {
source := `[cols="2*^.^,<,.>,>"]
|===
|h1|h2|h3|h4|h5
|one|two|three|four|five
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrCols: []interface{}{
&types.TableColumn{
Multiplier: 2,
HAlign: "^",
VAlign: "^",
Weight: 1,
},
&types.TableColumn{
Multiplier: 1,
HAlign: "<",
VAlign: "<",
Weight: 1,
},
&types.TableColumn{
Multiplier: 1,
HAlign: "<",
VAlign: ">",
Weight: 1,
},
&types.TableColumn{
Multiplier: 1,
HAlign: ">",
VAlign: "<",
Weight: 1,
},
},
},
Header: &types.TableRow{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "h1",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "h2",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "h3",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "h4",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "h5",
},
},
},
},
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "one",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "two",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "three",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "four",
},
},
},
},
},
{
Elements: []interface{}{
&types.Paragraph{
Elements: []interface{}{
&types.StringElement{
Content: "five",
},
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with basic image blocks in cells", func() {
source := `[cols="2*^"]
|===
a|
image::image.png[]
a|
image::another-image.png[]
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrCols: []interface{}{
&types.TableColumn{
Multiplier: 2,
HAlign: types.HAlignCenter,
VAlign: types.VAlignTop,
Weight: 1,
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Format: "a",
Elements: []interface{}{
&types.ImageBlock{
Location: &types.Location{
Path: "image.png",
},
},
},
},
{
Format: "a",
Elements: []interface{}{
&types.ImageBlock{
Location: &types.Location{
Path: "another-image.png",
},
},
},
},
},
},
},
},
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
It("with image blocks with attributes in cells", func() {
source := `[cols="2*^"]
|===
a|
[#image-id]
.An image
image::image.png[]
a|
[#another-image-id]
.Another image
image::another-image.png[]
|===`
expected := &types.Document{
Elements: []interface{}{
&types.Table{
Attributes: types.Attributes{
types.AttrCols: []interface{}{
&types.TableColumn{
Multiplier: 2,
HAlign: types.HAlignCenter,
VAlign: types.VAlignTop,
Weight: 1,
},
},
},
Rows: []*types.TableRow{
{
Cells: []*types.TableCell{
{
Format: "a",
Elements: []interface{}{
&types.ImageBlock{
Attributes: types.Attributes{
types.AttrID: "image-id",
types.AttrTitle: "An image",
},
Location: &types.Location{
Path: "image.png",
},
},
},
},
{
Format: "a",
Elements: []interface{}{
&types.ImageBlock{
Attributes: types.Attributes{
types.AttrID: "another-image-id",
types.AttrTitle: "Another image",
},
Location: &types.Location{
Path: "another-image.png",
},
},
},
},
},
},
},
},
},
ElementReferences: types.ElementReferences{
"image-id": "An image",
"another-image-id": "Another image",
},
}
Expect(ParseDocument(source)).To(MatchDocument(expected))
})
})
})
var _ = Describe("table cols", func() {
DescribeTable("valid",
func(source string, expected []*types.TableColumn) {
// given
log.Debugf("processing '%s'", source)
content := strings.NewReader(source)
// when parsing only (ie, no substitution applied)
result, err := parser.ParseReader("", content, parser.Entrypoint("TableColumnsAttribute"))
// then
Expect(err).NotTo(HaveOccurred())
Expect(result).To(BeAssignableToTypeOf([]interface{}{}))
cols := result.([]interface{})
// now, set the attribute in the table and call the `Columns()` method
t := &types.Table{
Attributes: types.Attributes{
types.AttrCols: result,
},
Rows: []*types.TableRow{{}},
}
t.Rows[0].Cells = make([]*types.TableCell, len(cols))
for i := range cols {
t.Rows[0].Cells[i] = &types.TableCell{}
}
Expect(t.Columns()).To(Equal(expected))
},
Entry(`1`, `1`,
[]*types.TableColumn{
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
Width: "100",
},
}),
Entry(`3*^`, `3*^`,
[]*types.TableColumn{
{
Multiplier: 3,
HAlign: types.HAlignCenter,
VAlign: types.VAlignTop,
Weight: 1,
Width: "33.3333",
},
{
Multiplier: 3,
HAlign: types.HAlignCenter,
VAlign: types.VAlignTop,
Weight: 1,
Width: "33.3333",
},
{
Multiplier: 3,
HAlign: types.HAlignCenter,
VAlign: types.VAlignTop,
Weight: 1,
Width: "33.3334",
},
}),
Entry(`20,~,~`, `20,~,~`,
[]*types.TableColumn{
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 20,
Width: "20",
},
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Autowidth: true,
Width: "",
},
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Autowidth: true,
Width: "",
},
}),
Entry(`<,>`, `<,>`,
[]*types.TableColumn{
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
Width: "50",
},
{
Multiplier: 1,
HAlign: types.HAlignRight,
VAlign: types.VAlignTop,
Weight: 1,
Width: "50",
},
}),
Entry(`.<,.>`, `.<,.>`,
[]*types.TableColumn{
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
Width: "50",
},
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignBottom,
Weight: 1,
Width: "50",
},
}),
Entry(`<.<,>.>`, `<.<,>.>`,
[]*types.TableColumn{
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
Width: "50",
},
{
Multiplier: 1,
HAlign: types.HAlignRight,
VAlign: types.VAlignBottom,
Weight: 1,
Width: "50",
},
}),
Entry(`<.<1,>.>2`, `<.<1,>.>2`,
[]*types.TableColumn{
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
Width: "33.3333",
},
{
Multiplier: 1,
HAlign: types.HAlignRight,
VAlign: types.VAlignBottom,
Weight: 2,
Width: "66.6667",
},
}),
Entry(`2*<.<1,1*>.>2`, `2*<.<1,1*>.>2`,
[]*types.TableColumn{
{
Multiplier: 2,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
Width: "25",
},
{
Multiplier: 2,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Weight: 1,
Width: "25",
},
{
Multiplier: 1,
HAlign: types.HAlignRight,
VAlign: types.VAlignBottom,
Weight: 2,
Width: "50",
},
}),
// with style
Entry(`2*^.^d,<e,.>s`, `2*^.^d,<e,.>s`,
[]*types.TableColumn{
{
Multiplier: 2,
HAlign: types.HAlignCenter,
VAlign: types.VAlignMiddle,
Style: types.DefaultStyle,
Weight: 1,
Width: "25",
},
{
Multiplier: 2,
HAlign: types.HAlignCenter,
VAlign: types.VAlignMiddle,
Style: types.DefaultStyle,
Weight: 1,
Width: "25",
},
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignTop,
Style: types.EmphasisStyle,
Weight: 1,
Width: "25",
},
{
Multiplier: 1,
HAlign: types.HAlignLeft,
VAlign: types.VAlignBottom,
Style: types.StrongStyle,
Weight: 1,
Width: "25",
},
}),
)
DescribeTable("invalid",
func(source string) {
// given
log.Debugf("processing '%s'", source)
content := strings.NewReader(source)
// when parsing only (ie, no substitution applied)
_, err := parser.ParseReader("", content, parser.Entrypoint("TableColumnsAttribute"))
// then
Expect(err).To(HaveOccurred())
},
// unknown case: should return an error
Entry(`invalid`, `invalid`),
)
})
|
Java
|
UTF-8
| 1,143
| 3.34375
| 3
|
[] |
no_license
|
package barriers;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerArray;
public class Barriers {
private static final int TASKS = 5;
private static final int NUMBERS = 5000;
public static void main(String[] args) {
ThreadPoolExecutor executor =
(ThreadPoolExecutor) Executors.newFixedThreadPool(TASKS);
AtomicIntegerArray partialSums = new AtomicIntegerArray(TASKS);
Random random = new Random();
CyclicBarrier barrier = new CyclicBarrier(TASKS, new ReductionTask(partialSums));
for (int i = 0; i < TASKS; i++) {
int[] nubmers = random.ints(NUMBERS, 0, 10).toArray();
executor.execute(new Task(i, nubmers, barrier, partialSums));
}
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
System.out.println("Main thread was interrupted.");
}
executor.shutdownNow();
}
}
|
Python
|
UTF-8
| 1,038
| 2.71875
| 3
|
[] |
no_license
|
#!/usr/bin/python3
# encoding:utf-8
'''
@author: liyin
@file: testpolls.py
@time: 2018-09-29
'''
import unittest
import json
import requests
class Lesson3Test(unittest.TestCase):
def setUp(self):
self._url="http://127.0.0.1:8000"
def get_url(self, url):
r=requests.get(url)
return (r.status_code, json.loads(r.text))
def post_url(self,url,params):
r=requests.post(url,data=params)
return (r.status_code, json.loads(r.text))
def test_polls(self):
url=self._url+"/polls/2/"
code,obj=self.get_url(url)
self.assertEqual(code,200)
self.assertEqual(obj['status'],'200')
self.assertEqual(obj['data']['4'], '泰国')
def test_vote(self):
url=self._url+"/polls/2/vote/"
code,obj=self.post_url(url,{'choice':'4'})
self.assertEqual(code,200)
self.assertEqual(obj['status'],'200')
self.assertEqual(obj['data']['question'], '你喜欢去哪里旅游?')
if __name__ == '__main__':
unittest.main()
|
Python
|
UTF-8
| 14,847
| 2.65625
| 3
|
[] |
no_license
|
class Halo() :
def __init__(self,id,aexp) :
self.id = id
self.aexp = aexp
def __repr__(self):
return 'Halo(id=%d, aexp=%6.4f)' % (self.id, self.aexp)
def getId(self) :
return self.id
def getAexpn(self) :
return self.aexp
def integrate_profile ( pro, rbins, rcore=0.0 ) :
from numpy import zeros
num_bins = len(pro)
sum_profile = zeros(num_bins)
sum = 0.0
for i in range(num_bins) :
if ( rbins[i] >= rcore ):
sum += pro[i]
sum_profile[i] = sum
return sum_profile
def average_integrate_profile ( pro, rbins, weight, rcore=0.0 ) :
from numpy import zeros
num_bins = len(pro)
sum_profile = zeros(num_bins)
sum = 0.0
sum_weight = 0.0
for i in range(num_bins) :
if ( rbins[i] >= rcore ):
sum += pro[i]*weight[i]
sum_weight += weight[i]
sum_profile[i] = sum/sum_weight
return sum_profile
def find_profile_max_smooth ( pro, rbins, s=0, delta=0.1) :
from numpy import log10, amin, amax, argmin, argmax, linspace
from scipy.interpolate import UnivariateSpline
minx = amin(rbins)
maxx = amax(rbins)
x = linspace(minx,maxx, 1000)
yspline = UnivariateSpline(rbins, pro, s = s )
ys = yspline(x)
p = amax(ys)
ir = argmax(ys)
r = x[ir]
i = argmax(pro)
#rmin, rmax = (rbins[i]-rbins[i-1])/2.0,(rbins[i+1]-rbins[i])/2.0
return (p, r)
def find_profile_min_smooth ( pro, rbins, s=0, delta=0.1 ) :
from numpy import log10, amin, amax, argmin, argmax, linspace
from scipy.interpolate import UnivariateSpline, InterpolatedUnivariateSpline
from scipy.signal import savgol_filter
lrbins = log10(rbins)
minx = amin(lrbins)
maxx = amax(lrbins)
x = linspace(minx,maxx, 1000)
yspline = UnivariateSpline(lrbins, pro)
yspline.set_smoothing_factor(0.1)
ys = yspline(x)
maxtab, mintab = peakdet(ys, delta, x)
imin = argmin(mintab[:,1])
rmin = 10**(mintab[:,0][imin])
pmin = mintab[:,1][imin]
return (pmin, rmin)
def find_profile_max ( pro, rbins, delta=0.1 ) :
from numpy import log10, argmax
x = log10(rbins)
y = pro
maxtab, mintab = peakdet(y, delta, x)
imax = argmax(maxtab[:,1])
rmax = 10**(maxtab[:,0][imax])
pmax = maxtab[:,1][imax]
return (pmax, rmax)
def find_profile_min ( pro, rbins, delta=0.1 ) :
from numpy import log10, argmin
x = log10(rbins)
y = pro
maxtab, mintab = peakdet(y, delta, x)
#print mintab[:,1]
imin = argmin(mintab[:,1])
rmin = 10**(mintab[:,0][imin])
pmin = mintab[:,1][imin]
return (pmin, rmin)
def compute_density_profile ( rmid, rr, mass ) :
'''
Compute density profile (Msun h^2/kpc^3) for a given mass profile in Msun/h. Takes in radial bin in kpc/h (rmid,rr)
'''
from numpy import array, pi
num_bins = len(rmid)
rmid0 = rmid[0]
rr0 = rr[0]
mass0 = mass[0]
vol = 4./3.*pi*rr0**3
lbinr = [rmid0]
lrho = [mass0/vol]
for i in xrange(1,num_bins) :
# vol in (kpc/h)^3
vol = 4./3.*pi*(rr[i]**3-rr0**3)
lbinr.append( rmid[i] )
lrho.append( (mass[i]-mass0)/vol )
mass0 = mass[i]
rr0 = rr[i]
rho = array( lrho )
return ( rho )
def compute_density_profiles ( rmid, rr, Mdm, Mgas, Mtot ) :
'''
Compute density profile (Msun h^2/kpc^3) for DM, gas and total given their mass profiles in Msun/h. Takes in radial bin in kpc/h (rmid,rr)
'''
from numpy import array, pi
num_bins = len(rmid)
rmid0 = rmid[0]
rr0 = rr[0]
Mdm0 = Mdm[0]
Mgas0 = Mgas[0]
Mtot0 = Mtot[0]
vol = 4./3.*pi*rr0**3
lbinr = [rmid0]
lrhodm = [Mdm0/vol]
lrhoicm = [Mgas0/vol]
lrhotot = [Mtot0/vol]
for i in range(1,num_bins) :
# vol in (kpc/h)^3
vol = 4./3.*pi*(rr[i]**3-rr0**3)
lbinr.append( rmid[i] )
lrhodm.append( (Mdm[i]-Mdm0)/vol )
lrhoicm.append( (Mgas[i]-Mgas0)/vol )
lrhotot.append( (Mtot[i]-Mtot0)/vol )
rr0 = rr[i]
Mdm0 = Mdm[i]
Mgas0 = Mgas[i]
Mtot0 = Mtot[i]
rhodm = array(lrhodm)
rhoicm = array(lrhoicm)
rhotot = array(lrhotot)
return ( rhodm, rhoicm, rhotot )
def compute_diffmass_profiles ( rmid, rr, Mdm, Mgas, Mtot ) :
'''
Compute differential mass profile (Msun/h) for DM, gas and total given their mass profiles in Msun/h. Takes in radial bin in kpc/h (rmid,rr)
'''
from numpy import array, pi
num_bins = len(rmid)
rmid0 = rmid[0]
rr0 = rr[0]
Mdm0 = Mdm[0]
Mgas0 = Mgas[0]
Mtot0 = Mtot[0]
#vol = 4./3.*pi*rr0**3
lbinr = [rmid0]
lrhodm = [Mdm0]
lrhoicm = [Mgas0]
lrhotot = [Mtot0]
for i in range(1,num_bins) :
# vol in (kpc/h)^3
#vol = 4./3.*pi*(rr[i]**3-rr0**3)
lbinr.append( rmid[i] )
lrhodm.append( (Mdm[i]-Mdm0) )
lrhoicm.append( (Mgas[i]-Mgas0) )
lrhotot.append( (Mtot[i]-Mtot0) )
rr0 = rr[i]
Mdm0 = Mdm[i]
Mgas0 = Mgas[i]
Mtot0 = Mtot[i]
rhodm = array(lrhodm)
rhoicm = array(lrhoicm)
rhotot = array(lrhotot)
return ( rhodm, rhoicm, rhotot )
def calc_log_slope (x,y, m = 5) :
'''
Compute log slope. Assumes that radius are spaced uniformly in log.
Uses SG filter with default window size m = 5; polynomial or order 2
'''
#from sg_filter import *
import scipy.signal
import numpy as np
num_bins = len(x)
dlogy = scipy.signal.savgol_filter( np.log10(y), m, 2, deriv=1 )
dlogx = scipy.signal.savgol_filter( np.log10(x), m, 2, deriv=1 )
#dlogx = np.zeros(num_bins)
#for i in np.arange(len(dlogx)) :
# dlogx[i] = np.log10(x[2]) - np.log10(x[1])
dlydlx = dlogy/dlogx
return ( dlydlx )
def peakdet(v, delta, x = None):
"""
Converted from MATLAB script at http://billauer.co.il/peakdet.html
Returns two arrays
function [maxtab, mintab]=peakdet(v, delta, x)
% PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consists of two columns. Column 1
% contains indices in V, and column 2 the found values.
%
% With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices
% in MAXTAB and MINTAB are replaced with the corresponding
% X-values.
%
% A point is considered a maximum peak if it has the maximal
% value, and was preceded (to the left) by a value lower by
% DELTA.
% Eli Billauer, 3.4.05 (Explicitly not copyrighted).
% This function is released to the public domain; Any use is allowed.
"""
from numpy import NaN, Inf, arange, isscalar, asarray, array
maxtab = []
mintab = []
if x is None:
x = arange(len(v))
v = asarray(v)
if len(v) != len(x):
sys.exit('Input vectors v and x must have same length')
if not isscalar(delta):
sys.exit('Input argument delta must be a scalar')
if delta <= 0:
sys.exit('Input argument delta must be positive')
mn, mx = Inf, -Inf
mnpos, mxpos = NaN, NaN
lookformax = True
for i in arange(len(v)):
this = v[i]
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if this < mx-delta:
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if this > mn+delta:
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
return array(maxtab), array(mintab)
def find_overdensity(rhalo, rr, mtot, aexpn, crit=True, omega_m=0.27, omega_l=0.73 ) :
'''
find overdensity for given halo radius and mass profile
'''
from numpy import sqrt, array, pi, log10
Msun = 1.989e33
kpc = 3.08567758e21
H_0 = 100.0*1.e5/(1.e3*kpc)
grav_c = 6.673e-8
rho_crit = (3.0/(8.0*pi*grav_c))*H_0*H_0 / Msun * (kpc**3.0) # h^2Msun/kpc^3
Ez = sqrt(omega_m/aexpn**3.0+omega_l)
z = 1.0/aexpn-1.0
if crit :
rho_background = rho_crit*Ez**2 # h^2Msun/kpc^3
else:
# this should be the mean density, not critical
rho_background = omega_m* rho_crit /aexpn**3.0 # h^2Msun/kpc^3
# this is the average density enclosed in radius rr in kpc/h
sphvol = 4.0*pi/3.0*rr**3.0
rho_enc = log10(mtot/sphvol)
lrr = log10(rr)
i = 0
while log10(rhalo) > lrr[i] :
i += 1
# interpolate to find rhovir
# rvir = 10.0**(lrr[i-1] + (lrr[i]-lrr[i-1])/(rho_enc[i]-rho_enc[i-1]) * (log10(rho_vir) - rho_enc[i-1]))
rho_vir = 10.0**(rho_enc[i-1] + (rho_enc[i]-rho_enc[i-1])/(lrr[i]-lrr[i-1]) * (log10(rhalo)-lrr[i-1]))
overdensity = rho_vir/rho_background
return overdensity, rho_vir
def find_rvir_mvir(rr, mtot, aexpn, overdensity = 200.0, crit = True, vir=False, omega_m=0.27, omega_l=0.73):
'''
find rvir, mvir, and rho_vir given mass profile mtot, radial bins rr, expansion factor and overdensity with respect to critical (default) or mean (critical = False). Radial bins should be in [kpc/h] and mass bins in [Msun/h].
'''
from numpy import sqrt, array, pi, log10
Msun = 1.989e33
kpc = 3.08567758e21
H_0 = 100.0*1.e5/(1.e3*kpc)
grav_c = 6.673e-8
rho_crit = (3.0/(8.0*pi*grav_c))*H_0*H_0 / Msun * (kpc**3.0) # h^2Msun/kpc^3
Ez = sqrt(omega_m/aexpn**3.0+omega_l)
z = 1.0/aexpn-1.0
if crit or vir:
rho_background = rho_crit*Ez**2 # h^2Msun/kpc^3
else:
# this should be the mean density, not critical
rho_background = omega_m* rho_crit /aexpn**3.0 # h^2Msun/kpc^3
if vir :
## Use Bryan & Norman (1998) formula for virial overdensty wrt critical
omega_z = omega_m/aexpn**3./Ez**2.
overdensity = 18.0*pi*pi+82.0*(omega_z-1)-39.0*(omega_z-1)*(omega_z-1)
rho_vir = overdensity * rho_background
# this is the average density enclosed in radius rr in kpc/h
sphvol = 4.0*pi/3.0*rr**3.0
rho_enc = log10(mtot/sphvol)
lrr = log10(rr)
i = 0
while rho_enc[i] > log10(rho_vir) :
i += 1
if i >= len(rho_enc) :
break
# interpolate to find rvir
if i < len(rho_enc) :
rvir = 10.0**(lrr[i-1] + (lrr[i]-lrr[i-1])/(rho_enc[i]-rho_enc[i-1]) * (log10(rho_vir) - rho_enc[i-1]))
else :
rvir = 10.0**(lrr[-1])
mvir = 4.0*pi/3.0*rvir**3.0*rho_vir
return rvir, mvir, rho_vir
def getSelfSimilarValues (mvir, delta, crit=True, aexp=1.0, omega_m=0.27, omega_l=0.73, omega_b = 0.0469, hubble=0.7 ) :
'''
Return self-similar quantites (e.g. T500c) for temperature [keV] pressure [erg/cm^3], and entropy [keV cm^2] given halo mass mvir [Msun/h], its overdensity delta, with respect to critical (crit=True) or mean (crit=False) at expansion factor aexp (= 1.0 by default). Assume WMAP5 cosmological parameters (true for Bolshoi and L500 simulations).
'''
from numpy import sqrt
fb = omega_b/omega_m
Ez = sqrt(omega_m/aexp**3.0+omega_l)
mu = 0.59
mue = 1.14
mpivot = 1e15 # in Msun/h
delta = float(delta)
if crit :
Tfit_norm = 11.055*(mu/0.59)*(hubble/0.7)**(2./3.)
Tfit_alpha = 2./3.
Tfit_beta = 2./3.
Pfit_norm = 1.4458e-11*(fb/0.1737)*(hubble/0.7)**2
Pfit_alpha = 2./3.
Pfit_beta = 8./3.
Kfit_alpha = 2./3.
Kfit_beta = -2./3.
#Kfit_norm = 1963.6*(mu/0.59)*(mue/1.14)**(2./3.)*(fb/0.1737)**(-2./3.)*(hubble/0.7)**(-2./3.)
Kfit_norm = 1265.7*(mu/0.59)**(5./3.)*(fb/0.1737)**(-2./3.)*(hubble/0.7)**(-2./3.)
Tvir = (delta/500.0)**(1./3.)*Tfit_norm*(mvir/mpivot)**(Tfit_alpha)*Ez**(Tfit_beta)
Kvir = (delta/500.0)**(-1./3.)*Kfit_norm*(mvir/mpivot)**(Kfit_alpha)*Ez**(Kfit_beta)
Pvir = (delta/500.0)**(4./3.)*Pfit_norm*(mvir/mpivot)**(Pfit_alpha)*Ez**(Pfit_beta)
else :
Tfit_norm = 5.2647*(mu/0.59)*(hubble/0.7)**(2./3.)*(omega_m/0.27)**(1./3.)
Tfit_alpha = 2./3.
Tfit_beta = -1.0
Pfit_norm = 7.4359e-13*(fb/0.1737)*(hubble/0.7)**2*(omega_m/0.27)**(4./3.)
Pfit_alpha = 2./3.
Pfit_beta = 4.0
Kfit_alpha = 2./3.
Kfit_beta = 1.0
#Kfit_norm = 4123.3*(mu/0.59)*(mue/1.14)**(2./3.)*(fb/0.1737)**(-2./3.)*(hubble/0.7)**(-2./3.)*(omega_m/0.27)**(-1./3.)
Kfit_norm = 2799.75*(mu/0.59)**(5./3.)*(fb/0.1737)**(-2./3.)*(hubble/0.7)**(-2./3.)*(omega_m/0.27)**(-1./3.)
Tvir = (delta/200.0)**(1./3.)*Tfit_norm*(mvir/mpivot)**(Tfit_alpha)*(aexp)**(Tfit_beta)
Kvir = (delta/200.0)**(-1./3.)*Kfit_norm*(mvir/mpivot)**(Kfit_alpha)*(aexp)**(Kfit_beta)
Pvir = (delta/200.0)**(4./3.)*Pfit_norm*(mvir/mpivot)**(Pfit_alpha)/(aexp)**(Pfit_beta)
return (Tvir, Pvir, Kvir)
def getMnl(z) :
"""
Return characteristic collapse mass Mnl at a given redshift z.
"""
#from numpy import *
#from scipy import *
import numpy as np
import cosmolopy.perturbation as cp
#Cosmological Parameters for L500 and Bolshoi
cosmo = {'omega_M_0' : 0.27, 'omega_lambda_0' : 0.73, 'omega_b_0' : 0.0469388, 'omega_n_0' : 0.0, 'N_nu' : 0,'h' : 0.70, 'n' : 0.96, 'sigma_8' : 0.82, 'baryonic_effects': True}
delta_c = 1.686
# mass bins in Msun/h
mbins = np.array(10**(arange(1,16,0.01)))
nu = np.zeros (len(mbins))
# Build nu array
sigma = cp.sigma_r(cp.mass_to_radius(mbins/cosmo['h'], **cosmo), z, **cosmo)[0]
nu = delta_c/sigma
# Compute Mnl which equals M when nu = 1
closest = where(nu < 1.)[0][-1] #nu increases with M
# Interplolate to get Mnl
Mnl = np.log10(mbins[closest]) + np.log10(mbins[closest+1]/mbins[closest])/np.log10(nu[closest+1]/nu[closest])*np.fabs(np.log10(nu[closest]))
Mnl = 10**Mnl
return Mnl
def getNu(mvir,z) :
"""
Return peak height nu for a given halo mass Mvir and redshift z. Mvir is in Msun/h
"""
#from numpy import *
#from scipy import *
import cosmolopy.perturbation as cp
#Cosmological Parameters for L500 and Bolshoi
cosmo = {'omega_M_0' : 0.27, 'omega_lambda_0' : 0.73, 'omega_b_0' : 0.0469388, 'omega_n_0' : 0.0, 'N_nu' : 0,'h' : 0.70, 'n' : 0.96, 'sigma_8' : 0.820, 'baryonic_effects': True}
delta_c = 1.686
sigma = cp.sigma_r(cp.mass_to_radius(mvir/cosmo['h'], **cosmo), z, **cosmo)[0]
nu = delta_c/sigma
return nu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.