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
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 1,606
| 3.453125
| 3
|
[] |
no_license
|
# Answers
1. What is React JS and what problems does it try and solve?
React JS is a Javascript Library for building complex and dynamic intercaes. React uses a virtual DOM so it can compare against the real DOM and only update single parts instead of the entire page every time. This also means it allows a website to update the DOM multiple times with limited performance hit.
1. What does it mean to _think_ in react?
To take an interface and be able to break it down into its individual components. Each component should ideally do one thing and be reusable.
1. Briefly describe some of the differences between a Class/Stateful component and a Functional/Presentational component.
Class components are components that extend React.component and are used to control state in the component. They contain the data for the application as well as the logic.
Functional componenets are used to accept props and return a React element. They do not contain state or control the data life cycle. They actaully render the UI ti the page.
1. Describe state.
State is assigned in a class constructor function and is used as a data store in the component. It keeps track of information about data in components. State can be changed by using setState.
1. Describe props.
Props, which is short for property, is an attribute-like property that is assigned to data in a component and can be passed around from parent to child elemetns. It is read-only, can't be mutated and used to control data flow in a React app.
Props are received in componenets and usd to display data in the UI.
|
C++
|
UTF-8
| 8,425
| 3.640625
| 4
|
[] |
no_license
|
#include "graph.h"
using namespace std;
//Zach Li
//Table class supports building, traversing graph structures. There are
//three ways of traversing and diplay the structure of the graph: display
//adjacency list and connection of each vertices, DFS and BFS.The menu class handles the
//client program with simple display, functionality test, and continue function.
//All the functionalities can be accessed in the process() function.
//first prompt
void menu::intro()
{
cout<<"==============Welcome!=============\n";
cout<<"Welcome to the contact tracing manager!\n";
cout<<"Start by entering the names you want to add. \n";
}
//adding vertices to the graph
void menu::establish(table & new_table)
{
char option;
char addName[SHORT];
do
{
cout<<"Please enter the name you want to add: \n";
cin.get(addName, SHORT, '\n');
cin.ignore(100,'\n');
if(new_table.insert_vertex(addName))
cout<<"Contact added successfully!\n";
cout<<"continue?\n";
cin>>option;
cin.ignore(100,'\n');
}
while(option!='n');
}
//display available options of the ADT
void menu::display()
{
cout<<"===============MENU===============\n";
cout<<"Please choose from the followin actions:\n";
cout<<"1. Adding contacts among the existing list;\n";
cout<<"2. Display each person and their contacts;\n";
cout<<"3. Display every person using Depth First Search;\n";
cout<<"4. Display every person with Breadth First Search;\n";
}
//record input choice from the user
void menu::choose()
{
choice = 999;
cin >> choice;
cin.ignore(100,'\n');
}
//process available actions according to the order in the display menu
void menu::process(table & new_tree)
{
switch(choice)
{
case 1:
insert_edges(new_tree);
break;
case 2:
new_tree.display_list();
break;
case 3:
new_tree.display_all(1);//need revision function
break;
case 4:
new_tree.display_all(2);
break;
default:
cout<<"Invalid!\n";
break;
}
}
//exit program only when the input is n
bool menu::cont()
{
char option;
cout<<"============================\n";
cout<<"Do you want to continue(y/n) ?\n";
cin>>option;
cin.ignore(100,'\n');
if(option == 'n')
return false;
else return true;
}
//prompt to take input for table
void menu::insert_edges(table & new_tree)
{
char anotherName[SHORT];
char contactName[SHORT];
char choice;
do{
cout<<"Please specify the person you are looking for\n";
cin.get(anotherName,SHORT,'\n');
cin.ignore(100,'\n');
cout<<"Please specify the name of person they are in contact with:\n";
cin.get(contactName, SHORT, '\n');
cin.ignore(100,'\n');
int num = new_tree.insert_edge(contactName, anotherName);
if(num >0)
cout<<"Contact added successfully!\n";
else if(num==0)
cout<<"Contact already exist!\n";
else
cout<<"No matching entries!\n";
cout<<"continue?\n";
cin>>choice;
cin.ignore(100,'\n');
}while(choice!='n');
}
//constructor to initialize a table of designated size
table::table(int size)
{
adjacency_list = new vertex[size];
for(int i = 0; i < size; ++i)
{
adjacency_list[i].name = NULL;
adjacency_list[i].head = NULL;
}
list_size = size;
next_index = 0;
}
table::~table()
{
if(adjacency_list)
{
for(int i = 0; i < list_size; ++i)//for each vertex
{
if(adjacency_list[i].name)//check if the name of the vertex
{
delete [] adjacency_list[i].name;
if(adjacency_list[i].head)//delete the edge list
{
node * current = adjacency_list[i].head;
while(current)
{
node * temp = current->next;
delete current;
current = temp;
}
adjacency_list[i].head = NULL;
}
adjacency_list[i].name = NULL;//set the head to null
}
}
delete [] adjacency_list;
}
adjacency_list = NULL;
}
//add a new person name to the adjacency list
int table::insert_vertex(char * new_name)
{
if(next_index == list_size)
return 0;//no more room
adjacency_list[next_index].name = new char[strlen(new_name)+1];
strcpy(adjacency_list[next_index].name, new_name);
//cout<<"This is the copied name: "<<adjacency_list[next_index].name<<endl;
++next_index;
return 1;
}
//wrapper function to calculate the necessary index in the array
int table::insert_edge(char * current, char * dest)
{
int current_index = find_location(current);//index of current name
int dest_index = find_location(dest);//find the index in the array to attach to
if(dest_index < 0 || current_index < 0)//no match
return -1;
return insert_edge(current, current_index, adjacency_list[dest_index].head);
}
//add an edge to a vertex, return 0 if edge already exits
int table::insert_edge(char * current, int current_index,node * & head)
{
if(!head)
{
head = new node;
head->adjacent =& adjacency_list[current_index];
head->next = NULL;
return 1;
}
if(head->adjacent ==& adjacency_list[current_index])//edge already exit;
return 0;
return insert_edge(current, current_index, head->next);
}
//take a name and return the index in the array
int table::find_location(char* index) const
{
for(int i = 0; i < next_index; ++i)//search through existing array element
{
if(strcmp(index, adjacency_list[i].name)==0)
return i;
}
return -1;
}
//wrapper function to display adjacency list
int table::display_list() const
{
for(int i = 0; i < next_index; ++i)
{
cout<<"The contact list of "<<adjacency_list[i].name<<": \n";
node * current = adjacency_list[i].head;
display_list(current);
}
return 1;
}
//display the adjacent list and each edge list
void table::display_list(node * head) const
{
if(!head)
return;
cout<<head->adjacent->name<<" "<<endl;
display_list(head->next);
}
//wrapper function for traversal and display with dfs
int table::display_all(int option) const
{
int array[next_index];//initialize the visit array to 0
for(int i=0; i < next_index; ++i )
{
array[i] = 0;
}
int num =0;
if(option == 1)
{
cout<<"+++DFS+++"<<endl;
display_all(num, array);
}
else
{
cout<<"+++BFS+++"<<endl;
display_bfs(num, array);
}
return 1;
}
//DFS for connected graph, index is the starting point of the search, visited[]
//is an array to keep track of vertices visited
void table::display_all(int & index, int visited[] ) const
{
if(visited[index]==0)
{
cout<<adjacency_list[index].name<<endl;
visited[index]=1;
node * temp = adjacency_list[index].head;
while(temp)
{
index = find_location(temp->adjacent->name);
display_all(index, visited);
temp = temp->next;
}
}
}
//BFS for connected graph, index is the starting point of the search, visited[]
//is an array to keep track of vertices visited
void table::display_bfs(int & index, int visited[]) const
{
int indexEdge;
if(visited[index]==2)//2 means the vertices is visited
//1 means the vertices is displayed
//0 means it is neither
return;
if(visited[index]==0)//only for the first vertex
cout<<adjacency_list[index].name<<endl;//display the name of the vertices
node * temp = adjacency_list[index].head;
while(temp)//loop through the node adjacent to vertices
{
indexEdge = find_location(temp->adjacent->name);
if(visited[indexEdge]==0)//only display if it is not displayed before
{
cout<<temp->adjacent->name<<" "<<endl;//display the name of the node
visited[indexEdge]=1;
}
temp = temp->next;
}
temp = adjacency_list[index].head;//reset temp to the beginning of the list
visited[index]=2;
while(temp) //visit all the vertices in the previous loop
{
indexEdge = find_location(temp->adjacent->name);
display_bfs(indexEdge,visited);//can I still access indexArray when I unwind?
temp = temp->next;
}
}
|
Markdown
|
UTF-8
| 627
| 3.109375
| 3
|
[] |
no_license
|
# [ B L O C K S ]
`blocks-dot-js` `[].js`
*blocks/prototypes === default-constructor === implicit-base*
>> 
---
# Syntax
*Block* := `["classes", "name", {config}, Block[]];`
* **classes** - (comma- and/or) whitespace-seperated list of class names
* **name** - the name for the block, optional
>> 
Where it is assumed that `inherits` (when it's a string value) is a reference to, either;
* line 3 & 5: another Block (no namespace, default namespace)
* line 9: a preconfigured constructor (specific namespace)
>> 
|
Java
|
UTF-8
| 1,366
| 3.8125
| 4
|
[] |
no_license
|
package algorithm;
import java.util.*;
public class MapValueSort {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("three", 3);
map.put("nine", 9);
map.put("zero", 0);
map.put("five", 5);
map.put("two", 2);
map.put("six", 6);
MapValueSort m = new MapValueSort();
Map<String, Integer> res = m.mapValueSort(map);
for (String key : res.keySet()) {
System.out.println(key + " " + res.get(key));
}
}
public <T extends Comparable> Map<String, T> mapValueSort(Map<String, T> map) {
int size = map.size();
if (size == 0 || map == null) {
return map;
}
List<Map.Entry<String, T>> list = new ArrayList<>();
for (Map.Entry<String, T> entry : map.entrySet()) {
list.add(entry);
}
Collections.sort(list, new Comparator<Map.Entry<String, T>>() {
@Override
public int compare(Map.Entry<String, T> o1, Map.Entry<String, T> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
LinkedHashMap<String, T> m = new LinkedHashMap<>();
for (Map.Entry<String, T> entry : list) {
m.put(entry.getKey(), entry.getValue());
}
return m;
}
}
|
Java
|
UTF-8
| 1,077
| 2.765625
| 3
|
[] |
no_license
|
package com.example.pruebasjuego.Screen;
import android.content.Context;
public class ScreenDivider {
private int w,h,boxSizeX,boxSizeY;
private Box[] boxes;
public ScreenDivider(int initX, int finalX, int initY, int finalY, int div, Context context) {
this.w = finalX-initX;
this.h = finalY-initY;
this.boxSizeX = w/div;
this.boxSizeY = h/div;
boxes = new Box[((div)*(div))];
int index= 0;
for (int i = 0; i < div; i++) {
for (int j = 0; j < div; j++) {
boxes[index] = new Box(i,j,initX+(i*this.boxSizeX),initY+(j*this.boxSizeY),boxSizeX,boxSizeY,context,null,null,true);
index++;
}
}
}
public Box[] getBoxes() {
return boxes;
}
public void setBoxes(Box[] boxes) {
this.boxes = boxes;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
}
|
Python
|
UTF-8
| 5,327
| 2.765625
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import numpy as np
from nitime import descriptors as desc
from nitime import timeseries as ts
from nitime import algorithms as tsa
# To support older versions of numpy that don't have tril_indices:
from nitime.index_utils import tril_indices
from .base import BaseAnalyzer
class CorrelationAnalyzer(BaseAnalyzer):
"""Analyzer object for correlation analysis. Has the same API as the
CoherenceAnalyzer"""
def __init__(self, input=None):
"""
Parameters
----------
input : TimeSeries object
Containing the data to analyze.
Examples
--------
>>> np.set_printoptions(precision=4) # for doctesting
>>> t1 = ts.TimeSeries(data = np.sin(np.arange(0,
... 10*np.pi,10*np.pi/100)).reshape(2,50),
... sampling_rate=np.pi)
>>> c1 = CorrelationAnalyzer(t1)
>>> c1 = CorrelationAnalyzer(t1)
>>> c1.corrcoef
array([[ 1., -1.],
[-1., 1.]])
>>> c1.xcorr.sampling_rate # doctest: +ELLIPSIS
3.141592653... Hz
>>> c1.xcorr.t0 # doctest: +ELLIPSIS
-15.91549430915... s
"""
BaseAnalyzer.__init__(self, input)
@desc.setattr_on_read
def corrcoef(self):
"""The correlation coefficient between every pairwise combination of
time-series contained in the object"""
return np.corrcoef(self.input.data)
@desc.setattr_on_read
def xcorr(self):
"""The cross-correlation between every pairwise combination time-series
in the object. Uses np.correlation('full').
Returns
-------
TimeSeries : the time-dependent cross-correlation, with zero-lag
at time=0
"""
tseries_length = self.input.data.shape[0]
t_points = self.input.data.shape[-1]
xcorr = np.zeros((tseries_length,
tseries_length,
t_points * 2 - 1))
data = self.input.data
for i in range(tseries_length):
data_i = data[i]
for j in range(i, tseries_length):
xcorr[i, j] = np.correlate(data_i,
data[j],
mode='full')
idx = tril_indices(tseries_length, -1)
xcorr[idx[0], idx[1], ...] = xcorr[idx[1], idx[0], ...]
return ts.TimeSeries(xcorr,
sampling_interval=self.input.sampling_interval,
t0=-self.input.sampling_interval * t_points)
@desc.setattr_on_read
def xcorr_norm(self):
"""The cross-correlation between every pairwise combination time-series
in the object, where the zero lag correlation is normalized to be equal
to the correlation coefficient between the time-series
Returns
-------
TimeSeries : A TimeSeries object
the time-dependent cross-correlation, with zero-lag at time=0
"""
tseries_length = self.input.data.shape[0]
t_points = self.input.data.shape[-1]
xcorr = np.zeros((tseries_length,
tseries_length,
t_points * 2 - 1))
data = self.input.data
for i in range(tseries_length):
data_i = data[i]
for j in range(i, tseries_length):
xcorr[i, j] = np.correlate(data_i,
data[j],
mode='full')
xcorr[i, j] /= (xcorr[i, j, t_points])
xcorr[i, j] *= self.corrcoef[i, j]
idx = tril_indices(tseries_length, -1)
xcorr[idx[0], idx[1], ...] = xcorr[idx[1], idx[0], ...]
return ts.TimeSeries(xcorr,
sampling_interval=self.input.sampling_interval,
t0=-self.input.sampling_interval * t_points)
class SeedCorrelationAnalyzer(object):
"""
This analyzer takes two time-series. The first is designated as a
time-series of seeds. The other is designated as a time-series of targets.
The analyzer performs a correlation analysis between each of the channels
in the seed time-series and *all* of the channels in the target
time-series.
"""
def __init__(self, seed_time_series=None, target_time_series=None):
"""
Parameters
----------
seed_time_series : a TimeSeries object
target_time_series : a TimeSeries object
"""
self.seed = seed_time_series
self.target = target_time_series
@desc.setattr_on_read
def corrcoef(self):
#If there is more than one channel in the seed time-series:
if len(self.seed.shape) > 1:
# Preallocate results
Cxy = np.empty((self.seed.data.shape[0],
self.target.data.shape[0]), dtype=float)
for seed_idx, this_seed in enumerate(self.seed.data):
Cxy[seed_idx] = tsa.seed_corrcoef(this_seed, self.target.data)
#In the case where there is only one channel in the seed time-series:
else:
Cxy = tsa.seed_corrcoef(self.seed.data, self.target.data)
return Cxy.squeeze()
|
Java
|
UTF-8
| 418
| 2.046875
| 2
|
[] |
no_license
|
package kodlamaio.hrms.business.abstracts;
import java.util.List;
import kodlamaio.hrms.core.utilities.results.DataResult;
import kodlamaio.hrms.core.utilities.results.Result;
import kodlamaio.hrms.entities.concretes.CvTalent;
public interface CvTalentService {
DataResult<List<CvTalent>> getAll();
DataResult<CvTalent> getById(int cvTalentId);
Result add(CvTalent cvTalent);
Result delete(int cvTalentId);
}
|
Java
|
UTF-8
| 87
| 2.203125
| 2
|
[] |
no_license
|
@Override protected final String defaultAsString(){
return asString(defaultValue);
}
|
Python
|
UTF-8
| 128
| 3.1875
| 3
|
[] |
no_license
|
#!/usr/bin/env Python3
counter = 1
fac = 1
while counter < 1001 :
fac = fac * counter
counter += 1
print(fac)
print('Done!')
|
Markdown
|
UTF-8
| 1,659
| 2.5625
| 3
|
[] |
no_license
|
# CleanApp
**This is a work in progress experimental project and is not intended as production-ready code**. It's currently in a development process and many more features will be implemented soon.
## Purpose
The main purpose of this project is to provide an easy house cleaning service to its users. The app has two modes: **service-receiver** and **service-provider** ones.
## Description
After registration, the service-receiver can choose what type of cleaning service does he/she want to receive:
_After party_, _Simple cleaning_, _After renovation_, _Deep cleaning_ or _Garden cleaning_. Then choose their preferable day and time, indicate the number of rooms to clean and prodive their location. Then he/she will find the masters, filtered by the previous inputs. After confirmation and reservation of the master, master will receive the notification that his/her service is needed. The client and the master can have in-app chat to exchange more details that is based on _Firebase realtime database_.
On the other hand, any user can activate their master's profile, where they can indicate which category of cleaning do they want to provide, indidcate their fee and cancellation policy.
## Used libraries and technologies
- Dagger hilt
- Coroutines
- Navigation
- Livedata
- Retrofit
- Google play services
- Firebase realtime database
- Firebase authorization
- Firebase cloud messaging
- Glide
- Lottie
#### Architecture
- The app is based on _MVVM_ architecture
## What will be improved in this project
- For now the features of the master's profile is not implemented and will be added soon.
- The UI will deffinitely be improved
|
Markdown
|
UTF-8
| 16,121
| 2.53125
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: 规划 Azure 用户主体名称(UPN)更改并对其进行故障排除
description: 了解 UPN 更改的已知问题和缓解措施
services: active-directory
ms.service: active-directory
ms.subservice: hybrid
ms.topic: how-to
ms.date: 03/13/2020
ms.author: baselden
author: barbaraselden
manager: daveba
ms.reviewer: jsimmons
ms.collection: M365-identity-device-management
ms.openlocfilehash: 885d30305ba2b186052e17b9b455b2248bca541b
ms.sourcegitcommit: 877491bd46921c11dd478bd25fc718ceee2dcc08
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 07/02/2020
ms.locfileid: "85608511"
---
# <a name="plan-and-troubleshoot-user-principal-name-changes-in-azure-active-directory"></a>在 Azure Active Directory 中规划用户主体名称更改并进行故障排除
用户主体名称(UPN)是一个属性,该属性是用户帐户的 internet 通信标准。 UPN 由 UPN 前缀(用户帐户名)和 UPN 后缀(DNS 域名)组成。 前缀使用 "@" 符号联接后缀。 例如 someone@example.com。 UPN 必须在目录林中的所有安全主体对象之间保持唯一。
**本文假设你使用 UPN 作为用户标识符。它用于规划 UPN 更改,并从可能由 UPN 更改引起的问题进行恢复。**
> [!NOTE]
> 对于开发人员,我们建议使用用户 objectID 作为不可变标识符,而不是 UPN 或电子邮件地址,因为它们的值可能会更改。
## <a name="learn-about-upns-and-upn-changes"></a>了解 Upn 和 UPN 更改
当所需的值实际上是其 UPN 时,登录页通常会提示用户输入其电子邮件地址。 因此,应确保在用户的主电子邮件地址发生更改时更改用户的 UPN。
用户的主要电子邮件地址可能因多种原因而发生变化:
* 公司品牌重塑
* 移动到不同公司部门的员工
* 合并和收购
* 员工姓名更改
### <a name="types-of-upn-changes"></a>UPN 更改的类型
可以通过更改前缀和/或后缀来更改 UPN。
* **更改前缀**。
* 例如,如果某人的名称发生了更改,你可以更改其帐户名:
BSimon@contoso.com到BJohnson@contoso.com
* 你还可以更改前缀的企业标准:
Bsimon@contoso.com到Britta.Simon@contoso.com
* **更改后缀**。 <br>
例如,如果某个人更改了部门,则可以更改其域:
* Britta.Simon@contoso.com 至 Britta.Simon@contosolabs.com <br>
或<br>
* Britta.Simon@corp.contoso.com 至 Britta.Simon@labs.contoso.com
建议在每次更新用户的主要电子邮件地址时更改用户的 UPN。
在从 Active Directory 到 Azure AD 的初始同步过程中,请确保用户的电子邮件与其 Upn 完全相同。
### <a name="upns-in-active-directory"></a>Active Directory 中的 Upn
在 Active Directory 中,默认的 UPN 后缀是在其中创建用户帐户的域的 DNS 名称。 在大多数情况下,这是在 internet 上注册为企业域的域名。 如果在 contoso.com 域中创建用户帐户,则默认 UPN 是
username@contoso.com
不过,你可以通过使用 Active Directory 域和信任关系来[添加更多 UPN 后缀](https://docs.microsoft.com/azure/active-directory/fundamentals/add-custom-domain)。
例如,你可能想要添加 labs.contoso.com,并让用户的 Upn 和电子邮件反映这一情况。 然后,它们将成为
username@labs.contoso.com.
>[!IMPORTANT]
> 如果在[Active Directory 中更改后缀](https://docs.microsoft.com/azure/active-directory/fundamentals/add-custom-domain),则必须确保已[在 Azure AD 中添加并验证](https://docs.microsoft.com/azure/active-directory/fundamentals/add-custom-domain)了匹配的自定义域名。

### <a name="upns-in-azure-active-directory"></a>Azure Active Directory 中的 Upn
用户以其 userPrincipalName 属性中的值登录到 Azure AD。
将 Azure AD 与本地 Active Directory 结合使用时,将使用 Azure AD Connect 服务来同步用户帐户。 默认情况下,Azure AD Connect 向导使用本地 Active Directory 中的 userPrincipalName 属性作为 Azure AD 中的 UPN。 可以将其更改为自定义安装中的其他属性。
更新单个用户的用户主体名称(UPN)或整个组织时,必须具有定义的进程。
请参阅本文档中的已知问题和解决方法。
将用户帐户从 Active Directory 同步到 Azure AD 时,请确保 Active Directory 中的 Upn 映射到 Azure AD 中的已验证域。

如果 userPrincipalName 属性的值不对应于 Azure AD 中的已验证域,则同步过程会将后缀替换为 onmicrosoft.com 值。
### <a name="roll-out-bulk-upn-changes"></a>推出批量 UPN 更改
按照有关批量 UPN 更改的[试验的最佳实践进行](https://docs.microsoft.com/azure/active-directory/fundamentals/active-directory-deployment-plans)操作。 如果发现无法快速解决的问题,还可以使用已测试的回退计划来恢复 Upn。 试点计算机运行后,可以开始针对包含各种组织角色的小型用户和特定的应用或设备集。
通过此第一个用户子集,你可以很好地了解用户在更改过程中应期待的内容。 将此信息包含在用户通信中。
创建一个已定义的过程,用于在正常操作过程中更改各个用户的 Upn。 建议有一个已测试的过程,其中包含有关已知问题和解决方法的文档。
以下各节详细介绍了在更改 Upn 时可能存在的已知问题和解决方法。
## <a name="apps-known-issues-and-workarounds"></a>应用已知问题和解决方法
[软件即服务(SaaS)](https://azure.microsoft.com/overview/what-is-saas/)和业务线(LoB)应用程序通常依赖于 upn 查找用户并存储用户配置文件信息,包括角色。 当用户首次登录到应用时,使用实时[预配](https://docs.microsoft.com/azure/active-directory/app-provisioning/user-provisioning)创建用户配置文件的应用程序可能会受到 UPN 更改的影响。
**已知问题**<br>
更改用户的 UPN 可能会破坏 Azure AD 用户与在应用程序上创建的用户配置文件之间的关系。 如果应用程序使用实时[预配](https://docs.microsoft.com/azure/active-directory/app-provisioning/user-provisioning),则它可能会创建全新的用户配置文件。 这将要求应用程序管理员进行手动更改来修复此关系。
**解决方法**<br>
[Azure AD 自动用户预配](https://docs.microsoft.com/azure/active-directory/manage-apps/user-provisioning),你可以在受支持的云应用程序中自动创建、维护和删除用户标识。 在应用程序上配置自动用户预配会自动更新应用程序上的 Upn。 在渐进式推出过程中测试应用程序,以验证它们是否不受 UPN 更改的影响。
如果你是开发人员,请考虑[将 SCIM 支持添加到你的应用程序](https://docs.microsoft.com/azure/active-directory/app-provisioning/use-scim-to-provision-users-and-groups),以启用 Azure Active Directory 的自动用户预配。
## <a name="managed-devices-known-issues-and-workarounds"></a>托管设备的已知问题和解决方法
通过[使你的设备 Azure AD](https://docs.microsoft.com/azure/active-directory/devices/overview),你可以通过单一登录(SSO)跨云和本地资源最大化用户的工作效率。
### <a name="azure-ad-joined-devices"></a>Azure AD 加入设备
[Azure AD 联接](https://docs.microsoft.com/azure/active-directory/devices/concept-azure-ad-join)的设备直接连接到 Azure AD,并允许用户使用其组织的标识登录到设备。
**已知问题** <br>
用户可能会遇到依赖于身份验证 Azure AD 的应用程序的单一登录问题。
**解决方法** <br>
此部分中提到的问题已在 Windows 10 2020 更新(2004)上得到解决。
**解决方法** <br>
留出足够的时间让 UPN 更改同步到 Azure AD。 验证新 UPN 是否反映在 Azure AD 门户上之后,要求用户选择 "其他用户" 磁贴,以通过其新 UPN 进行登录。 还可以通过[PowerShell](https://docs.microsoft.com/powershell/module/azuread/get-azureaduser?view=azureadps-2.0)进行验证。 使用新的 UPN 登录后,对旧 UPN 的引用可能仍会显示在 "访问工作或学校" Windows 设置上。

### <a name="hybrid-azure-ad-joined-devices"></a>混合 Azure AD 加入设备
[混合 Azure AD 联接](https://docs.microsoft.com/azure/active-directory/devices/concept-azure-ad-join-hybrid)的设备加入到 Active Directory 和 Azure AD。 如果你的环境具有本地 Active Directory 空间,你可以实施混合 Azure AD 联接,并且还想要从 Azure AD 提供的功能中获益。
**已知问题**
Windows 10 混合 Azure AD 联接的设备可能会遇到意外的重新启动和访问问题。
如果用户在新 UPN 已同步到 Azure AD 之前登录到 Windows,或者继续使用现有的 Windows 会话,则当条件性访问已配置为强制使用混合加入设备访问资源时,用户可能会遇到使用 Azure AD 进行身份验证的应用程序的单一登录问题。
此外,将显示以下消息,并强制一分钟后重启。
"你的电脑将在一分钟内自动重新启动。 Windows 遇到问题,需要重新启动。 应该立即关闭此消息,并保存工作。
**解决方法** <br>
此部分中提到的问题已在 Windows 10 2020 更新(2004)上得到解决。
**解决方法**
设备必须脱离 Azure AD 并重新启动。 重新启动后,设备将再次自动 Azure AD 加入,用户必须通过选择 "其他用户" 磁贴,使用新的 UPN 登录。 若要从 Azure AD 中脱离设备,请在命令提示符下运行以下命令:
**dsregcmd.exe/leave**
如果使用 Windows Hello 企业版,用户将需要[重新注册](https://docs.microsoft.com/windows/security/identity-protection/hello-for-business/hello-hybrid-cert-whfb-provision)。 在 UPN 更改后,Windows 7 和8.1 设备不受此问题的影响。
## <a name="microsoft-authenticator-known-issues-and-workarounds"></a>Microsoft Authenticator 已知问题和解决方法
你的组织可能需要使用[Microsoft Authenticator 应用](https://docs.microsoft.com/azure/active-directory/user-help/user-help-auth-app-overview)来登录和访问组织的应用程序和数据。 尽管用户可能会在应用程序中出现用户名,但在用户完成注册过程之前,帐户未设置为作为验证方法。
[Microsoft Authenticator 应用](https://docs.microsoft.com/azure/active-directory/user-help/user-help-auth-app-overview)具有四个主要功能:
* 通过推送通知或验证码进行多重身份验证
* 作为 iOS 和 Android 设备上的身份验证代理,以便为使用[中转身份验证](https://docs.microsoft.com/azure/active-directory/develop/brokered-auth)的应用程序提供单一登录
* 设备注册(也称为 Workplace Join)用于 Azure AD,这是 Intune 应用保护和设备注册/管理等其他功能的一种要求。
* 需要进行 MFA 和设备注册的手机登录。
### <a name="multi-factor-authentication-with-android-devices"></a>Android 设备的多重身份验证
Microsoft Authenticator 应用提供了带外验证选项。 在登录时,[多重身份验证(MFA)](https://docs.microsoft.com/azure/active-directory/authentication/concept-mfa-howitworks)会将通知推送到用户的智能手机或平板电脑上的 Microsoft Authenticator 应用,而不是在登录时将自动电话呼叫或短信。 用户只需在应用中点击 "批准" (或输入 PIN 或生物识别,然后点击 "身份验证")即可完成登录。
**已知问题**
更改用户的 UPN 时,旧的 UPN 仍将显示在用户帐户上,并且可能无法接收通知。 [验证代码](https://docs.microsoft.com/azure/active-directory/user-help/user-help-auth-app-faq)将继续工作。
**解决方法**
如果收到通知,请指示用户关闭通知,打开验证器应用,点击 "检查通知" 选项,并批准 MFA 提示。 此后,将更新在该帐户上显示的 UPN。 请注意,更新的 UPN 可能显示为新帐户,这是因为正在使用其他验证器功能。 有关详细信息,请参阅本文中的其他已知问题。
### <a name="brokered-authentication"></a>中转身份验证
在 Android 和 iOS 代理上,如 Microsoft Authenticator 启用:
* 单一登录(SSO)-用户无需登录到每个应用程序。
* 设备标识-当设备加入工作区时,代理会访问在设备上创建的设备证书。
* 应用程序标识验证-当应用程序调用代理时,它会传递其重定向 URL,并且 broker 将对其进行验证。
此外,它还允许应用程序参与更高级的功能,如[条件性访问](https://docs.microsoft.com/azure/active-directory/conditional-access/),并支持[Microsoft Intune 方案](https://docs.microsoft.com/azure/active-directory/develop/msal-net-use-brokers-with-xamarin-apps)。
**已知问题**<br>
由于应用程序传递的 login_hint 与代理上存储的 UPN 不匹配,用户在使用 broker 辅助登录的新应用程序上提供了更多的交互式身份验证提示。
**解决方法** <br> 用户需要从 Microsoft Authenticator 中手动删除帐户,然后从代理辅助应用程序开始新的登录。 初始身份验证后,将自动添加该帐户。
### <a name="device-registration"></a>设备注册
Microsoft Authenticator 应用负责向 Azure AD 注册设备。 设备注册允许设备进行 Azure AD 身份验证,并且在以下情况下是必需的:
* Intune 应用保护
* Intune 设备注册
* 电话登录
**已知问题**<br>
更改 UPN 后,具有新 UPN 的新帐户将显示在 Microsoft Authenticator 应用上,并且仍会列出具有旧 UPN 的帐户。 此外,旧 UPN 将显示在 "设备注册" 部分的 "应用设置" 中。 设备注册的正常功能或依赖方案不会有任何变化。
**解决方法** <br> 若要删除对 Microsoft Authenticator 应用上的旧 UPN 的所有引用,请指示用户手动从 Microsoft Authenticator 中删除旧帐户和新帐户,重新注册 MFA 并重新加入设备。
### <a name="phone-sign-in"></a>电话登录
使用手机登录,用户无需密码即可登录 Azure AD。 若要启用手机登录,用户需要注册使用验证器应用的 MFA,然后在验证器上直接启用手机登录。 在配置过程中,设备将注册到 Azure AD。
**已知问题** <br>
用户无法使用手机登录,因为他们没有收到任何通知。 如果用户点击 "检查通知",则会出现错误。
**解决方法**<br>
用户需要选择启用了电话登录的帐户的下拉菜单,然后选择 "禁用电话登录"。 如果需要,可以重新启用电话登录。
## <a name="security-key-fido2-known-issues-and-workarounds"></a>安全密钥(FIDO2)已知问题和解决方法
**已知问题** <br>
如果在同一密钥上注册多个用户,则 "登录" 屏幕会显示一个帐户选择页,其中显示了旧的 UPN。 使用安全密钥的登录不受 UPN 更改的影响。
**解决方法**<br>
若要删除对旧 Upn 的引用,用户必须[重置安全密钥并重新注册](https://docs.microsoft.com/azure/active-directory/authentication/howto-authentication-passwordless-security-key#known-issues)。
## <a name="onedrive-known-issues-and-workarounds"></a>OneDrive 已知问题和解决方法
OneDrive 用户已知在 UPN 更改后遇到问题。 有关详细信息,请参阅[UPN 更改如何影响 ONEDRIVE URL 和 onedrive 功能](https://docs.microsoft.com/onedrive/upn-changes)。
## <a name="next-steps"></a>后续步骤
请参阅以下资源:
* [Azure AD Connect:设计概念](https://docs.microsoft.com/azure/active-directory/hybrid/plan-connect-design-concepts)
* [Azure AD UserPrincipalName 填充](https://docs.microsoft.com/azure/active-directory/hybrid/plan-connect-userprincipalname)
* [Microsoft 标识平台 ID 令牌](https://docs.microsoft.com/azure/active-directory/develop/id-tokens)
|
Java
|
UTF-8
| 1,484
| 1.953125
| 2
|
[] |
no_license
|
///******************************************************************************
// * Copyright (C) 2016 Wuhan Medical union Co.Ltd All Rights Reserved.
// * 本软件为武汉水象科技有限公司开发研制。 未经本公司正式书面同意,其他任何个人、
// * 团体不得使用、复制、修改或发布本软件.
// *****************************************************************************/
//package com.waterelephant.sxyDrainage.entity.kaNiu;
//
///**
// * Module:
// * KaNiuCheckUserReq.java
// * @author huangjin
// * @since JDK 1.8
// * @version 1.0
// * @description: <描述>
// */
//public class KaNiuCheckUserReq {
// private String cardNiuId;
// private String channel;
// private String Name;
// private String mobile;
// private String idCardNo;
//
// public String getCardNiuId() {
// return cardNiuId;
// }
//
// public void setCardNiuId(String cardNiuId) {
// this.cardNiuId = cardNiuId;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public String getName() {
// return Name;
// }
//
// public void setName(String name) {
// Name = name;
// }
//
// public String getMobile() {
// return mobile;
// }
//
// public void setMobile(String mobile) {
// this.mobile = mobile;
// }
//
// public String getIdCardNo() {
// return idCardNo;
// }
//
// public void setIdCardNo(String idCardNo) {
// this.idCardNo = idCardNo;
// }
//
//}
|
Java
|
UTF-8
| 180
| 1.828125
| 2
|
[] |
no_license
|
package com.axpresslogistics.it2.axpresslogisticapp.presenter;
public interface MainPresenter<T> {
void init();
void subscribe(T t);
void unSubscribe();
}
|
SQL
|
UTF-8
| 359
| 3.234375
| 3
|
[] |
no_license
|
create keyspace if not exists datastax_shared_session_demo with replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
use datastax_shared_session_demo;
CREATE TABLE if not exists timeline (
userid uuid,
time timeuuid,
follower_id uuid,
message text,
PRIMARY KEY (userid, time)
) WITH CLUSTERING ORDER BY(time DESC);
truncate timeline;
|
Java
|
UTF-8
| 531
| 2.109375
| 2
|
[] |
no_license
|
package ce.pucmm.edu.vaadin.Data;
import ce.pucmm.edu.vaadin.Model.CalendarEvent;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.Date;
import java.util.List;
public interface EventRepository extends JpaRepository<CalendarEvent, Long> {
List<CalendarEvent> findAllByDate(Date date);
@Query("select event from CalendarEvent event where event.date between ?1 and ?2")
List<CalendarEvent> findByDatesBetween(Date start, Date end);
}
|
PHP
|
UTF-8
| 1,578
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\AdminRole;
use Illuminate\Notifications\Notifiable;
class AdminUser extends Authenticatable
{
use Notifiable;
protected $rememberTokenName = '';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* 用户拥有的角色
*/
public function roles()
{
return $this->belongsToMany(AdminRole::class, 'admin_role_user', 'user_id', 'role_id')
->withPivot(['user_id', 'role_id']);
}
/**
* 检测是否拥有某个角色
* @param $roles
* @return bool
*/
public function isOwnRoles($roles)
{
return !!$roles->intersect($this->roles)->count();
}
/**
* 检测是否拥有权限
* @param $permission
* @return bool
*/
public function hasPermission($permission)
{
return $this->isOwnRoles($permission->roles);
}
/**
* 针对用户分配角色
* @param $role
* @return bool
*/
public function grantRole($role)
{
return $this->roles()->save($role);
}
/**
* 删除用户角色关联
* @param $role
* @return mixed
*/
public function deleteRole($role)
{
return $this->roles()->detach($role);
}
}
|
Python
|
UTF-8
| 194
| 2.984375
| 3
|
[] |
no_license
|
N = int(input())
data = [0]*(N+1)
data[1]=1
def fibo(N,data):
for i in range(2,N+1):
data[i]=data[i-1]+data[i-2]
return(data[N])
fibo(N,data)
print(4*data[N]+2*data[N-1])
|
Java
|
UTF-8
| 2,838
| 2.328125
| 2
|
[] |
no_license
|
package com.bit.struts.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.bit.struts.model.entity.Struts06Vo;
public class Struts06Dao {
private Connection conn;
private String driver="oracle.jdbc.OracleDriver";
private String url="jdbc:oracle:thin:@localhost:1521:xe";
private String user="scott";
private String password="tiger";
private PreparedStatement pstmt;
private ResultSet rs;
public Struts06Dao() {
try {
if(conn==null || conn.isClosed()){
Class.forName(driver);
conn=DriverManager.getConnection(url, user, password);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public List<Struts06Vo> getList() {
List<Struts06Vo> list=new ArrayList<Struts06Vo>();
String sql="SELECT NUM,NAME,SUB,NALJA FROM STRUTS06 ORDER BY NUM DESC";
try {
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next())list.add(new Struts06Vo(
rs.getInt(1),rs.getString(2),rs.getString(3),rs.getDate(4)
));
} catch (SQLException e) {
e.printStackTrace();
} finally{
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public void insertOne(Struts06Vo bean) {
String sql="INSERT INTO STRUTS06 VALUES (STRUTS06_SEQ.NEXTVAL,?,?,?,SYSDATE)";
try {
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, bean.getName());
pstmt.setString(2, bean.getSub());
pstmt.setString(3, bean.getContent());
int result=pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Struts06Vo listOne(int num) {
Struts06Vo bean=new Struts06Vo();
String sql="SELECT * FROM STRUTS06 WHERE NUM=?";
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, num);
rs=pstmt.executeQuery();
if(rs.next()){
bean.setNum(rs.getInt("num"));
bean.setName(rs.getString("name"));
bean.setNalja(rs.getDate("nalja"));
bean.setSub(rs.getString("sub"));
bean.setContent(rs.getString("content"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return bean;
}
}
|
JavaScript
|
UTF-8
| 553
| 2.78125
| 3
|
[] |
no_license
|
import React, {Component} from 'react';
import './App.css';
class App extends Component {
state = {
name: "Shuva"
}
changeName = () => {
this.setState({
name: "Shuv"
})
}
removeName = () => {
this.setState({
name: ""
})
}
render() {
return (
<div className="App">
<br/>
<br/>
<button onClick={this.changeName}>Change name</button>
<br/>
<br/>
<button onClick={this.removeName}>Remove name</button>
<br/>
<br/>
<div>{this.state.name}</div>
</div>
);
}
}
export default App;
|
Markdown
|
UTF-8
| 3,816
| 2.53125
| 3
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
# TensorFlowObjectDetector (TFOD) for FTC
[](
https://www.youtube.com/watch?v=PJrMLcY_Es4&list=PL7jOvcu8grvvO54G4f0QdUCyg8loid5Wd&index=1 "Seek Example Videos")
## What is this?
This repository contains an Android library which enables FTC teams to use
machine learning in their OpModes. Specifically, this library makes it possible
to use neural networks to do object detection on camera frames. This library
requires very little setup, and once running will update recognitions in the
background without user interaction, enabling the user to focus on other tasks.
Furthermore, this repository contains scripts to enable teams to collect and
annotate their own datasets, should they wish to learn more or experiment with
different models.
## Why did you do this?
Perhaps a better question is what we're hoping to accomplish by releasing this
library. In no particular order, here are some of our goals.
1. **Democratize machine learning.** We believe machine learning is becoming a
fundamental technology that everyone (e.g. all FTC teams) should be able to
benefit from and have access to, and this is a step in that direction.
1. **Enable higher levels of autonomy.** It's no secret that the reason for
machine learning's success has been its unparalleled performance and accuracy
across a wide range of real world tasks. By bringing some of this technology
to FTC, we hope to push the limits of what autonomous robots can do.
1. **Educate people about ML.** We want students to learn about the whole
process of using and developing machine learning models, to help them better
understand the true extents of what is possible.
## How do I get started?
Depending on when you are reading this, this library may or may not already be
prepackaged with the robot controller app. If that is the case, then you can
jump directly to the usage guidelines. If not, or if you're trying to use this
library outisde of the FTC codebase (which is supported, acceptable, and
encouraged!), you'll first want to follow the steps in the Installation section.
You can then continue to the usage section, as above.
## How does it work?
Definitions:
* frame: A single image, from e.g. a camera or a video
* model: A pretrained machine learned model which operates on frames
* recognition: Output from the model, annotating all objects in a frame
* tracker: An object tracker to smoothly interpolate recognitions
The library's operation can be thought of as being broken into a few distinct
steps:
1. Initialize a source for frames
1. Load the labels and models into memmory
1. Start background processing and other objects
Then, the following runs indefinitely:
1. Get a new frame
1. If possible, pass the frame to the model
1. Feed the frame through the tracker
1. If the model is done processing, feed its results into the tracker
1. Make the most recent model results (recognitions) available to the client
A more detailed understanding of each of the steps involved can be found in the
documentation and comments for each of the parts of the system.
## Acknowledgements
We would like to thank Aakanksha Chowdhery, Vivek Rathod, and Ronny Votel for
their help and support with TensorFlow Lite and the TensorFlow Object Detection
API. We would also like to thank Vasu Agrawal for his tireless work in developing
this library, David Konerding and Liz Looney for their mentorship throughout the
development cycle, as well as the folks on the FTC SDK team (especially Tom Eng,
Bob Atkinson, and Craig MacFarlane) for their help with FTC-speciic integration.
Finally, we would like to thank everyone involved in coordinating and participating
in our data collection event, including Patricia Cruz, Aaron Cunningham, Calvin Johnson,
Nathan Mulcahey, and FTC teams 8381, 11039, 12454, 12635, 12869, and 13799.
|
C#
|
UTF-8
| 1,942
| 2.71875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ApiConsumer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
static HttpClient client;
public MainWindow()
{
InitializeComponent();
client = new HttpClient();
client.BaseAddress = new Uri("https://oeapika.azurewebsites.net");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue
("application/json"));
GetAll();
}
async Task AddToDo(Todo t)
{
HttpResponseMessage response =
await client.PostAsJsonAsync("/api/values", t);
response.EnsureSuccessStatusCode();
GetAll();
}
async Task<List<Todo>> GetAll()
{
List<Todo> todos = new List<Todo>();
HttpResponseMessage response = await
client.GetAsync("/api/values");
if (response.IsSuccessStatusCode)
{
//
todos = await response.Content.ReadAsAsync<List<Todo>>();
}
dgrid.ItemsSource = todos;
return todos;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Todo t = new Todo()
{
Name = tb_name.Text
};
AddToDo(t);
}
}
}
|
JavaScript
|
UTF-8
| 2,584
| 3.703125
| 4
|
[] |
no_license
|
// 完成的功能是合并多个对象到第一个对象中去
// 第一个参数如果是一个布尔值,那么可以用来区分是浅拷贝还是深拷贝
// extend(true, obj1, obj2, obj3)
import { isArray, isPlainObject } from "../../utils";
// 深度扩展的核心有两点
// 1、如果待拷贝属性值是一个对象,那么就不能直接赋值,要深度合并
// 2、如果待拷贝属性值是对象,那么已有值需要和其类型一致(要么都是数组、要么都是对象)
// 如果不一致,就要对clone进行重新赋值使其类型一致
export default function extend() {
// 默认不进行深层拷贝
let deep = false;
let name, src, copy;
const length = arguments.length;
// 用来维护参数的下标
let index = 1;
// 如果第一个参数==null,那么可以重置为一个空对象
let target = arguments[0] || {};
if (typeof target === "boolean") {
deep = target;
target = arguments[index] || {};
index++;
}
// 如果target不是一个对象的话那么我们是无法进行合并的
// 所以要将其重置为一个空对象
if (typeof target !== "object") {
target = {};
}
// 以上都是参数的准备工作,将deep、target、index重置为函数所需要的值
for (; index < length; index++) {
// 取出待合并的对象
const toExtendObj = arguments[index];
if (toExtendObj !== null) {
// 遍历待合并对象的属性
for (name in toExtendObj) {
src = target[name];
copy = toExtendObj[name];
// 如果copy是一个对象,且开启了深度扩展
// 那么src也要进行深度扩展
if (
deep &&
copy &&
(typeof copy === "object" || typeof copy === "function")
) {
// 这里要区分一下copy和src的类型
// 如果copy和src都是对象,那么就直接合并
// 如果copy是对象,src是数组,那么他们的类型就不一样
// 如果类型不一样的话,那么src就要重新赋值为copy类型一致的空对象或者空数组
const isCopyArray = isArray(copy);
let clone;
if (isCopyArray) {
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
target[name] = extend(deep, clone, copy);
} else if (copy != null) {
// 如果copy是一个简单类型,那么直接赋值即可
target[name] = copy;
}
}
}
}
return target;
}
|
Python
|
UTF-8
| 1,238
| 3.09375
| 3
|
[] |
no_license
|
import math
import numpy as np
from configs import *
from wall import Wall
def createGoodWall(finishPos):
wall = Wall(finishPos[0]-5, finishPos[1]-5, finishPos[2], finishPos[3])
wall.image.fill(pg.Color('red'))
good_wall_list.add(wall)
def randomAngle():
angle = np.random.uniform(0, 2.0*math.pi)
#angle = (np.random.uniform(0, 1)*360)
#angle = np.random.randint(-180,181)
#return round(angle,2)
return angle
def getVector(angle, speed):
vector = [speed * math.cos(angle), speed * math.sin(angle)]
vector = [round(x,2) for x in vector]
return vector
def project(pos, angle, distance):
x = pos[0] + (math.cos(angle) * distance)
y = pos[1] - (math.sin(angle) * distance)
if x < 0:
x = 0
elif x > screen_height:
x = pos[0]
if y < 0:
y = 0
elif y > screen_width:
y = pos[1]
return(x,y)
def DNA():
DNA = []
for i in range(DNA_length):
DNA.append(randomAngle())
return DNA
def DNA2():
DNA = []
for i in range(int(DNA_length/10)):
DNA.append([randomAngle()]*10)
DNA = np.array(DNA).ravel()
return DNA
def getDistance(listPop, finishPos):
listFitness = []
for i in listPop:
fit = math.sqrt((finishPos[0] - i.pos[0])**2 + (finishPos[1] - i.pos[1])**2)
listFitness.append(fit)
return listFitness
|
PHP
|
WINDOWS-1251
| 207
| 2.859375
| 3
|
[] |
no_license
|
<?php
$s=600;
$t=10;
echo " = $s/$t = " . $s/$t .' /;<br>';
echo " = $s/$t*1000/(10*60) = " . ($s/$t*1000/(10*60)) .' /;';
?>
|
Python
|
UTF-8
| 4,463
| 3.359375
| 3
|
[] |
no_license
|
#huffman.py
"""contains the huffmannode class and all of the functions dedicated to implementing the huffman codes, decoding and encoding
"""
class HuffmanNode:
def __init__(self, char, freq):
self.char = char # actually the character code
self.freq = freq
self.left = None
self.right = None
def set_left (self, node):
self.left = node
def set_right (self, node):
self.right = node
def comes_before (a, b) :
"""returns true if tree rooted at node a comes before tree rooted at node b """
if(a.freq < b.freq):
return True
elif(a.freq == b.freq):
if(a.char < b.char):
return True
return False
def combine (a, b) :
""" creates a new huffman node with children a and b with combined freq and lower value char """
newfreq = a.freq+b.freq
if(a.char < b.char):
newchar = a.char
else:
newchar = b.char
newnode = HuffmanNode(newchar, newfreq)
newnode.set_left(a)
newnode.set_right(b)
return newnode
def create_list(size):
return [0]*size
def create_string_list(size):
return ['']*size
def cnt_freq(filename):
try:
text = open(filename, 'r')
except:
raise IndexError("file not found")
characters = text.readline()
countlist = create_list(256)
for i in range(len(characters)):
countlist[ord(characters[i])] +=1
#print(characters[i], " : ", ord(characters[i]))
text.close()
return countlist
def insert_sorted(alist, node):
if(len(alist) == 0):
alist.append(node)
else:
flag = False
for i in range(len(alist)):
if(comes_before(node, alist[i]) and not flag):
alist.insert(i, node)
flag = True
if(flag == False):
alist.append(node)
def create_huff_tree(freqs):
treelist = []
for i in range(len(freqs)):
if(freqs[i] > 0):
newnode = HuffmanNode(ord(chr(i)), freqs[i])
insert_sorted(treelist, newnode)
while len(treelist) > 1:
combined = combine(treelist[0], treelist[1])
treelist = treelist[2:]
insert_sorted(treelist, combined)
return treelist[0]
def create_map(node, codelist, prefix):
#print(prefix)
if(node.left != None):
#prefix += '0'
create_map(node.left, codelist, ''.join((prefix, '0')))
if(node.right != None):
#prefix += '1'
create_map(node.right, codelist, ''.join((prefix, '1')))
if(node.left == None and node.right == None):
codelist[node.char] = prefix
def create_code(root_node):
codelist = create_string_list(256)
current = root_node
create_map(current, codelist, '')
return codelist
def tree_preord(root_node):
returnstring = ''
preord = []
tree_preord_helper(root_node, preord)
return ''.join(preord)
return returnstring
def tree_preord_helper(root, preord):
if(root.left == None and root.right == None):
preord.append('1')
preord.append(chr(root.char))
else:
preord.append('0')
tree_preord_helper(root.left, preord)
tree_preord_helper(root.right, preord)
def huffman_encode(in_file, out_file):
try:
inputfile = open(in_file, 'r')
except:
raise IndexError("file not found")
preord = inputfile.readline()
inputfile.close()
freqlist = cnt_freq(in_file)
hufftree = create_huff_tree(freqlist)
codes = create_code(hufftree)
outputlist = []
for i in range(len(preord)):
outputlist.append(codes[ord(preord[i])])
outputfile = open(out_file, 'w')
outputfile.write(''.join(outputlist))
outputfile.close()
def huffman_decode(freqs, encoded_file, decode_file):
try:
encoded = open(encoded_file, 'r')
except:
raise IndexError("file not found")
encodedlist = encoded.readline()
encoded.close()
hufftree = create_huff_tree(freqs)
decodedlist = []
current = hufftree
for i in range(len(encodedlist)):
if(encodedlist[i] == '0'):
current = current.left
elif(encodedlist[i] == '1'):
current = current.right
if(current.left == None and current.right == None):
decodedlist.append(chr(current.char))
current = hufftree
output = open(decode_file, 'w')
output.write(''.join(decodedlist))
output.close()
|
Swift
|
UTF-8
| 2,965
| 2.78125
| 3
|
[] |
no_license
|
//
// FlightDocsAPIService.swift
// FlightDocsInventory
//
// Created by PRADIP on 2021-06-15.
//
import Foundation
typealias Request = (Result<Array<Any>, NetwrokError>) -> Void
class FlightDocsAPIService {
static let shared = FlightDocsAPIService()
private let urlSession = URLSession.shared
private let baseURL = URL(string: "http://localhost:9001")!
func getAppParts(completion: @escaping Request) {
let partsURL = baseURL.appendingPathComponent("/parts")
urlSession.dataTask(with: partsURL) { (data, response, error) in
guard let data = data else {
completion(.failure(.badError))
return
}
do {
let jsonObject = try JSONDecoder().decode([Parts].self,from: data)
completion(.success(jsonObject))
} catch {
completion(.failure(.badError))
}
}.resume()
}
func addNewPart(parts: Dictionary<String, Any>, completion: @escaping Request) {
let partsURL = baseURL.appendingPathComponent("/parts")
var request = URLRequest(url: partsURL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let newPart = NewParts(cost: (parts["cost"] as! NSString).floatValue, name: parts["name"] as! String, partNumber: parts["partNumber"] as! String, description: parts["partDescription"] as! String, inStock: 55, image: nil, isActive: (parts["isActive"] != nil), notes: parts["notes"] as! String)
do {
let jsonData = try JSONEncoder().encode(newPart)
request.httpBody = jsonData
} catch {
print("encode failure")
}
urlSession.dataTask(with: partsURL) { (data, response, error) in
guard let data = data else {
completion(.failure(.badError))
return
}
do {
let jsonObject = try JSONDecoder().decode([NewPart].self,from: data)
completion(.success([jsonObject]))
} catch {
completion(.failure(.badError))
}
}.resume()
}
func editExistingPart() {
// http://localhost:9001/parts
// PATH PARAMETERS - id
// {
// "cost": 0,
// "partNumber": "string",
// "description": "string",
// "name": "string",
// "notes": "string",
// "inStock": 0,
// "image": { },
// "isActive": true
// }
}
func consumeExistingPart() {
// http://localhost:9001/parts/{id}/consume
// {
// "quantity": 0
// }
}
func receiveNewPart() {
// http://localhost:9001/parts/{id}/receive
// {
// "quantity": 0
// }
}
}
|
Go
|
UTF-8
| 4,087
| 2.890625
| 3
|
[] |
no_license
|
package main
import (
"fmt"
"net/http"
"strconv"
"github.com/labstack/echo/v4"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var (
DB *gorm.DB
)
func init() {
InitDB()
InitialMigration()
}
type Config struct {
DB_Username string
DB_Password string
DB_Port string
DB_Host string
DB_Name string
}
func InitDB() {
config := Config{
DB_Username: "root",
DB_Password: "root",
DB_Port: "3306",
DB_Host: "localhost",
DB_Name: "crud_go",
}
connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
config.DB_Username,
config.DB_Password,
config.DB_Host,
config.DB_Port,
config.DB_Name,
)
var err error
DB, err = gorm.Open(mysql.Open(connectionString), &gorm.Config{})
if err != nil {
panic(err)
}
}
type User struct {
gorm.Model
Name string `json:"name" form:"name"`
Email string `json:"email" form:"email"`
Password string `json:"password" form:"password"`
}
func InitialMigration() {
DB.AutoMigrate(&User{})
}
// get all users
func GetUsersController(c echo.Context) error {
var users []User
if err := DB.Find(&users).Error; err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, map[string]interface{}{
"message": "success get all users",
"users": users,
})
}
// get user by id
func GetUserController(c echo.Context) error {
user := User{}
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
fmt.Println(err)
return c.String(http.StatusBadRequest, "Invalid ID")
}
if err := DB.First(&user, id).Error; err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "internal server error")
}
return c.JSON(http.StatusOK, map[string]interface{}{
"message": "success get user by id",
"user": user,
})
}
// create new user
func CreateUserController(c echo.Context) error {
user := User{}
if err := c.Bind(&user); err != nil {
return c.String(http.StatusInternalServerError, "Internal Server Error")
}
if err := DB.Save(&user).Error; err != nil {
return c.String(http.StatusInternalServerError, "Internal Server Error")
}
return c.JSON(http.StatusOK, map[string]interface{}{
"message": "success create new user",
"user": user,
})
}
//delete user by id
func DeleteUserController(c echo.Context) error {
// user, err := strconv.Atoi(c.Param())
user := User{}
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
fmt.Println(err)
return c.String(http.StatusBadRequest, "Invalid ID")
}
if err := DB.First(&user, id).Error; err != nil {
return c.String(http.StatusInternalServerError, "Internal Server Error")
}
if err := DB.Delete(&user).Error; err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "Internal Server Error")
}
return c.JSON(http.StatusOK, map[string]interface{}{
"message": "success delete by user id",
"user": user,
})
}
// // update user by id
func UpdateUserController(c echo.Context) error {
user := User{}
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
fmt.Println(err)
return c.String(http.StatusBadRequest, "Invalid ID")
}
if err := DB.First(&user, id).Error; err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "Internal Server Error")
}
if err := c.Bind(&user); err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "Internal Server Error")
}
if err := DB.Save(&user).Error; err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError, "Internal Server Error")
}
return c.JSON(http.StatusOK, map[string]interface{}{
"message": "success update user by id",
"user": user,
})
}
func main() {
// create a new echo instance
e := echo.New()
// Route / to handler function
e.GET("/users", GetUsersController)
e.GET("/users/:id", GetUserController)
e.POST("/users", CreateUserController)
e.DELETE("/users/:id", DeleteUserController)
e.PUT("users/:id", UpdateUserController)
// strart the server, and log if it fails
e.Logger.Fatal(e.Start(":8000"))
}
|
Python
|
UTF-8
| 13,506
| 2.515625
| 3
|
[] |
no_license
|
from Team import Team
import warnings, random
from VocabList import VocabList
import random, os, socket, sys, pickle
import pygame
import tkinter
import tkinter.filedialog
import matplotlib.pyplot as plt
import pandas as pd
root = tkinter.Tk()
root.withdraw()
pygame.init()
## get size of an
def sizeof(obj):
size = sys.getsizeof(obj)
if isinstance(obj, dict): return size + sum(map(sizeof, obj.keys())) + sum(map(sizeof, obj.values()))
if isinstance(obj, (list, tuple, set, frozenset)): return size + sum(map(sizeof, obj))
return size
class Game:
KEYS = ('PROPERTY', 'BOOL_GUESS', 'WORD')
PROPERTIES = ('BLUE', 'RED', 'BLANK', 'MINE')
TEAMS = ('BLUE', 'RED')
PROPERTY_COLOR_DICT = {'BLUE': "#9FE9EE",
'RED': "#EE9F9F",
'BLANK': 'W',
'MINE': '#DADADA'}
VOCAB_DIR = './VocabList/'
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARK_GREEN = (0, 128, 0)
DARK_RED = (128, 0, 0)
DARK_BLUE = (0, 0, 128)
BEIGE = (255, 243, 202)
LIGHT_GREY = (220, 220, 220)
BLOCK_X_SIZE = 250
BLOCK_Y_SIZE = 120
SPACE_SIZE = 10
SCREEN_X_SIZE = 1500
SCREEN_Y_SIZE = 1000
KEYS_ORDER = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y']
KEYS_DICT = {'A': pygame.K_a,
'B': pygame.K_b,
'C': pygame.K_c,
'D': pygame.K_d,
'E': pygame.K_e,
'F': pygame.K_f,
'G': pygame.K_g,
'H': pygame.K_h,
'I': pygame.K_i,
'J': pygame.K_j,
'K': pygame.K_k,
'L': pygame.K_l,
'M': pygame.K_m,
'N': pygame.K_n,
'O': pygame.K_o,
'P': pygame.K_p,
'Q': pygame.K_q,
'R': pygame.K_r,
'S': pygame.K_s,
'T': pygame.K_t,
'U': pygame.K_u,
'V': pygame.K_v,
'W': pygame.K_w,
'X': pygame.K_x,
'Y': pygame.K_y}
KEY_LABEL_FONT = pygame.font.Font('freesansbold.ttf', 18)
SCORE_FONT = pygame.font.Font('freesansbold.ttf', 32)
WORD_FONT = pygame.font.Font('../fonts/NotoSerifSC-Bold.otf', 28)
HINT_FONT = pygame.font.Font('../fonts/MaShanZheng-Regular.ttf', 30)
HELP_FONT = pygame.font.Font('freesansbold.ttf', 18)
def __init__(self, spymaster=False):
self.team_red = Team('RED')
self.team_blue = Team('BLUE')
self.set_empty_board()
self._vocab = VocabList()
self.vocab_list = []
## pygame display
self.size = [Game.SCREEN_X_SIZE, Game.SCREEN_Y_SIZE]
self.screen = pygame.display.set_mode(self.size)
self.set_rect()
self.screen.fill(Game.WHITE)
pygame.display.set_caption("Codename")
self.host_socket = None
self.client_socket = None
self.spymaster = spymaster
self.team_dict = {'RED': self.team_red, 'BLUE': self.team_blue}
self.round_counter = 0
def set_socket(self, host_socket, client_socket):
self.host_socket = host_socket
self.client_socket = client_socket
def add_vocab_doc_to_vocab_list(self, doc):
success_flag = self._vocab.add_vocab_doc(doc)
self.vocab_list = list(self._vocab.vocab_list)
random.shuffle(self.vocab_list)
return success_flag
def set_empty_board(self):
self.board = []
self.simple_board = []
for i in range(5):
self.board.append([])
self.simple_board.append([])
for j in range(5):
board_ij = {k:None for k in Game.KEYS}
self.board[i].append(board_ij)
self.simple_board[i].append(board_ij.copy())
def reset_vocab_list(self):
self.vocab_list = list(self._vocab.vocab_list)
random.shuffle(self.vocab_list)
def reset_board(self):
if len(self.vocab_list) < 25:
self.load_vocab(msg='Not enough words loaded.')
#self.reset_vocab_list()
teams = list(Game.TEAMS)
random.shuffle(teams)
team_words = random.sample(list(range(25)), 18)
self.team_dict[teams[0]].set_current_word_count(9)
self.team_dict[teams[1]].set_current_word_count(8)
# clear board
for i in range(5):
for j in range(5):
self.board[i][j]['PROPERTY'] = 'BLANK'
for i in range(18):
if i < 9:
self.board[team_words[i]//5][team_words[i]%5]['PROPERTY'] = teams[0]
elif i < 17:
self.board[team_words[i]//5][team_words[i]%5]['PROPERTY'] = teams[1]
else:
self.board[team_words[i]//5][team_words[i]%5]['PROPERTY'] = 'MINE'
for i in range(5):
for j in range(5):
self.board[i][j]['BOOL_GUESS'] = False
self.board[i][j]['WORD'] = self.vocab_list.pop()
self.simple_board[i][j]['PROPERTY'] = self.board[i][j]['PROPERTY']
self.simple_board[i][j]['WORD'] = self.board[i][j]['WORD']
self.simple_board[i][j]['BOOL_GUESS'] = self.board[i][j]['BOOL_GUESS']
self.print_board_by_key('WORD')
print('')
self.print_board_by_key('PROPERTY')
def plot_current_board(self):
words_df = self.get_board_words_as_df()
color_list = self.get_board_colors()
fig, ax = plt.subplots()
# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')
ax.table(cellText=words_df.values, loc='center', cellColours=color_list)
fig.tight_layout()
plt.show()
return
def get_board_colors(self):
color_list = []
for i in range(5):
color_list.append([])
for j in range(5):
color_list[i].append(Game.PROPERTY_COLOR_DICT[self.board[i][j]['PROPERTY']])
return color_list
def get_board_words_as_df(self):
word_list = []
for i in range(5):
word_list.append([])
for j in range(5):
word_list[i].append(self.board[i][j]['WORD'])
return pd.DataFrame(word_list)
def set_simple_board(self, new_board):
self.simple_board = new_board
for i in range(5):
for j in range(5):
self.board[i][j]['PROPERTY'] = self.simple_board[i][j]['PROPERTY']
self.board[i][j]['WORD'] = self.simple_board[i][j]['WORD']
self.board[i][j]['BOOL_GUESS'] = self.simple_board[i][j]['BOOL_GUESS']
def set_rect(self):
boarder_x = (Game.SCREEN_X_SIZE - (Game.BLOCK_X_SIZE*5) - (Game.SPACE_SIZE*4))//2
boarder_y = (Game.SCREEN_Y_SIZE - (Game.BLOCK_Y_SIZE*5) - (Game.SPACE_SIZE*4))//2
for i in range(5):
for j in range(5):
rect = pygame.Rect(boarder_x+i*Game.BLOCK_X_SIZE+i*Game.SPACE_SIZE,
boarder_y+j*Game.BLOCK_Y_SIZE+j*Game.SPACE_SIZE,
Game.BLOCK_X_SIZE, Game.BLOCK_Y_SIZE)
label = Game.KEYS_ORDER[i*5+j]
self.board[i][j]['LABEL'] = label
label_text = Game.KEY_LABEL_FONT.render(label, True, Game.BLACK)
label_position = (boarder_x+i*Game.BLOCK_X_SIZE+i*Game.SPACE_SIZE,
boarder_y+j*Game.BLOCK_Y_SIZE+j*Game.SPACE_SIZE)
self.board[i][j]['RECT'] = rect
self.board[i][j]['LABEL_TEXT'] = label_text
self.board[i][j]['LABEL_POSITION'] = label_position
self.board[i][j]['RECT_KEY'] = Game.KEYS_DICT[label]
def draw_board(self):
self.screen.fill(Game.WHITE)
if not self.spymaster:
red_score_text = Game.SCORE_FONT.render('{}'.format(self.team_red.current_word_count), True,
Game.DARK_RED)
blue_score_text = Game.SCORE_FONT.render('{}'.format(self.team_blue.current_word_count), True,
Game.DARK_BLUE)
score_mid_text = Game.SCORE_FONT.render('-', True, Game.BLACK)
self.screen.blit(red_score_text, (20, 20))
self.screen.blit(score_mid_text, (20+red_score_text.get_width()+2, 20))
self.screen.blit(blue_score_text, (20+red_score_text.get_width()+4+score_mid_text.get_width(), 20))
for i in range(5):
for j in range(5):
color = Game.LIGHT_GREY
font_color = Game.BLACK
if self.board[i][j]['BOOL_GUESS']:
if self.board[i][j]['PROPERTY'] == 'BLANK':
color = Game.BEIGE
elif self.board[i][j]['PROPERTY'] == 'RED':
color = Game.DARK_RED
font_color = Game.WHITE
elif self.board[i][j]['PROPERTY'] == 'BLUE':
color = Game.DARK_BLUE
font_color = Game.WHITE
elif self.board[i][j]['PROPERTY'] == 'MINE':
color = Game.BLACK
font_color = Game.WHITE
elif self.spymaster:
if self.board[i][j]['PROPERTY'] == 'RED':
font_color = Game.DARK_RED
elif self.board[i][j]['PROPERTY'] == 'BLUE':
font_color = Game.DARK_BLUE
elif self.board[i][j]['PROPERTY'] == 'MINE':
color = (150, 150, 150)
pygame.draw.rect(self.screen, color, self.board[i][j]['RECT'])
self.screen.blit(self.board[i][j]['LABEL_TEXT'],
self.board[i][j]['LABEL_POSITION'])
word_text = Game.WORD_FONT.render(self.board[i][j]['WORD'], True, font_color)
word_position = (self.board[i][j]['LABEL_POSITION'][0]+(Game.BLOCK_X_SIZE-word_text.get_width())//2,
self.board[i][j]['LABEL_POSITION'][1]+(Game.BLOCK_Y_SIZE-word_text.get_height())//2)
self.screen.blit(word_text, word_position)
## Display
pygame.display.update()
return
def play(self):
self.reset_board()
#self.plot_current_board()
ingame_flag = True
status_flag = True
while ingame_flag:
self.draw_board()
for event in pygame.event.get():
if event.type == pygame.QUIT: # Usually wise to be able to close your program.
msg = pickle.dumps(False)
self.client_socket.send(msg)
raise SystemExit
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
ingame_flag = False
elif event.key in Game.KEYS_DICT.values():
found = False
for i in range(5):
for j in range(5):
if self.board[i][j]['RECT_KEY'] == event.key:
status_flag = True
self.board[i][j]['BOOL_GUESS'] = True
self.simple_board[i][j]['BOOL_GUESS'] = True
if self.board[i][j]['PROPERTY'] == 'MINE':
ingame_flag = False
if self.board[i][j]['PROPERTY'] == 'RED':
self.team_red.decrease_current_word_count()
if self.team_red.current_word_count == 0:
ingame_flag = False
if self.board[i][j]['PROPERTY'] == 'BLUE':
self.team_blue.decrease_current_word_count()
if self.team_blue.current_word_count == 0:
ingame_flag = False
if status_flag:
msg = pickle.dumps(self.simple_board)
self.client_socket.send(msg)
status_flag = False
self.round_counter += 1
end_flag = False
continue_flag = False
while not end_flag:
self.screen.fill(Game.WHITE)
text = Game.HINT_FONT.render('Next round?', True, Game.BLACK)
self.screen.blit(text, ((self.size[0]-text.get_width())//2, (self.size[1]-text.get_height())//2))
output_string = 'Press [N] for next round. Press [ESC] to end game.'
help_text = Game.HELP_FONT.render(output_string, True, Game.BLACK)
self.screen.blit(help_text, ((self.size[0]-help_text.get_width())//2,
(self.size[1]+text.get_height())//2+20))
## Display
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT: # Usually wise to be able to close your program.
msg = pickle.dumps(False)
self.client_socket.send(msg)
raise SystemExit
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
msg = pickle.dumps(False)
self.client_socket.send(msg)
end_flag = True
elif event.key == pygame.K_n:
continue_flag = True
end_flag = True
if continue_flag and self.round_counter <= 25:
self.play()
return
def load_vocab_list_dialog(self):
try:
root.filename = tkinter.filedialog.askopenfilename(initialdir = Game.VOCAB_DIR,
title = "Select vocabulary lists",
filetypes = [("Text file",'*.txt')])
return self.add_vocab_doc_to_vocab_list(root.filename)
except Exception:
return False
def load_vocab(self, msg=''):
end_flag = False
success_flag = False
help_font = pygame.font.Font('freesansbold.ttf', 18)
vocab_font = pygame.font.Font('../fonts/MaShanZheng-Regular.ttf', 48)
msg = msg+' ' if msg else msg
while not end_flag:
self.screen.fill(Game.WHITE)
text = Game.HINT_FONT.render('{}Let\'s Load!'.format(msg), True, Game.BLACK)
self.screen.blit(text, ((self.size[0]-text.get_width())//2, (self.size[1]-text.get_height())//2))
help_text = Game.HELP_FONT.render('Press [L] to load vocabulary list. Press [P] to play.', True, Game.BLACK)
self.screen.blit(help_text, ((self.size[0]-help_text.get_width())//2,
(self.size[1]+text.get_height())//2+20))
help_text2 = Game.HELP_FONT.render('Number of successfully loaded vocabulary lists: {}'.format(self._vocab.get_number_of_lists()), True, Game.DARK_RED)
self.screen.blit(help_text2, ((self.size[0]-help_text2.get_width())//2,
(self.size[1]+text.get_height())//2+40+help_text.get_height()))
## Display
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT: # Usually wise to be able to close your program.
raise SystemExit
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_l:
success_flag = self.load_vocab_list_dialog()
elif event.key == pygame.K_p and self._vocab.get_number_of_lists() > 0:
end_flag = True
def print_board_by_key(self, key):
for i in range(5):
print_str = ''
for j in range(5):
print_str += self.board[i][j][key] + '\t\t'
print(print_str)
if __name__ == '__main__':
game = Game()
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(1) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
game.set_socket(s, c)
#game.reset_board()
game.play()
|
Markdown
|
UTF-8
| 2,714
| 2.859375
| 3
|
[] |
no_license
|
# IMAGE-CLASSISICATION using CIFAR-10 DATSET
## Datasets:
The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000
training images and 10000 test images.
The dataset is divided into five training batches and one test batch, each with 10000 images.
The test batch contains exactly 1000 randomly-selected images from each class.
The training batches contain the remaining images in random order, but some training batches may contain more images from one class than another. Between them, the training batches contain exactly 5000 images from each class.
### Dataset Summary and Exploration
Number of training examples = 40000
Number of validation examples = 10000
Number of testing examples = 10000
Image data shape = (32, 32, 3)
Number of classes = 10
### Labels and Classes
0 : airplane
1 : automobile
2 : bird
3 : cat
4 : deer
5 : dog
6 : frog
7 : horse
8 : ship
9 : truck
## Dataset Visualization


## Design and Test a Model Architecture
I used two different kind of architecture :
1.LENET-5(used modified version)
2.VGG-16
VGG16 perfoms very well and produce high testing accuracy as compare to LENET-5.
## Confusion matrix
I also compute confusion matrix to measure the performance of an model(VGG16). The name confusion matrix reflects the fact that it makes it easy for us to see what kind of confusions occur in our classification algorithms. It's also known as an error matrix.A confusion matrix is a summary of prediction results on a classification problem.The number of correct and incorrect predictions are summarized with count values and broken down by each class. This is the key to the confusion matrix.The confusion matrix shows the ways in which your classification model is confused when it makes predictions.It gives us insight not only into the errors being made by a classifier but more importantly the types of errors that are being made.
## Test a Model on Unseen Images (Output Top 5 Softmax Probabilities For Each Image):


For more detail explanation , please look the [Notebook](final_Cifar_10_Classification.ipynb)
## Future Work
Improve Testing accuracy
Apply different Hyperparameters(leraning_rate, batch_size,epochs,...)
Use different Regularization technique
Apply different Architecture
Apply on differant application(field).
|
C++
|
UTF-8
| 548
| 3.4375
| 3
|
[] |
no_license
|
class Solution {
public:
int size(ListNode* head) {
int res = 0;
while(head) {
res++;
head = head->next;
}
return res;
}
TreeNode* build(ListNode *& head, int l, int r) {
if(l > r) {
return NULL;
}
int mid = (l + r) >> 1;
TreeNode* root = new TreeNode(0);
if(l <= mid) root->left = build(head, l, mid - 1);
root->val = head->val;
head = head->next;
if(mid <= r) root->right = build(head, mid + 1, r);
return root;
}
TreeNode* sortedListToBST(ListNode *head) {
return build(head, 0, size(head) - 1);
}
};
|
C#
|
UTF-8
| 550
| 2.859375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterfacePolymorphism_App
{
class Man : IMannerable,IEmotionable
{
public void depart()
{
Console.WriteLine("Man Depart");
}
public void wish()
{
Console.WriteLine("Man Wish");
}
public void cry()
{
Console.WriteLine("Man Cry");
}
public void laugh()
{
Console.WriteLine("Man Laugh");
}
}
}
|
Python
|
UTF-8
| 629
| 3.421875
| 3
|
[] |
no_license
|
def main():
f = open("input.txt", 'r')
line = f.readline().replace("0", " ")
rows = 6
columns = 25
n = rows * columns
layers = [line[i:i + n] for i in range(0, len(line), n)]
pict = list(map(lambda it: some(it, layers), range(0, n)))
one = ''.join(pict)
pictrows = [one[i:i + columns] for i in range(0, len(one), columns)]
for it in range(rows):
print(pictrows[it])
def some(it, layers):
startingLayer = 0
transparent = "2"
while layers[startingLayer][it] == transparent:
startingLayer = startingLayer + 1
return layers[startingLayer][it]
main()
|
Java
|
UTF-8
| 9,230
| 2.671875
| 3
|
[] |
no_license
|
package com.prs.main;
import com.prs.abstraction.enumic.ConstraintTypes;
import com.prs.abstraction.interfaces.IOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
public class ParserHelper {
public static void checkUnsupported(String[] args) throws Exception {
List<String> _suportedList = CParser.Utility.getOptions()
.stream()
.map(a -> a.get_expression())
.collect(Collectors.toList());
_suportedList.addAll(CParser.Utility.getFlags().stream()
.map(c -> c.get_expression())
.collect(Collectors.toList()));
for (String arg : args) {
if (arg.trim().startsWith("-")) {
if (!_suportedList.contains(arg.trim())) {
boolean isKvP;
isKvP = CParser.Utility.getKvPairs().stream()
.anyMatch(a -> arg.startsWith(a.get_expression()));
if (!isKvP) {
throw new Exception("Error:..." + arg + " argument does not supported yet");
}
}
}
}
}
public static void checkIfFirstElementIsOptionOrFlag(String firstElement) throws Exception {
if (!firstElement.startsWith("-")) {
throw new Exception("Error:..." + " values without an option is not accepted");
}
}
public static void checkEmptyParams(String[] args) throws Exception {
if (args.length == 0) {
throw new Exception("Error:.. There are no arguments to parse");
}
}
public static void checkValueFreeOptions(String[] args) throws Exception {
String arg;
boolean isProvidedOption;
boolean flag = false;
boolean isExistingOption;
for (int s = 0; s < args.length; s++) {
arg = args[s];
isProvidedOption = args[s].startsWith("-");
isExistingOption = CParser.Utility.getOptions().stream().map(a -> a.get_expression()).collect(Collectors.toList()).contains(arg);
if (isProvidedOption & isExistingOption) {
if (flag) {
throw new Exception("option without value is not accepted");
}
flag = true;
continue;
} else {
flag = false;
}
}
if (flag) {
throw new Exception("option without value is not accepted");
}
}
public static void parseOptions(String[] args) throws Exception {
boolean isOption = false;
String optionExpression = " ";
for (String arg : args) {
if (arg.trim().startsWith("-")) {
isOption = CParser.Utility.getOptions()
.stream()
.map(a -> a.get_expression())
.anyMatch(b -> b.contains(arg.trim()));
optionExpression = arg;
continue;
}
if (isOption) {
String finalOptionExpression = optionExpression;
if (CParser.Utility.getOptions().stream().filter(a -> a.get_expression().equals(finalOptionExpression)).findAny().get().get_valueSeparator().equals(" ")) {
CParser.Utility.getOptions().stream()
.filter(x -> x.get_expression().equals(finalOptionExpression))
.collect(Collectors.toList())
.forEach(a -> {
try {
a.addValue(arg.trim());
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
});
} else {
String[] values;
String valueSeparator = CParser.Utility.getOptions()
.stream()
.filter(a -> a.get_expression().equals(finalOptionExpression))
.findAny()
.get()
.get_valueSeparator();
if (arg.contains(valueSeparator)) {
values = arg.trim().split(valueSeparator.trim());
} else {
throw new Exception("Error:... Defined " + "'".concat(valueSeparator).concat("'") + " and provided value separator does not match");
}
CParser.Utility.getOptions().stream()
.filter(a -> a.get_expression().equals(finalOptionExpression))
.forEach(x -> {
try {
x.addValueRange(values);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
}
}
public static void parseKvP(String[] args) throws Exception {
boolean isKvP = false;
String kvpExpression = " ";
for (String arg : args) {
if (arg.trim().startsWith("-")) {
isKvP = CParser.Utility.getKvPairs().stream()
.anyMatch(a -> arg.startsWith(a.get_expression()));
if (isKvP) {
kvpExpression = arg.trim();
String finalKvPExpression = kvpExpression;
String valueSeparator = CParser.Utility.getKvPairs()
.stream()
.filter(a ->arg.startsWith(a.get_expression()))
.findAny()
.get()
.get_valueSeparator();
String[] values;
if (arg.contains(valueSeparator)) {
values = arg.trim().split(valueSeparator.trim());
} else {
throw new Exception("Error:... Defined " + "'".concat(valueSeparator).concat("'") + " and provided value separator does not match");
}
CParser.Utility.getKvPairs().stream()
.filter(a -> arg.startsWith(a.get_expression()))
.forEach(x -> {
try {
x.setValue(values[1]);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
}
}
/*
TODO
*/
public static void parseFlags(String[] args) {
boolean isFlag = false;
String flagExpression = " ";
for (String arg : args) {
if (arg.startsWith("-")) {
isFlag = CParser.Utility.getFlags()
.stream()
.map(a -> a.get_expression())
.anyMatch(b -> b.equals(arg.trim()));
flagExpression = arg.trim();
if (isFlag) {
String finalflagExpression = flagExpression;
CParser.Utility.getFlags().stream()
.filter(a->a.get_expression().equals(finalflagExpression))
.forEach(a -> {
try {
a.setValue(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
}
}
public static void checkMandatories(String[] args) throws Exception {
boolean anyMandatoryOption = CParser.Utility.getOptions().stream()
.anyMatch(a->a.getcType() == ConstraintTypes.Mandatory);
if(anyMandatoryOption){
List<String > mandatories = CParser.Utility.getOptions().stream()
.filter(a->a.getcType() == ConstraintTypes.Mandatory)
.map(b->b.get_expression())
.collect(Collectors.toList());
mandatories.addAll(CParser.Utility.getKvPairs().stream()
.filter(a->a.getcType() == ConstraintTypes.Mandatory)
.map(b->b.get_expression()).collect(Collectors.toList()));
List<String> allOptions = new ArrayList<>();
for(String s : args){
if(s.trim().startsWith("-")){
allOptions.add(s);
}
}
if(!allOptions.containsAll(mandatories)){
StringBuilder sb = new StringBuilder();
mandatories.forEach(a->sb.append(a).append(" "));
throw new Exception("Error:... Mandatory "+ sb.toString() + " options omited");
}
}
}
}
|
Python
|
UTF-8
| 545
| 2.96875
| 3
|
[] |
no_license
|
class Solution:
def majorityElement(self, nums: List[int]) -> int:
dic = {}
for i, element in enumerate(nums):
if element not in dic:
dic[element] = 1
else:
dic[element] += 1
# print(dic)
return max(dic, key=dic.get)
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums)//2]
<<<<<<< HEAD
=======
>>>>>>> 192284b0e5bae3db598e96e0a4267b85cab9ace8
|
Ruby
|
UTF-8
| 677
| 4.125
| 4
|
[] |
no_license
|
catch(:done) do
puts "This is done"
end
catch(:finished) do
puts "This is finished"
end
# catch(:taken) do
# print "Enter number: "
# num = gets.chomp.to_i
# throw(:taken) if num == 0
# puts "Your number is #{num}"
# end
# puts "You're finished!"
def do_things(num)
i = 0
while true
puts "I'm doing things"
i += 1
throw(:go_for_tea) if i == num
end
end
catch(:go_for_tea) do
puts "I'm drinking my tea"
do_things(3)
end
catch(:whole) do
print "Enter a number: "
num = gets.chomp.to_i
throw(:whole) if num == 0
puts 100 / num
catch(:go_for_tea) do
do_things(5)
end
puts "Things have all been done. Time for tea!"
end
|
C#
|
UTF-8
| 821
| 3.328125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ImtiazAdar
{
class SortByLength
{
//static void Main(string[] args)
//{
// int N = int.Parse(Console.ReadLine());
// while(N-- > 0)
// {
// List<string> li = new List<string>();
// string[] sen = Console.ReadLine().Split(' ');
// for (int i = 0; i < sen.Length; i++)
// li.Add(sen[i]);
// StringBuilder sb = new StringBuilder();
// foreach (var item in li.OrderByDescending(i => i.Length))
// sb.Append(item + " ");
// sb.Length--;
// Console.WriteLine(sb);
// }
//}
}
}
|
Go
|
UTF-8
| 454
| 2.53125
| 3
|
[] |
no_license
|
package main
import (
"flag"
"fmt"
"log"
gs "github.com/mllu/go-ssh"
)
func main() {
cmd := flag.String("cmd", "pwd", "command to execute on remote server")
sc := gs.NewConfig()
sc.ParseCommandLine()
sess, err := sc.NewSSHClientSession()
if err != nil {
log.Fatal(err)
}
defer sess.Close()
rsp, err := gs.Run(sess, *cmd)
if err != nil {
log.Printf("remote command %s failed with error %v\n", *cmd, err)
return
}
fmt.Print(rsp)
}
|
PHP
|
UTF-8
| 2,886
| 2.84375
| 3
|
[] |
no_license
|
<?php
session_start();
include("class/db.php");
if (isset ($_POST['index']) ) {
$arr_newdata = sort_data("ISBN", 0);
print_table($arr_newdata);
}
if (isset ($_POST['select_1']) || isset ($_POST['select_2']) ) {
$choose = $_POST['select_1'];
$sort = $_POST['select_2'];
$arr_newdata = sort_data($choose, $sort);
print_table($arr_newdata);
}
if (isset ($_GET['load']) ) {
$no = 0;
$load_time = date("Y-m-d");
header("Content-type: text/x-csv; charset=utf-8");
header("Content-Disposition: filename=".$load_time.".csv");
echo "\xEF\xBB\xBF";
while ( isset($_SESSION["value"][$no]) ) {
if ($no == 0) {
echo $_SESSION["value"][$no];
$no ++;
} else {
echo PHP_EOL;
echo $_SESSION["value"][$no];
$no ++;
}
}
session_unset();
}
function print_table($data)
{
echo "<table>
<tr>
<th>ISBN</th>
<th>出版社</th>
<th>書名</th>
<th>作者</th>
<th>定價</th>
<th>發行日</th>
<th>編輯/刪除</th>
</tr>";
foreach ($data as $key => $value) {
$data_array = explode(",", $value);
$_SESSION["value"][$key] = $data_array[0].",".$data_array[1].",".$data_array[2].","
.$data_array[3].",".$data_array[4].",".$data_array[5];
echo "<tr>";
echo "<td>" . $data_array[0] . "</td>";
echo "<td>" . $data_array[1] . "</td>";
echo "<td>" . $data_array[2] . "</td>";
echo "<td>" . $data_array[3] . "</td>";
echo "<td>" . $data_array[4] . "</td>";
echo "<td>" . $data_array[5] . "</td>";
echo "<td> <button> <a href='edit.php?id=".$data_array[6]."'> EDIT </a> </button>";
echo " ";
echo "<button> <a href='delete.php?id=".$data_array[6]."' onClick='return check_delete();'> DEL </a> </button> </td>";
echo "</tr>";
}
echo "</table>";
}
function sort_data($sorttype, $l)
{
$no = 0;
$arr_data = array();
$arr_newdata = array();
$db = new DataBase;
$query = $db->query("SELECT * FROM `book`");
foreach ($query->result() as $row) {
$arr_data[$no]["ISBN"] = $row->ISBN;
$arr_data[$no]["press"] = $row->press;
$arr_data[$no]["name"] = $row->bName;
$arr_data[$no]["author"] = $row->author;
$arr_data[$no]["prize"] = $row->prize;
$arr_data[$no]["day"] = $row->day;
$arr_data[$no]["id"] = $row->id;
$no++;
}
if ($l == 0) { //asc
usort($arr_data, function ($a, $b) use ($sorttype) {
return strnatcmp($a[$sorttype], $b[$sorttype]);
}
);
} else { //desc
usort($arr_data, function ($a, $b) use ($sorttype) {
return strnatcmp($b[$sorttype], $a[$sorttype]);
}
);
}
foreach ($arr_data as $key => $value) {
$line = implode(",", $value);
$arr_newdata[$key] = $line;
}
return $arr_newdata;
}
|
PHP
|
UTF-8
| 1,407
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use Notifiable;
use HasApiTokens, Notifiable;
use Sluggable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password','credit','path','unread','slug','role'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function organize(){
return $this->hasOne('App\Organize');
}
public function tournaments(){
return $this->hasMany('App\Tournament');
}
public function matches(){
return $this->hasMany('App\Match');
}
public function messages(){
return $this->hasMany('App\Message');
}
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
public function sluggable(): array
{
return [
'slug' => [
'source' => 'username'
]
];
}
}
|
C
|
UTF-8
| 321
| 3.015625
| 3
|
[] |
no_license
|
//
// main.c
// dev1
//
// Created by 今林 毅一郎 on 2016/09/25.
// Copyright © 2016年 今林 毅一郎. All rights reserved.
//
#include <stdio.h>
int main(void)
{
int i;
for (i=1;i<=10;i++)
{
printf("%2d:hello !\n",i);
}
printf("goodby World!\n");
return 0;
}
|
C++
|
UHC
| 1,371
| 2.953125
| 3
|
[] |
no_license
|
#include<iostream>
using namespace std;
int n, m, a[510][510], dy[510][510];
int mx[4] = { -1, 1, 0, 0 }, my[4] = { 0, 0, -1, 1 };
int DFS(int x, int y)
{
int i;
if (x == n && y == m)
return 1;
if (dy[x][y] >= 0)
return dy[x][y];
if (dy[x][y] == -1)
dy[x][y] = 0;
for (i = 0; i < 4; i++)
{
int nx = x + mx[i], ny = y + my[i];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && a[nx][ny] < a[x][y])
dy[x][y] += DFS(nx, ny);
}
return dy[x][y];
}
int main()
{
int i, j;
cin >> n >> m;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= m; j++)
{
dy[i][j] = -1;
cin >> a[i][j];
}
}
dy[n][m] = 1;
DFS(1, 1);
cout << dy[1][1];
return 0;
}
/*̹ Ʋ
#include<iostream>
using namespace std;
int a[510][510], dy[510][510], check[510][510];
int n, m;
int DFS(int x, int y)
{
int i;
int movex[5] = { 0, 0, 1, 0, -1 };
int movey[5] = { 0, 1, 0, -1, 0 };
if (x == n && y == m)
{
return 1;
}
if (dy[x][y] != 0)
{
return dy[x][y];
}
for (i = 1; i <= 4; i++)
{
int tox = x + movex[i];
int toy = y + movey[i];
if (a[tox][toy] < a[x][y] && tox > 0 && tox <= n && toy > 0 && toy <= m)
{
dy[x][y] += DFS(tox, toy);
}
}
return dy[x][y];
}
int main()
{
int i, j;
cin >> n >> m;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
cin >> a[i][j];
int result = DFS(1, 1);
cout << result;
return 0;
}
*/
|
TypeScript
|
UTF-8
| 186
| 2.84375
| 3
|
[] |
no_license
|
export interface IOrganism {
id?: number;
organismName?: string;
}
export class Organism implements IOrganism {
constructor(public id?: number, public organismName?: string) {}
}
|
JavaScript
|
UTF-8
| 1,461
| 2.84375
| 3
|
[] |
no_license
|
module.exports.distance = function(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
};
module.exports.getCriticalPath = function(tasks) {
var endTasks = getEndTasks(tasks);
// Trace forward to find worst path
var maxTime = 0;
var worstPath = [];
var recurse = function(task, alreadyChecked, currPath, totalTime) {
if(alreadyChecked.has(task)) throw new Error("Loop detected in schedule");
alreadyChecked.add(task);
currPath.push(task);
totalTime += task.time;
if(task.children.size === 0) {
if(totalTime > maxTime) {
maxTime = totalTime;
worstPath = currPath.slice(0);
}
} else {
task.children.forEach(function(child) {
recurse(child, alreadyChecked, currPath, totalTime);
});
}
alreadyChecked.delete(task);
currPath.pop();
};
endTasks.forEach(function(task) {
var alreadyChecked = new Set();
var currPath = [];
recurse(task, alreadyChecked, currPath, 0);
});
return worstPath.reverse();
};
function getEndTasks(startTasks) {
var endTasks = new Set();
startTasks.forEach(function(task) {
if(task.parents.size === 0) {
endTasks.add(task);
}
});
return endTasks;
}
module.exports.sign = function(x) {
return x > 0 ? 1 : ((x < 0) ? -1 : 0);
};
module.exports.lower = function(x, diff) {
var origSign = module.exports.sign(x);
if(x > 0) {
x -= diff;
} else if(x < 0) {
x += diff;
}
if(module.exports.sign(x) !== origSign) x = 0;
return x;
};
|
Markdown
|
UTF-8
| 51,752
| 3.421875
| 3
|
[
"MIT"
] |
permissive
|
## black-bible
一些常用的Javascript工具函数,可以简化我们日常的很多操作
## Install
```
npm i black-bible -S
```
## Usage
在Node环境下:
```javascript
const _ = require('black-bible');
function f (a, b,c) {
return a + b + c;
}
_.curry(f, 1)(2)(3); // 6
```
使用ES6模块:
```javascript
import _ from 'black-bible';
function f (a, b,c) {
return a + b + c;
}
_.curry(f, 1)(2)(3); // 6
```
使用script标签:
```html
<script src="black-bible/umd"></script>
<script>
function f (a, b,c) {
return a + b + c;
}
_.curry(f, 1)(2)(3); // 6
</script>
```
## Modules
<dl>
<dt><a href="#module_add">add</a> ⇒ <code>Number</code></dt>
<dd><p>求所有参数的和</p>
<p>对于参数列表中的任何类型,都会尝试相加,所以可能会有强制类型转换</p>
</dd>
<dt><a href="#module_after">after</a> ⇒ <code>function</code></dt>
<dd><p>函数在count次后执行</p>
<p>限制函数在触发多少次后执行</p>
</dd>
<dt><a href="#module_before">before</a> ⇒ <code>function</code></dt>
<dd><p>限制函数执行的次数</p>
<p>限制函数只能执行多少次,返回一个执行器函数,用来执行函数,次数到之后,再次执行函数
会失效,</p>
</dd>
<dt><a href="#module_camelCase">camelCase</a> ⇒ <code>String</code></dt>
<dd><p>驼峰化字符串</p>
<p>函数会舍弃字符串的所有特殊字符,无论是在开头还是中间还是结尾,而在非开头处的数字或特殊字符
后的字母会大写</p>
</dd>
<dt><a href="#module_checkedType">checkedType</a> ⇒ <code>String</code></dt>
<dd><p>判断类型的函数</p>
<p>该函数通过Object.prototype.toString方法来判断,所以
若是重写了该方法,函数可能会失效,函数会返回对应类型的大写形式,</p>
</dd>
<dt><a href="#module_compact">compact</a> ⇒ <code>Array</code></dt>
<dd><p>获取真值数组</p>
<p>返回一个新数组,包含原数组的所有真值,
假值为:undefined, NaN, 0, false, null</p>
</dd>
<dt><a href="#module_curry">curry</a> ⇒ <code>function</code></dt>
<dd><p>函数柯里化的辅助函数</p>
<p>接受一个函数fn和可选的用于函数fn的参数,返回柯里化后的函数fn,即使函数fn的参数已经满足
同样会返回一个函数而不是fn调用的结果</p>
</dd>
<dt><a href="#module_debounce">debounce</a> ⇒ <code>function</code></dt>
<dd><p>创建一个防抖函数</p>
<p>创建一个防抖函数,根据option选项对象来决定delay延时开始前或结束
后调用回调函数,其中option.before决定是否在延时开始之前触发回调,若是为false,那么
无论option.after为true还是false,都会在延时结束后触发回调,option.after决定是否
在延时结束之后触发回调,函数返回的防抖函数拥有一个cancel方法,用来取消延时调用</p>
</dd>
<dt><a href="#module_deepClone">deepClone</a> ⇒ <code>any</code></dt>
<dd><p>深拷贝函数</p>
<p>一个深拷贝函数,cloneProto参数决定是否拷贝一个对象的原型,不会忽略函数,对象的
Symbol属性,但是对于Symbol属性,仍然传递的是Symbol的引用</p>
</dd>
<dt><a href="#module_delay">delay</a> ⇒ <code>Object</code></dt>
<dd><p>延时函数</p>
<p>延时函数fn的执行wait毫秒,会返回一个定时器ID</p>
</dd>
<dt><a href="#module_divide">divide</a> ⇒ <code>Boolean</code></dt>
<dd><p>求商</p>
</dd>
<dt><a href="#module_divideBy">divideBy</a> ⇒ <code>Number</code></dt>
<dd><p>求商</p>
<p>接受一个函数作为第二参数,对集合内每个元素调用,用来决定求值的标准</p>
</dd>
<dt><a href="#module_every">every</a> ⇒ <code>Boolean</code></dt>
<dd><p>every迭代函数</p>
<p>适用于多种类型的every函数,对于对象的每个元素调用函数,若所有属性都使
函数返回True则返回True,否则返回false</p>
</dd>
<dt><a href="#module_filter">filter</a> ⇒ <code>Array</code></dt>
<dd><p>适用于各种类型的Filter迭代函数</p>
<p>适用于各种类型的Filter迭代函数,对于集合的每一项调用函数,返回函数返回True的
项组成的数组</p>
</dd>
<dt><a href="#module_find">find</a> ⇒ <code>any</code></dt>
<dd><p>find迭代函数</p>
<p>适用于多种类型的find方法,它返回第一个使断言函数返回true的项,
对于Object和Map类型,find返回的将不再是项,而是键值对中的键,
fromIndex为迭代的起点,对于数组来说,是其索引,对于对象Map等类型来说,
是获取他们的所有键的数组的索引</p>
</dd>
<dt><a href="#module_findRight">findRight</a> ⇒ <code>any</code></dt>
<dd><p>find函数的反向函数</p>
<p>从反方向开始迭代,返回第一个使函数返回True的项的值
对于对象或Map,返回的将是他们的键而不是值</p>
</dd>
<dt><a href="#module_forEach">forEach</a> ⇒ <code>Array</code> | <code>Map</code> | <code>Set</code> | <code>String</code> | <code>Number</code> | <code>Object</code></dt>
<dd><p>forEach迭代函数</p>
<p>适用于各种类型的forEach,对集合的每一项运行函数,最终返回集合本身,
可以显式的通过返回false来终止循环</p>
</dd>
<dt><a href="#module_forEachRight">forEachRight</a> ⇒ <code>Array</code> | <code>Object</code> | <code>Map</code> | <code>Set</code></dt>
<dd><p>forEachRight迭代函数</p>
<p>forEach函数的反向函数,从结尾开始迭代,可以通过返回false显式的
结束迭代,返回集合本身</p>
</dd>
<dt><a href="#module_isArray">isArray</a></dt>
<dd><p>是否是数组类型</p>
<p>使用Array的isArray方法来进行检查</p>
</dd>
<dt><a href="#module_isBigInt">isBigInt</a> ⇒ <code>Boolean</code></dt>
<dd><p>值是否是BigInt类型</p>
</dd>
<dt><a href="#module_isBoolean">isBoolean</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查是否是布尔值</p>
</dd>
<dt><a href="#module_isDate">isDate</a> ⇒ <code>Boolean</code></dt>
<dd><p>值是否是Date</p>
</dd>
<dt><a href="#module_isError">isError</a> ⇒ <code>Boolean</code></dt>
<dd><p>是否是Error类型</p>
</dd>
<dt><a href="#module_isFalseValue">isFalseValue</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查是否是假植</p>
<p>在这里,假值的概念为值等于 undefined ,null ,false ,0</p>
</dd>
<dt><a href="#module_isFinite">isFinite</a> ⇒ <code>Boolean</code></dt>
<dd><p>值是否是有限数字</p>
</dd>
<dt><a href="#module_isFunction">isFunction</a> ⇒ <code>Boolean</code></dt>
<dd><p>值是否是函数</p>
</dd>
<dt><a href="#module_isInContainer">isInContainer</a> ⇒ <code>Boolean</code></dt>
<dd><p>判断一个元素是否在对应容器的可视区域内</p>
</dd>
<dt><a href="#module_isMap">isMap</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查值是否为Map</p>
</dd>
<dt><a href="#module_isNaN">isNaN</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查是否是NaN</p>
<p>与Javascript自带的isNaN不同,该函数只会对NaN值返回true</p>
</dd>
<dt><a href="#module_isNodeEnv">isNodeEnv</a> ⇒ <code>Boolean</code></dt>
<dd><p>是否是Node环境</p>
</dd>
<dt><a href="#module_isNull">isNull</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查值是否等于Null</p>
</dd>
<dt><a href="#module_isNumber">isNumber</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查是否是数字</p>
</dd>
<dt><a href="#module_isObject">isObject</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查是否是对象类型</p>
<p>对于任何对象类型包括函数返回True,对于null返回false和undefined返回false</p>
</dd>
<dt><a href="#module_isObjectLike">isObjectLike</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查是否是类对象</p>
<p>跟isObject基本相同,只是会对函数返回false,也就是说对
一个非null非function对象返回True</p>
</dd>
<dt><a href="#module_isPlainObject">isPlainObject</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查值是否为普通对象</p>
<p>一个普通对象为直接通过Object构造函数或对象字面量创建的对象,
一个对象若是继承了其他对象也算是普通对象</p>
</dd>
<dt><a href="#module_isRegExp">isRegExp</a> ⇒ <code>Boolean</code></dt>
<dd><p>是否是RegExp</p>
</dd>
<dt><a href="#module_isSet">isSet</a> ⇒ <code>Boolean</code></dt>
<dd><p>是否是Set</p>
</dd>
<dt><a href="#module_isString">isString</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查是否是字符串</p>
</dd>
<dt><a href="#module_isSymbol">isSymbol</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查值是否是Symbol</p>
</dd>
<dt><a href="#module_isTrueValue">isTrueValue</a> ⇒ <code>Boolean</code></dt>
<dd><p>值是否是真值</p>
<p>在这里,真值的概念为不等于 undefined ,null ,0 ,false,</p>
</dd>
<dt><a href="#module_isUndefined">isUndefined</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查值是否是Undefined</p>
</dd>
<dt><a href="#module_isWeakMap">isWeakMap</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查值是否是WeakMap</p>
</dd>
<dt><a href="#module_isWeakSet">isWeakSet</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查值是否是WeakSet</p>
</dd>
<dt><a href="#module_isWindow">isWindow</a> ⇒ <code>Boolean</code></dt>
<dd><p>检查当前宿主环境是否为window</p>
</dd>
<dt><a href="#module_map">map</a> ⇒ <code>Array</code></dt>
<dd><p>map迭代函数</p>
<p>适用于各种类型的map迭代函数,对集合的每一项调用函数fn,返回函数
的返回值组成的数组</p>
</dd>
<dt><a href="#module_max">max</a> ⇒ <code>Number</code> | <code>String</code></dt>
<dd><p>集合的最大值</p>
</dd>
<dt><a href="#module_maxBy">maxBy</a> ⇒ <code>any</code></dt>
<dd><p>最大值</p>
<p>接受一个函数作为第二参数,用来决定求值的标准</p>
</dd>
<dt><a href="#module_min">min</a> ⇒ <code>Number</code> | <code>String</code></dt>
<dd><p>求最小值</p>
</dd>
<dt><a href="#module_minBy">minBy</a> ⇒ <code>any</code></dt>
<dd><p>最小值</p>
<p>接受一个函数作为第二参数,用来决定求值的标准</p>
</dd>
<dt><a href="#module_multiply">multiply</a> ⇒ <code>Number</code></dt>
<dd><p>求集合的乘积</p>
</dd>
<dt><a href="#module_multiplyBy">multiplyBy</a> ⇒ <code>Number</code></dt>
<dd><p>集合的乘积</p>
<p>接受一个函数作为第二参数,用来决定求值的标准</p>
</dd>
<dt><a href="#module_pull">pull</a> ⇒ <code>Array</code></dt>
<dd><p>移除数组元素</p>
<p>删除数组中所有与给定值相等的元素,给定值可以有多个,该方法会在原数组修改,
返回修改完成后的数组</p>
</dd>
<dt><a href="#module_random">random</a> ⇒ <code>Number</code></dt>
<dd><p>随机数函数</p>
<p>返回min-max之间的随机数,包括min和max,默认返回整数</p>
</dd>
<dt><a href="#module_reduce">reduce</a> ⇒ <code>any</code></dt>
<dd><p>reduce归并函数</p>
<p>适用于多种类型的归并函数,函数接受四个参数,
前一项的值,当前项的值,当前项的索引,对象本身,函数的返回值会作为第一个
参数自动传给下一项,也可以通过使函数返回false终止迭代</p>
</dd>
<dt><a href="#module_reduceRight">reduceRight</a> ⇒ <code>any</code></dt>
<dd><p>rediceRight归并函数</p>
<p>reduce函数的反向函数,从反方向开始迭代,对每一项调用函数fn,
函数fn接受4个参数,前一项的值,当前项的值,当前项的索引,对象本身,
若accumulator存在,则从第一项开始迭代,否则,从第二项开始迭代
若fn函数显式的返回false,则终止迭代,返回结果</p>
</dd>
<dt><a href="#module_remove">remove</a> ⇒ <code>Array</code></dt>
<dd><p>删除数组元素</p>
<p>删除数组中所有对函数返回True的项,返回删除的项,在原数组删除
断言函数接受三个参数,数组当前项的值,索引和数组本身</p>
</dd>
<dt><a href="#module_sample">sample</a> ⇒ <code>any</code></dt>
<dd><p>随机获取集合的某一项的值</p>
<p>随机获取集合的某一项,对于Object和Map类型来说,获取得将会是他们的
Key,而不是Value</p>
</dd>
<dt><a href="#module_sampleSize">sampleSize</a> ⇒ <code>Array</code></dt>
<dd><p>随机抽取一个集合的num个元素</p>
<p>随机抽取一个集合的num个元素,适用于多种类型,若是num大于集合内元素的数量,会随机抽取
集合所有的元素,会将抽取到的元素放到一个数组内,</p>
</dd>
<dt><a href="#module_shuffle">shuffle</a> ⇒ <code>Array</code> | <code>Object</code> | <code>Map</code> | <code>Set</code> | <code>String</code></dt>
<dd><p>打乱集合的顺序</p>
<p>打乱一个集合的顺序,不会改变原集合,而是返回一个新集合,</p>
</dd>
<dt><a href="#module_size">size</a> ⇒ <code>Number</code></dt>
<dd><p>一个集合内元素的数量</p>
<p>对于数组和字符串,为他们的length属性,其他类型的对象,为对象内所有
的可迭代属性的数量</p>
</dd>
<dt><a href="#module_some">some</a> ⇒ <code>Boolean</code></dt>
<dd><p>some迭代函数</p>
<p>适用于多种类型的Some函数,对对象的每一项调用函数,若是有一项使函数返回True,
则返回True,否则返回false</p>
</dd>
<dt><a href="#module_subtract">subtract</a> ⇒ <code>Number</code></dt>
<dd><p>集合内所有元素的差</p>
</dd>
<dt><a href="#module_subtractBy">subtractBy</a> ⇒ <code>Number</code></dt>
<dd><p>集合内元素的差</p>
<p>接受一个函数作为第二参数,对集合内每个元素调用,用来决定求值的标准</p>
</dd>
<dt><a href="#module_sum">sum</a> ⇒ <code>Number</code></dt>
<dd><p>集合内所有值的和</p>
</dd>
<dt><a href="#module_sumBy">sumBy</a> ⇒ <code>Number</code></dt>
<dd><p>集合内元素的和</p>
<p>接受一个函数作为第二参数,用来决定求值的标准</p>
</dd>
<dt><a href="#module_swapIndex">swapIndex</a> ⇒ <code>Array</code> | <code>String</code></dt>
<dd><p>交换元素位置</p>
<p>交换数组或字符串元素的位置,对于数组,在数组本身修改,对于字符串,会返回新的字符串</p>
</dd>
<dt><a href="#module_throttle">throttle</a> ⇒ <code>function</code></dt>
<dd><p>节流函数</p>
</dd>
<dt><a href="#module_toCurrency">toCurrency</a> ⇒ <code>String</code></dt>
<dd><p>将一个数字转化为以逗号分隔的货币形式的字符串</p>
</dd>
<dt><a href="#module_toLower">toLower</a> ⇒ <code>any</code></dt>
<dd><p>将一个字符串或集合中的字符串转化为小写形式</p>
<p>会递归一个集合所有的深度,将它们的字符串值全部转化</p>
</dd>
<dt><a href="#module_toUpper">toUpper</a> ⇒ <code>String</code> | <code>Array</code> | <code>Object</code> | <code>Map</code></dt>
<dd><p>将字符串或一个集合中的字符串大写,</p>
<p>该方法会递归一个集合的所有深度,将集合的所有字符串转化为大写形式</p>
</dd>
<dt><a href="#module_unique">unique</a> ⇒ <code>Array</code></dt>
<dd><p>去重函数</p>
<p>数组去重,不改变原数组,返回去重后的新数组</p>
</dd>
<dt><a href="#module_upperFirst">upperFirst</a> ⇒ <code>String</code> | <code>Array</code> | <code>Object</code> | <code>Map</code></dt>
<dd><p>将字符串或一个集合中的字符串首字母大写,</p>
<p>该方法会递归一个集合的所有深度,将集合的所有字符串转化为首字母大写形式</p>
</dd>
<dt><a href="#module_withOut">withOut</a> ⇒ <code>Array</code></dt>
<dd><p>不改变原数组,返回一个去除给定值的新数组</p>
<p>返回一个新数组,其中包含所有不等于value的值</p>
</dd>
</dl>
<a name="module_add"></a>
## add ⇒ <code>Number</code>
求所有参数的和
对于参数列表中的任何类型,都会尝试相加,所以可能会有强制类型转换
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>any</code> | 参数 |
**Example**
```js
// 'abc'
console.log(_.add('a', 'b', 'c'))
// 6
console.log(_.add(1, 2, 3))
```
<a name="module_after"></a>
## after ⇒ <code>function</code>
函数在count次后执行
限制函数在触发多少次后执行
**Returns**: <code>function</code> - 执行器函数
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| fn | <code>function</code> | | 想要限制执行的函数 |
| count | <code>Number</code> | | 次数 |
| [point] | <code>any</code> | <code>globalThis</code> | 函数执行时环境,默认为globalThis |
**Example**
```js
function after (n) {
console.log('只有在点击四次后才会执行我');
}
let button = document.querySelector('button');
let exec = _.after(after, 4);
button.addEventListener('click', exec);
```
<a name="module_before"></a>
## before ⇒ <code>function</code>
限制函数执行的次数
限制函数只能执行多少次,返回一个执行器函数,用来执行函数,次数到之后,再次执行函数
会失效,
**Returns**: <code>function</code> - 执行器函数
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| fn | <code>function</code> | | 想要限制执行次数的函数 |
| count | <code>Number</code> | | 执行次数 |
| [point] | <code>any</code> | <code>globalThis</code> | 函数运行时所在环境,默认为globalThis |
**Example**
```js
function before (n) {
console.log('只有在前四次点击才会执行我');
}
let button = document.querySelector('button');
let exec = _.before(before, 4);
button.addEventListener('click', exec);
```
<a name="module_camelCase"></a>
## camelCase ⇒ <code>String</code>
驼峰化字符串
函数会舍弃字符串的所有特殊字符,无论是在开头还是中间还是结尾,而在非开头处的数字或特殊字符
后的字母会大写
**Returns**: <code>String</code> - 驼峰化后的字符串
| Param | Type | Description |
| --- | --- | --- |
| str | <code>String</code> | 想要驼峰化的字符串 |
**Example**
```js
let str1 = '@!$as3gh-at^e123!@#';
let str2 = 'a1b2c3';
camelCase(str1); // as3GhAtE123
camelCase(str2); // a1B2C3
```
<a name="module_checkedType"></a>
## checkedType ⇒ <code>String</code>
判断类型的函数
该函数通过Object.prototype.toString方法来判断,所以
若是重写了该方法,函数可能会失效,函数会返回对应类型的大写形式,
**Returns**: <code>String</code> - 返回一个值对应的类型的字符串
| Param | Type | Description |
| --- | --- | --- |
| target | <code>any</code> | 一个需要检查类型的值 |
**Example**
```js
_.checkedType({}); // "Object"
_.checkedType([]); // "Array"
_.checkedType(true); // "Boolean"
_.checkedType(undefined); // "Undefined"
_.checkedType(null); // "Null"
_.checkedType('str'); // "String"
```
<a name="module_compact"></a>
## compact ⇒ <code>Array</code>
获取真值数组
返回一个新数组,包含原数组的所有真值,
假值为:undefined, NaN, 0, false, null
**Returns**: <code>Array</code> - 数组中的真值元素组成的数组
| Param | Type | Description |
| --- | --- | --- |
| arr | <code>Array</code> | array |
**Example**
```js
let arr = [0, 1, false, 2, null, '', 3, NaN, 4, undefined, 5];
// [1, 2, 3, 4, 5];
console.log( _.compact(arr) );
```
<a name="module_curry"></a>
## curry ⇒ <code>function</code>
函数柯里化的辅助函数
接受一个函数fn和可选的用于函数fn的参数,返回柯里化后的函数fn,即使函数fn的参数已经满足
同样会返回一个函数而不是fn调用的结果
**Returns**: <code>function</code> - 柯里化后的函数
| Param | Type | Description |
| --- | --- | --- |
| fn | <code>function</code> | 想要柯里化的函数 |
| ...args | <code>any</code> | 函数fn所需要的参数 |
**Example**
```js
function add (a, b, c, d) {
console.log(a + b + c + d);
}
let curried = _.curry(add, 1, 1, 1, 1);
curried(); // 4
let curried2 = _.curry(add);
curried2(1)(1)(1)(1); // 4
curried2(1, 1)(1)(1); // 4
curried2(1, 1, 1)(1); // 4
```
<a name="module_debounce"></a>
## debounce ⇒ <code>function</code>
创建一个防抖函数
创建一个防抖函数,根据option选项对象来决定delay延时开始前或结束
后调用回调函数,其中option.before决定是否在延时开始之前触发回调,若是为false,那么
无论option.after为true还是false,都会在延时结束后触发回调,option.after决定是否
在延时结束之后触发回调,函数返回的防抖函数拥有一个cancel方法,用来取消延时调用
**Returns**: <code>function</code> - debounced 防抖函数
| Param | Type | Description |
| --- | --- | --- |
| cb | <code>function</code> | 回调函数 |
| delay | <code>0</code> | 延时 |
| option | <code>Object</code> | 选项对象 |
| [option.before] | <code>Boolean</code> | 是否在延时开始之前触发回调 |
| [option.after] | <code>Boolean</code> | 是否在延时结束之后触发回调 |
**Example**
```js
function go () {
console.log('scroll');
}
window.addEventListener( 'scroll', _.debounce(go, 1000) );
window.addEventListener( 'scroll', _.debounce(go, 1000, {before: true, after: true}) );
```
<a name="module_deepClone"></a>
## deepClone ⇒ <code>any</code>
深拷贝函数
一个深拷贝函数,cloneProto参数决定是否拷贝一个对象的原型,不会忽略函数,对象的
Symbol属性,但是对于Symbol属性,仍然传递的是Symbol的引用
**Returns**: <code>any</code> - 深拷贝后的对象
| Param | Type | Description |
| --- | --- | --- |
| target | <code>any</code> | 想要进行深拷贝的对象 |
| cloneProto | <code>Boolean</code> | 是否拷贝对象的原型 |
**Example**
```js
let obj = {
name: 'Jack',
age: 30
};
let o2 = _.deepClone(obj);
```
<a name="module_delay"></a>
## delay ⇒ <code>Object</code>
延时函数
延时函数fn的执行wait毫秒,会返回一个定时器ID
**Returns**: <code>Object</code> - 定时器ID
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| fn | <code>function</code> | | 想要延时的函数 |
| wait | <code>Number</code> | | 延时 |
| args | <code>Array</code> | | 函数fn需要的参数,需要放到一个数组里面 |
| [point] | <code>any</code> | <code>globalThis</code> | 函数fn执行时环境,默认为globalThis |
**Example**
```js
let obj = {
name: 'Sun XiaoChuan',
age: 6,
introduction() {
console.log(`My name is ${this.name} I'm ${this.age} years old`)
}
}
// My name is sun Xiaochuan. I'm 6 years old
let timerId = delay(obj.introduction, 1000, [], obj);
```
<a name="module_divide"></a>
## divide ⇒ <code>Boolean</code>
求商
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
**Example**
```js
// 2
console.log(_.divide([4, 2]));
```
<a name="module_divideBy"></a>
## divideBy ⇒ <code>Number</code>
求商
接受一个函数作为第二参数,对集合内每个元素调用,用来决定求值的标准
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
| iterator | <code>function</code> | 迭代函数 |
**Example**
```js
let arr = [
{age: 30},
{name: 'xxx'},
{age: 30}
];
let arrf = (o) => o.age;
// 1
console.log(_.divideBy(arr , arrf))
```
<a name="module_every"></a>
## every ⇒ <code>Boolean</code>
every迭代函数
适用于多种类型的every函数,对于对象的每个元素调用函数,若所有属性都使
函数返回True则返回True,否则返回false
**Returns**: <code>Boolean</code> - 是否每个元素都对函数返回True
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | object |
| predicate | <code>function</code> | 断言函数 |
**Example**
```js
let arr = [1, 2, 3];
console.log( _.every(arr, item => item > 0) ); // true
```
<a name="module_filter"></a>
## filter ⇒ <code>Array</code>
适用于各种类型的Filter迭代函数
适用于各种类型的Filter迭代函数,对于集合的每一项调用函数,返回函数返回True的
项组成的数组
**Returns**: <code>Array</code> - 函数返回true的项组成的数组
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code> \| <code>Number</code> | 对象 |
| cb | <code>function</code> | 对对象的元素调用的函数 |
**Example**
```js
_.filter([1, 2, 3, 4], item => item % 2 === 0); // [2, 4]
_.filter('Jack', char => true); // ['J', 'a', 'c', 'k']
_.filter(5, n => true); // [0, 1, 2, 3, 4];
```
<a name="module_find"></a>
## find ⇒ <code>any</code>
find迭代函数
适用于多种类型的find方法,它返回第一个使断言函数返回true的项,
对于Object和Map类型,find返回的将不再是项,而是键值对中的键,
fromIndex为迭代的起点,对于数组来说,是其索引,对于对象Map等类型来说,
是获取他们的所有键的数组的索引
**Returns**: <code>any</code> - 第一个使断言函数返回true的项
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>Object</code> | object |
| predicate | <code>function</code> | 断言函数, |
| fromIndex | <code>Number</code> | 迭代的起始索引 |
**Example**
```js
let arr = [1, 2, 3, 4, 5, 6];
console.log( _.find(arr, item => item > 3) ); // 4
let obj = {a: 1, b: 2, c: 3};
console.log( _.find(obj, item => item > 2) ); // c
```
<a name="module_findRight"></a>
## findRight ⇒ <code>any</code>
find函数的反向函数
从反方向开始迭代,返回第一个使函数返回True的项的值
对于对象或Map,返回的将是他们的键而不是值
**Returns**: <code>any</code> - 第一个使断言函数返回true的项
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | object |
| fn | <code>function</code> | 对象每一项调用的函数 |
| fromIndex | <code>Number</code> | 迭代的起始索引 |
**Example**
```js
let arr = [1, 2, 3, 4];
console.log( _.findRight(arr, item => item > 1) ); // 4
```
<a name="module_forEach"></a>
## forEach ⇒ <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code> \| <code>Number</code> \| <code>Object</code>
forEach迭代函数
适用于各种类型的forEach,对集合的每一项运行函数,最终返回集合本身,
可以显式的通过返回false来终止循环
**Returns**: <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code> \| <code>Number</code> \| <code>Object</code> - 集合本身
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code> \| <code>Number</code> \| <code>Object</code> | 对象 |
| cb | <code>function</code> | 对对象的元素调用的函数 |
**Example**
```js
_.forEach([1, 2, 3], item => console.log(item)); 1, 2, 3
_.forEach({name: 'Jack', age: 30}, value => console.log(value)); // 'Jack', 30
```
<a name="module_forEachRight"></a>
## forEachRight ⇒ <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code>
forEachRight迭代函数
forEach函数的反向函数,从结尾开始迭代,可以通过返回false显式的
结束迭代,返回集合本身
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 想要迭代的集合 |
| fn | <code>function</code> | 对每个元素调用的迭代函数 |
**Example**
```js
let arr = [1, 2, 3, 4];
_.forEachRight(arr, item => console.log(item)); // 4, 3, 2, 1
```
<a name="module_isArray"></a>
## isArray
是否是数组类型
使用Array的isArray方法来进行检查
| Param | Type | Description |
| --- | --- | --- |
| value | <code>any</code> | 要检查的值 |
**Example**
```js
// true
_.isArray([]);
```
<a name="module_isBigInt"></a>
## isBigInt ⇒ <code>Boolean</code>
值是否是BigInt类型
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
let bigInt1 = 123n,
bigInt2 = BigInt(456),
bigInt3 = Object(789n);
// true
console.log( isBigInt(bigInt1) );
// true
console.log( isBigInt(bigInt2) );
// true
console.log( isBigInt(bigInt3) );
```
<a name="module_isBoolean"></a>
## isBoolean ⇒ <code>Boolean</code>
检查是否是布尔值
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
// true
_.isBoolean(true)
// true
_.isBoolean(false)
```
<a name="module_isDate"></a>
## isDate ⇒ <code>Boolean</code>
值是否是Date
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
<a name="module_isError"></a>
## isError ⇒ <code>Boolean</code>
是否是Error类型
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// true
console.log(_.isError(new Error()))
```
<a name="module_isFalseValue"></a>
## isFalseValue ⇒ <code>Boolean</code>
检查是否是假植
在这里,假值的概念为值等于 undefined ,null ,false ,0
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// false
console.log( _.isFalseValue(0) );
console.log( _.isFalseValue(false) );
console.log( _.isFalseValue(null) );
console.log( _.isFalseValue(undefined) );
```
<a name="module_isFinite"></a>
## isFinite ⇒ <code>Boolean</code>
值是否是有限数字
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
// true
console.log( _.isFinite(100) );
// false
console.log( _.isFinite(1e10000) );
```
<a name="module_isFunction"></a>
## isFunction ⇒ <code>Boolean</code>
值是否是函数
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// true
console.log(_.isFunction(function f(){}))
```
<a name="module_isInContainer"></a>
## isInContainer ⇒ <code>Boolean</code>
判断一个元素是否在对应容器的可视区域内
**Returns**: <code>Boolean</code> - 是否在可视区域内
| Param | Type | Description |
| --- | --- | --- |
| el | <code>Object</code> | 判断是否在容器的目标DOM元素 |
| container | <code>Object</code> | 容器DOM元素,默认为视口 |
<a name="module_isMap"></a>
## isMap ⇒ <code>Boolean</code>
检查值是否为Map
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
// true
console.log(_.isMap(new Map()))
```
<a name="module_isNaN"></a>
## isNaN ⇒ <code>Boolean</code>
检查是否是NaN
与Javascript自带的isNaN不同,该函数只会对NaN值返回true
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// true
_.isNaN(NaN);
// false
_.isNaN('AAA');
```
<a name="module_isNodeEnv"></a>
## isNodeEnv ⇒ <code>Boolean</code>
是否是Node环境
<a name="module_isNull"></a>
## isNull ⇒ <code>Boolean</code>
检查值是否等于Null
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
// true
console.log(_.isNull(null));
```
<a name="module_isNumber"></a>
## isNumber ⇒ <code>Boolean</code>
检查是否是数字
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// true
_.isNumber(new Number(100));
// true
_.isNumber(100);
```
<a name="module_isObject"></a>
## isObject ⇒ <code>Boolean</code>
检查是否是对象类型
对于任何对象类型包括函数返回True,对于null返回false和undefined返回false
| Param | Type | Description |
| --- | --- | --- |
| value | <code>any</code> | 想要检查的值 |
**Example**
```js
// true
_.isObject([])
// false
_.isObject(null)
// false
_.isObject(undefined)
```
<a name="module_isObjectLike"></a>
## isObjectLike ⇒ <code>Boolean</code>
检查是否是类对象
跟isObject基本相同,只是会对函数返回false,也就是说对
一个非null非function对象返回True
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// false
_.isObjectLike(function f () {})
```
<a name="module_isPlainObject"></a>
## isPlainObject ⇒ <code>Boolean</code>
检查值是否为普通对象
一个普通对象为直接通过Object构造函数或对象字面量创建的对象,
一个对象若是继承了其他对象也算是普通对象
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
let o1 = {},
o2 = {};
Object.setPrototypeOf(o1, o2);
// true
console.log(_.isPlainObject(o1))
// true
console.log(_.isPlainObject(o2))
```
<a name="module_isRegExp"></a>
## isRegExp ⇒ <code>Boolean</code>
是否是RegExp
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 检查的值 |
**Example**
```js
// true
console.log(_.isRegExp(new RegExp()))
```
<a name="module_isSet"></a>
## isSet ⇒ <code>Boolean</code>
是否是Set
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
// true
console.log(_.isSet(new Set()))
```
<a name="module_isString"></a>
## isString ⇒ <code>Boolean</code>
检查是否是字符串
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// true
_.isString('aaa')
// true
_.isString(new String())
```
<a name="module_isSymbol"></a>
## isSymbol ⇒ <code>Boolean</code>
检查值是否是Symbol
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
// true
console.log(_.isSymbol( Symbol("foo")))
// true
console.log(_.isSymbol(Object(Symbol("foo"))))
```
<a name="module_isTrueValue"></a>
## isTrueValue ⇒ <code>Boolean</code>
值是否是真值
在这里,真值的概念为不等于 undefined ,null ,0 ,false,
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// false
console.log(_.isTrueValue(undefined));
// false
console.log(_.isTrueValue(0));
// false
console.log(_.isTrueValue(null));
// false
console.log(_.isTrueValue(false));
// true
console.log(_.isTrueValue('0'));
```
<a name="module_isUndefined"></a>
## isUndefined ⇒ <code>Boolean</code>
检查值是否是Undefined
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 需要检查的值 |
**Example**
```js
// true
console.log( _.isUndefined(Undefined) );
```
<a name="module_isWeakMap"></a>
## isWeakMap ⇒ <code>Boolean</code>
检查值是否是WeakMap
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// true
console.log(_.isWeakMap(new WeakMap()))
```
<a name="module_isWeakSet"></a>
## isWeakSet ⇒ <code>Boolean</code>
检查值是否是WeakSet
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | 想要检查的值 |
**Example**
```js
// true
console.log(_.isWeakSet(new WeakSet()))
```
<a name="module_isWindow"></a>
## isWindow ⇒ <code>Boolean</code>
检查当前宿主环境是否为window
<a name="module_map"></a>
## map ⇒ <code>Array</code>
map迭代函数
适用于各种类型的map迭代函数,对集合的每一项调用函数fn,返回函数
的返回值组成的数组
**Returns**: <code>Array</code> - 函数的返回值组成的数组
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code> \| <code>Number</code> | obj |
| fn | <code>function</code> | 迭代函数 |
**Example**
```js
_.map(5, item => item + '号'); // [ '0号', '1号', '2号', '3号', '4号' ]
_.map([1, 2, 3, 4, 5], (item, index) => index + '号'); // [ '0号', '1号', '2号', '3号', '4号' ]
```
<a name="module_max"></a>
## max ⇒ <code>Number</code> \| <code>String</code>
集合的最大值
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
**Example**
```js
// 3
console.log(_.max([1, 2, 3]))
// c
console.log(_.max({'a', 'b', 'c'}))
```
<a name="module_maxBy"></a>
## maxBy ⇒ <code>any</code>
最大值
接受一个函数作为第二参数,用来决定求值的标准
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
| iterator | <code>function</code> | 迭代函数 |
**Example**
```js
let arr = [
{age: 30},
{name: 'xxx'},
{age: 20}
];
let arrf = (o) => o.age;
// {age: 30}
console.log(_.maxBy(arr, arrf));
```
<a name="module_min"></a>
## min ⇒ <code>Number</code> \| <code>String</code>
求最小值
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>Object</code> | 集合 |
**Example**
```js
// 0
console.log(_.min([1, 2, 3, 0]))
```
<a name="module_minBy"></a>
## minBy ⇒ <code>any</code>
最小值
接受一个函数作为第二参数,用来决定求值的标准
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
| iterator | <code>function</code> | 迭代函数 |
**Example**
```js
let arr = [
{age: 30},
{name: 'xxx'},
{age: 20}
];
let arrf = (o) => o.age;
// {age: 20}
console.log(_.minBy(arr, arrf));
```
<a name="module_multiply"></a>
## multiply ⇒ <code>Number</code>
求集合的乘积
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
**Example**
```js
// 24
console.log(_.multiply([2, 3, 4]))
```
<a name="module_multiplyBy"></a>
## multiplyBy ⇒ <code>Number</code>
集合的乘积
接受一个函数作为第二参数,用来决定求值的标准
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>Object</code> | 集合 |
| iterator | <code>function</code> | 迭代函数 |
**Example**
```js
let arr = [
{age: 30},
{name: 'xxx'},
{age: 20}
];
let arrf = (o) => o.age;
// 600
console.log(_.multiplyBy(arr, arrf))
```
<a name="module_pull"></a>
## pull ⇒ <code>Array</code>
移除数组元素
删除数组中所有与给定值相等的元素,给定值可以有多个,该方法会在原数组修改,
返回修改完成后的数组
**Returns**: <code>Array</code> - 修改完成的数组
| Param | Type | Description |
| --- | --- | --- |
| arr | <code>Array</code> | array |
| ...args | <code>any</code> | 想要删除的元素 |
**Example**
```js
let arr = [1, 2, 3, 4, 3, 2, 6, 1, 2];
_.pull(arr, 1, 2); // [3, 4, 3, 6]
```
<a name="module_random"></a>
## random ⇒ <code>Number</code>
随机数函数
返回min-max之间的随机数,包括min和max,默认返回整数
**Returns**: <code>Number</code> - 一个数字
| Param | Type | Description |
| --- | --- | --- |
| min | <code>Number</code> | 最小值 |
| max | <code>Number</code> | 最大值 |
| floating | <code>Boolean</code> | 是否包括浮点数 |
**Example**
```js
// 2, 5, 1, 1, 2
_.forEach(5, () => {
console.log( _.random(1, 5) );
});
```
<a name="module_reduce"></a>
## reduce ⇒ <code>any</code>
reduce归并函数
适用于多种类型的归并函数,函数接受四个参数,
前一项的值,当前项的值,当前项的索引,对象本身,函数的返回值会作为第一个
参数自动传给下一项,也可以通过使函数返回false终止迭代
**Returns**: <code>any</code> - 函数fn最终的返回值
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>String</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | obj |
| fn | <code>function</code> | 对目标每一项调用的函数 |
| accumulator | <code>any</code> | 初始值 |
**Example**
```js
let o = {a: 1, b: 2, c: 3};
// 6
let result = _reduce(o, (cur, pre) => {
return pre + cur;
});
```
<a name="module_reduceRight"></a>
## reduceRight ⇒ <code>any</code>
rediceRight归并函数
reduce函数的反向函数,从反方向开始迭代,对每一项调用函数fn,
函数fn接受4个参数,前一项的值,当前项的值,当前项的索引,对象本身,
若accumulator存在,则从第一项开始迭代,否则,从第二项开始迭代
若fn函数显式的返回false,则终止迭代,返回结果
**Returns**: <code>any</code> - 构建的最终值
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | object |
| fn | <code>function</code> | 对对象每个元素调用的函数 |
| accumulator | <code>any</code> | 初始值 |
**Example**
```js
let arr = [0, 1, 2, 3, 4];
console.log( _.reduceRight(arr, (pre, cur) => pre + cur) ); // 10
```
<a name="module_remove"></a>
## remove ⇒ <code>Array</code>
删除数组元素
删除数组中所有对函数返回True的项,返回删除的项,在原数组删除
断言函数接受三个参数,数组当前项的值,索引和数组本身
**Returns**: <code>Array</code> - 函数返回true的项组成的数组
| Param | Type | Description |
| --- | --- | --- |
| arr | <code>Array</code> | array |
| fn | <code>function</code> | 断言函数, |
**Example**
```js
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
_.remove(arr); // [ 2, 4, 6, 8, 10 ]
console.log(arr); // [ 1, 3, 5, 7, 9 ]
```
<a name="module_sample"></a>
## sample ⇒ <code>any</code>
随机获取集合的某一项的值
随机获取集合的某一项,对于Object和Map类型来说,获取得将会是他们的
Key,而不是Value
**Returns**: <code>any</code> - 集合的某一项
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code> | 一个集合 |
**Example**
```js
let arr = [1, 2, 3, 4];
// 3, 2, 2, 3, 3, 1, 2, 4, 4, 1
_.forEach(10, () => {
console.log( _.sample(arr) )
})
```
<a name="module_sampleSize"></a>
## sampleSize ⇒ <code>Array</code>
随机抽取一个集合的num个元素
随机抽取一个集合的num个元素,适用于多种类型,若是num大于集合内元素的数量,会随机抽取
集合所有的元素,会将抽取到的元素放到一个数组内,
**Returns**: <code>Array</code> - 抽取的元素组成的数组
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Map</code> \| <code>Set</code> \| <code>Object</code> \| <code>String</code> | 想要随机抽取的对象 |
| num | <code>Number</code> | 想要获得的元素数量 |
**Example**
```js
let arr = [1, 2, 3, 4];
// [3, 1]
console.log(_.sampleSize(arr, 2));
// [2, 4, 3, 1]
console.log(_.sampleSize(arr, 100));
```
<a name="module_shuffle"></a>
## shuffle ⇒ <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code>
打乱集合的顺序
打乱一个集合的顺序,不会改变原集合,而是返回一个新集合,
**Returns**: <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code> - 打乱顺序后的集合
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> \| <code>String</code> | 想要打乱顺序的集合 |
**Example**
```js
let arr = [1, 2, 3, 4];
// [2, 4, 3, 1]
console.log(_.shuffle(arr));
let str = 'ABCD';
// 'ADBC';
console.log(_.shuffle(str));
```
<a name="module_size"></a>
## size ⇒ <code>Number</code>
一个集合内元素的数量
对于数组和字符串,为他们的length属性,其他类型的对象,为对象内所有
的可迭代属性的数量
**Returns**: <code>Number</code> - 集合内元素的数量
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>String</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 一个集合 |
**Example**
```js
let o = {name: 'Davi', age: 22};
// 2
console.log(_.size(o));
```
<a name="module_some"></a>
## some ⇒ <code>Boolean</code>
some迭代函数
适用于多种类型的Some函数,对对象的每一项调用函数,若是有一项使函数返回True,
则返回True,否则返回false
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 对象 |
| predicate | <code>function</code> | 断言函数 |
**Example**
```js
let arr = [1, 2, 3, 4];
console.log( _.some(arr, item => item > 3) ); // true
```
<a name="module_subtract"></a>
## subtract ⇒ <code>Number</code>
集合内所有元素的差
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
**Example**
```js
// 0
console.log(_.subtract([3, 2, 1]))
```
<a name="module_subtractBy"></a>
## subtractBy ⇒ <code>Number</code>
集合内元素的差
接受一个函数作为第二参数,对集合内每个元素调用,用来决定求值的标准
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
| iterator | <code>function</code> | 迭代函数 |
**Example**
```js
let obj = {
name: [1, 2, 3],
age: [4, 5, 6],
color: [7, 8, 9]
};
let objf = (o) => o[0];
// -10
console.log(_.subtractBy(obj, objf));
let arr = [
{age: 30},
{name: 'xxx'},
{age: 20}
];
let arrf = (o) => o.age;
// 10
console.log(_.subtractBy(arr, arrf));
```
<a name="module_sum"></a>
## sum ⇒ <code>Number</code>
集合内所有值的和
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 集合 |
**Example**
```js
// 6
console.log(_.sum([1, 2, 3]))
```
<a name="module_sumBy"></a>
## sumBy ⇒ <code>Number</code>
集合内元素的和
接受一个函数作为第二参数,用来决定求值的标准
| Param | Type | Description |
| --- | --- | --- |
| collection | <code>Array</code> \| <code>Object</code> \| <code>Map</code> \| <code>Set</code> | 一个集合 |
| iterator | <code>function</code> | 用来迭代的函数 |
**Example**
```js
let arr = [
{age: 30},
{name: 'xxx'},
{age: 20}
];
let arrf = (o) => o.age;
// 50
console.log(_.sumBy(arr, arrf))
```
<a name="module_swapIndex"></a>
## swapIndex ⇒ <code>Array</code> \| <code>String</code>
交换元素位置
交换数组或字符串元素的位置,对于数组,在数组本身修改,对于字符串,会返回新的字符串
| Param | Type | Description |
| --- | --- | --- |
| target | <code>Array</code> \| <code>String</code> | 数组或字符串 |
| i | <code>Number</code> | 索引 |
| j | <code>Number</code> | 索引 |
**Example**
```js
_.swapIndex([1, 2], 0, 1); // [2, 1]
_.swapIndex('abcd', 0, 3); // dbca
```
<a name="module_throttle"></a>
## throttle ⇒ <code>function</code>
节流函数
**Returns**: <code>function</code> - 节流后的函数
| Param | Type | Description |
| --- | --- | --- |
| fn | <code>function</code> | 事件处理函数 |
| time | <code>Numer</code> | 延时 |
**Example**
```js
function go () {
console.log('scroll');
}
window.addEventListener( 'scroll', _.throttle(go, 1000) );
```
<a name="module_toCurrency"></a>
## toCurrency ⇒ <code>String</code>
将一个数字转化为以逗号分隔的货币形式的字符串
**Returns**: <code>String</code> - 货币形式的字符串
| Param | Type | Description |
| --- | --- | --- |
| num | <code>Number</code> | 一个数字 |
**Example**
```js
// 123,456,789.123456
console.log( toCurrency(123456789.123456) );
```
<a name="module_toLower"></a>
## toLower ⇒ <code>any</code>
将一个字符串或集合中的字符串转化为小写形式
会递归一个集合所有的深度,将它们的字符串值全部转化
| Param | Type | Description |
| --- | --- | --- |
| target | <code>String</code> \| <code>Object</code> \| <code>Map</code> \| <code>Array</code> | 想要小写的字符串或集合 |
**Example**
```js
let arr = ['AAA', ['BBB', ['CCC']]];
// ['aaa', ['bbb', ['ccc']]];
console.log(_.toLower(arr));
```
<a name="module_toUpper"></a>
## toUpper ⇒ <code>String</code> \| <code>Array</code> \| <code>Object</code> \| <code>Map</code>
将字符串或一个集合中的字符串大写,
该方法会递归一个集合的所有深度,将集合的所有字符串转化为大写形式
**Returns**: <code>String</code> \| <code>Array</code> \| <code>Object</code> \| <code>Map</code> - 转化完成的字符串或集合
| Param | Type | Description |
| --- | --- | --- |
| target | <code>String</code> \| <code>Array</code> \| <code>Object</code> \| <code>Map</code> | 想要大写的字符串或集合 |
**Example**
```js
let arr = ['aaa', {name: 'davi'}, 20];
// ['AAA', {name: 'DAVI'}, 20]
console.log(_.toUpper(['aaa', { name: 'davi' }, 20]));
```
<a name="module_unique"></a>
## unique ⇒ <code>Array</code>
去重函数
数组去重,不改变原数组,返回去重后的新数组
**Returns**: <code>Array</code> - 去重后的数组
| Param | Type | Description |
| --- | --- | --- |
| arr | <code>Array</code> | array |
**Example**
```js
let arr = [1, 2, 3, 4, 1, 2, 3, 5];
_.unique(arr); // [1, 2, 3, 4, 5]
```
<a name="module_upperFirst"></a>
## upperFirst ⇒ <code>String</code> \| <code>Array</code> \| <code>Object</code> \| <code>Map</code>
将字符串或一个集合中的字符串首字母大写,
该方法会递归一个集合的所有深度,将集合的所有字符串转化为首字母大写形式
**Returns**: <code>String</code> \| <code>Array</code> \| <code>Object</code> \| <code>Map</code> - 转化完成的字符串或集合
| Param | Type | Description |
| --- | --- | --- |
| target | <code>String</code> \| <code>Array</code> \| <code>Object</code> \| <code>Map</code> | 想要首字母大写的字符串或集合 |
**Example**
```js
let arr = ['aaa', {name: 'davi'}, 20];
// ['Aaa', {name: 'Davi'}, 20];
console.log(_.upperFirst(arr));
```
<a name="module_withOut"></a>
## withOut ⇒ <code>Array</code>
不改变原数组,返回一个去除给定值的新数组
返回一个新数组,其中包含所有不等于value的值
| Param | Type | Description |
| --- | --- | --- |
| arr | <code>Array</code> | array |
| ...values | <code>any</code> | 想要移除的值 |
**Example**
```js
let arr = [1, 1, 0, 2, 3 ,4 ,5 ,3, 6];
// [0, 2, 4, 5, 6]
console.log( _.withOut(arr, 1, 3) );
```
|
Python
|
UTF-8
| 4,733
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
'''
Creates the client GUI and processes the requests
'''
import tkinter
from tkinter.scrolledtext import ScrolledText
class Spacer(tkinter.Label): # pylint: disable=too-many-ancestors
'''
Loads a blank space by putting a label in
'''
def __init__(self, root):
'''
Loads the blank space
'''
self.root = root
super().__init__(self.root)
self.config(text="")
class ClientGUI(tkinter.Frame): # pylint: disable=too-many-ancestors
'''
Loads all of the GUI sections and contains their methods
'''
def __init__(self, root):
'''
Loads the GUI sections
'''
self.root = root
super().__init__(self.root)
# Set up the two main frames needed
self.info_fr = tkinter.Frame(self.root)
self.info_fr.pack(fill=tkinter.X, side=tkinter.LEFT,
expand=True, anchor=tkinter.N)
self.log_fr = tkinter.Frame(self.root)
self.log_fr.pack(fill=tkinter.BOTH, side=tkinter.RIGHT, expand=True)
self.set_info_frame()
self.set_log_fr()
def set_info_frame(self):
'''
Sets up the entry for the needed connection information
'''
# Server frame
self.server_fr = tkinter.Frame(self.info_fr)
self.server_fr.pack(fill=tkinter.X, expand=True)
# Server label
tkinter.Label(self.server_fr, text="Server:").pack(
fill=tkinter.X, side=tkinter.LEFT, expand=True)
# Server entry
self.server_ent = tkinter.Entry(self.server_fr)
self.server_ent.pack(
fill=tkinter.X, side=tkinter.RIGHT, expand=True, padx=3, pady=3)
# port frame
self.port_fr = tkinter.Frame(self.info_fr)
self.port_fr.pack(fill=tkinter.X, expand=True)
# port label
tkinter.Label(self.port_fr, text="Port:").pack(
fill=tkinter.X, side=tkinter.LEFT, expand=True)
# port entry
self.port_ent = tkinter.Entry(self.port_fr)
self.port_ent.pack(fill=tkinter.X,
side=tkinter.RIGHT, expand=True, padx=3, pady=3)
Spacer(self.info_fr).pack(fill=tkinter.X, expand=True)
# name frame
self.name_fr = tkinter.Frame(self.info_fr)
self.name_fr.pack(fill=tkinter.X, expand=True)
# name label
tkinter.Label(self.name_fr, text="Name:").pack(
fill=tkinter.X, side=tkinter.LEFT, expand=True)
# name entry
self.name_ent = tkinter.Entry(self.name_fr)
self.name_ent.pack(fill=tkinter.X,
side=tkinter.RIGHT, expand=True, padx=3, pady=3)
Spacer(self.info_fr).pack(fill=tkinter.X, expand=True)
tkinter.Button(self.info_fr, text="Connect", command=lambda: self.connect()).pack(
fill=tkinter.X, expand=True)
def set_log_fr(self):
'''
Sets the widgets in the log frame section for server O/I
'''
self.log_msg = ScrolledText(self.log_fr, state="disabled")
self.log_msg.pack(fill=tkinter.BOTH, expand=True, padx=3, pady=3)
self.add_log_text("Waiting to connect...")
self.input_fr = tkinter.Frame(self.log_fr)
self.input_fr.pack(fill=tkinter.BOTH, expand=True, padx=2, pady=2)
self.input_ent = tkinter.Entry(self.input_fr)
self.input_ent.pack(fill=tkinter.BOTH,
side=tkinter.LEFT, expand=True, padx=3, pady=3)
# Send button
tkinter.Button(self.input_fr, text="send", command=self.send_data()).pack(
fill=tkinter.BOTH, side=tkinter.LEFT, expand=True, padx=3, pady=3)
# Disconnect button
tkinter.Button(self.input_fr, text="disconnect", command=self.disconnect()).pack(
fill=tkinter.BOTH, side=tkinter.LEFT, expand=True, padx=3, pady=3)
def connect(self):
'''
Opens the socket connection
'''
return
def disconnect(self):
'''
Disconnects the socket connection
'''
return
def send_data(self):
'''
Sends data to the server
'''
return
def add_log_text(self, msg):
'''
Adds the given message to the log output
'''
msg = str(msg) + "\n"
self.log_msg.config(state="normal")
self.log_msg.insert(tkinter.END, msg)
self.log_msg.config(state="disabled")
def run():
'''
Runs the GUI for testing
'''
tkinter_root = tkinter.Tk()
tkinter_root.title("Chat Room- client")
ClientGUI(tkinter_root).pack(fill=tkinter.BOTH, expand=True)
tkinter_root.mainloop()
if __name__ == "__main__":
run()
|
PHP
|
UTF-8
| 2,946
| 2.78125
| 3
|
[] |
no_license
|
<?php
if (!defined('__ROOT__')) {
define('__ROOT__', dirname(__FILE__, 2));
}
require_once(__ROOT__ . '/Models/Usuario.php');
require_once(__ROOT__ . '/Services/UsuarioService.php');
if (session_id() == '') {
session_start();
}
if (isset($_POST["metodoUsuario"])) {
$controller = new UsuarioController();
$controller->Executar("metodoUsuario");
}
class UsuarioController {
private $retorno;
private $usuarioService;
public function getUsuarioService() {
return $this->usuarioService;
}
public function __construct() {
$this->retorno = new stdClass();
$this->usuarioService = new UsuarioService();
}
//Executa um metodo da class baseado no que foi passado por post
public function Executar($idMetodo) {
$metodo = $_POST[$idMetodo];
if (method_exists($this, $metodo)) {
$this->$metodo($_POST);
} else {
$this->retorno->erro = "metodo não encontrado";
}
//Retorn
echo json_encode($this->retorno);
}
public function Login($dados) {
$login = $dados['login'];
$senha = $dados['senha'];
try {
$usuario = $this->usuarioService->ValidarLogin($login, $senha);
$_SESSION['usuario'] = serialize($usuario);
} catch (Exception $e) {
$this->retorno->erro = $e->getMessage();
}
}
public function CriarUsuario($dados) {
$login = $dados['login'];
$senha = $dados['senha'];
$nivelAcesso = $dados['nivelAcesso'];
$usuario = new Usuario(null, $login, $senha, $nivelAcesso);
$this->usuarioService->CadastrarUsuario($usuario);
}
public function AlterarSenha($dados) {
$id = $dados['usuario'];
$senha = $dados['senha'];
try {
$this->usuarioService->AlterarSenha($id, $senha);
$this->retorno->sucesso = "Senha alterada com sucesso";
} catch (Exception $e) {
$this->retorno->erro = $e->getMessage();
}
}
public function Editar($dados) {
$id = $dados['usuario'];
$login = $dados['login'];
$nivelAcesso = $dados['nivelAcesso'];
$usuario = new Usuario($id, $login, null, $nivelAcesso);
$this->usuarioService->Editar($usuario);
}
public function Listar() {
try {
$this->retorno->lista = $this->usuarioService->Listar();
} catch (Exception $e) {
$this->retorno->erro = $e->getMessage();
}
}
//Não sei aonde está sendo usado
public static function RetornarUsuario($id) {
try {
$usuario = UsuarioService::RetornarLoginId($id);
return $usuario;
} catch (Exception $e) {
$_SESSION['erro'] = $e->getMessage();
echo "<script language='javascript'>history.go(-1);</script>";
exit();
}
}
}
|
Markdown
|
UTF-8
| 1,985
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
# map.setPadding()
Set map paddings. The same as the padding property of CSS.
```typescript
map.setPadding(top, right, bottom, left)
```
## Parameters
name | type | description
------------|---------|---------------------------------------
top | number | padding of top in pixels
right | number | (optional) padding of right in pixels
bottom | number | (optional) padding of bottom in pixels
left | number | (optional) padding of left in pixels
----------------------------------------------------------------------------------------------------------
## Demo code
```html
<div class="map" id="map_canvas" style="position:relative;">
<div style="position:absolute;width:50px;height:100%;right:0;background-color:rgba(0,0,0,0.25);"></div>
<div style="position:absolute;width:10px;height:100%;background-color:rgba(0,0,0,0.25);"></div>
<div style="position:absolute;width:100%;height:30px;background-color:rgba(0,0,0,0.25);"></div>
<div style="position:absolute;width:100%;height:20px;bottom:0;background-color:rgba(0,0,0,0.25);"></div>
</div>
```
```typescript
map: GoogleMap;
isEnabled: any;
loadMap() {
this.map = GoogleMaps.create('map_canvas', {
'controls': {
'compass': true,
'myLocationButton': true,
'indoorPicker': true,
'zoom': true
},
'camera': {
'target': {
'lat': 41.796875,
'lng': 140.757007
},
'tilt': 30,
'zoom': 15,
'bearing': 50
}
});
// Usage case #1:
// top = right = bottom = left = 30px
// this.map.setPadding( 30 );
// Usage case #2:
// top = bottom = 30px
// left = right = 50px
// this.map.setPadding( 30, 50 );
// Usage case #3:
// top = 30px
// left = right = 50px
// bottom = 20px
// this.map.setPadding( 30, 50 , 20 );
// Usage case #4:
// top = 30px
// right = 50px
// bottom = 20px
// left = 10px
this.map.setPadding( 30, 50 , 20 , 10 );
}
```

|
C#
|
UTF-8
| 1,450
| 2.5625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace ExceptionBreaker.Options.ImprovedComponentModel {
public class ImprovedTypeDescriptor : CustomTypeDescriptor {
public ImprovedTypeDescriptor(ICustomTypeDescriptor parent) : base(parent) {
}
public override PropertyDescriptorCollection GetProperties() {
return ProcessProperties(base.GetProperties());
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) {
return ProcessProperties(base.GetProperties(attributes));
}
private static PropertyDescriptorCollection ProcessProperties(PropertyDescriptorCollection properties) {
var newList = new List<PropertyDescriptor>();
foreach (PropertyDescriptor property in properties) {
var descriptorAttribute = (PropertyDescriptorAttribute)property.Attributes[typeof(PropertyDescriptorAttribute)];
if (descriptorAttribute != null) {
var newProperty = (PropertyDescriptor)Activator.CreateInstance(descriptorAttribute.PropertyDescriptorType, new[] { property });
newList.Add(newProperty);
continue;
}
newList.Add(property);
}
return new PropertyDescriptorCollection(newList.ToArray());
}
}
}
|
Java
|
UTF-8
| 498
| 1.664063
| 2
|
[] |
no_license
|
package com.zarate.event.resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zarate.event.service.ViaAemiliaService;
@Controller
public class Battle {
@Autowired
private ViaAemiliaService service;
@GetMapping("/war")
@ResponseBody
public void war() {
service.moveTroops();
}
}
|
Shell
|
UTF-8
| 169
| 2.90625
| 3
|
[] |
no_license
|
#!/usr/bin/env bash
chars=('_' '.' '+') ; for ((i=0; i<1000; i+=$(($RANDOM%10)))); do printf "%$((RANDOM%$(($(tput cols)/2))))s\n" ${chars[RANDOM%${#chars[@]}]} ; done
|
TypeScript
|
UTF-8
| 10,388
| 2.703125
| 3
|
[] |
no_license
|
/**
* Is actually resource-utilities
*/
import * as PathfindingUtilities from "../utilities/Pathfinding";
import {RoomLevel} from "../enums/roomlevel";
import * as RoomRepository from "../repository/Room";
import * as IntelLib from "../lib/intel";
export function getTiersRequiredForPioneerMining(tier: number, possibleMiningPositions: number, spawnPos: RoomPosition, sourcePos: RoomPosition): number {
const ticksToFill = 25; // 50 capacity / 2 mined per tick
let distance = PathfindingUtilities.getDistanseBetween(spawnPos, sourcePos);
let workerpartsNeeded = 5;
let possibleWorkerpartsAtOnceWithTier = possibleMiningPositions * tier;
let workerpartsPossbleAtSource = Math.min(workerpartsNeeded, possibleWorkerpartsAtOnceWithTier);
let timeUsedForMining = ticksToFill / (ticksToFill + (2 * distance));
let workerpartsNeededWithTravel = Math.ceil(workerpartsPossbleAtSource / timeUsedForMining);
return workerpartsNeededWithTravel;
}
/**
* Get number of workerparts needed to distancemine a source to spawn.
* Based on 1 move every tick, ie. enough move-parts.
* TODO: Legg til caching.
*/
export function getTiersRequiredForDistanceMining(source: Source, spawn: Spawn, tier: number): number {
const ticksToFill = 25; // 50 capacity / 2 mined per tick
let energyPerTick = (source.energyCapacity / 300);
let workerpartsNeeded = energyPerTick / 2; // energy per tick / 2 mined per tick
let possibleMiningPositions = getNumberOfPossibleMiningPositions(source);
let possibleWorkerpartsAtOnceWithTier = possibleMiningPositions * tier;
let workerpartsPossbleAtSource = Math.min(workerpartsNeeded, possibleWorkerpartsAtOnceWithTier);
let distance = PathfindingUtilities.getDistanseBetween(source.pos, spawn.pos);
let timeUsedForMining = ticksToFill / (ticksToFill + (distance * 2));
let workerpartsNeededWithTravel = Math.ceil(workerpartsPossbleAtSource / timeUsedForMining);
return workerpartsNeededWithTravel;
}
export function getWorkerPartsRequiredForContainerMining(tier: number /*, sourcePos: RoomPosition, homeRoom: Room*/): number {
let energyPerTick = 10; // TODO: Fix for actual number (source.energyCapacity / 300);
let workerpartsNeeded = (energyPerTick / 2); // energy per tick / 2 mined per tick - I add 2 for making sure I have enough when traveling and dumping.
let possibleMiningPositions = 3; //TODO: Fix for actual number source.getContainerMiningPositions().length;
let possibleWorkerpartsWithTier = possibleMiningPositions * tier;
let workerpartsPossbleAtSource = Math.min(workerpartsNeeded, possibleWorkerpartsWithTier);
return workerpartsPossbleAtSource;
}
export function getRequiredEnergyHaulers(room: Room, maxTier: number): number {
let spawn = room.getSpawn();
if (spawn === undefined) {
return 0;
}
let energyDistancePerHauler = maxTier * 50;
let energyDistance = 0;
let sourcesInRoom = getAllSourcesInRoom(room);
for (let source of sourcesInRoom) {
let distance = PathfindingUtilities.getDistanseBetween(spawn.pos, source.pos);
energyDistance += 10 * distance;
}
let outposts = RoomRepository.getBasicOutposts(room);
for (let outpost of outposts) {
if (IntelLib.hasIntel(outpost)) {
for (let sourceId of IntelLib.sourceIds(outpost)) {
let distance = PathfindingUtilities.getDistanseBetween(spawn.pos, IntelLib.sourcePos(outpost, sourceId));
energyDistance += 10 * distance;
}
}
}
let lairs = RoomRepository.getLairOutposts(room);
for (let outpost of lairs) {
if (IntelLib.hasIntel(outpost)) {
for (let sourceId of IntelLib.sourceIds(outpost)) {
let distance = PathfindingUtilities.getDistanseBetween(spawn.pos, IntelLib.sourcePos(outpost, sourceId));
energyDistance += 16 * distance;
}
}
}
return Math.ceil(energyDistance / energyDistancePerHauler);
}
export function getTiersRequiredForContainerHauling(sourcePos: RoomPosition, homeRoom: Room, sourceSize: number): number {
let storage = homeRoom.storage as Structure;
let spawn = homeRoom.getSpawn();
if (storage === undefined && spawn !== undefined) {
storage = spawn;
}
if (storage === undefined) {
console.log("No spawn or storage found for containerhaulers homeroom.");
return 0;
}
let distance = PathfindingUtilities.getDistanseBetween(storage.pos, sourcePos);
let energyPerTick = Math.ceil(sourceSize / 300);
let timeUsedForRoundtrip = (distance * 2);
let energyPerTrip = timeUsedForRoundtrip * energyPerTick;
if (RoomRepository.getRoomLevel(homeRoom) < RoomLevel.CivilizedColony) {
energyPerTrip = energyPerTrip + 30;
}
return Math.ceil(1.2 * energyPerTrip / 100);
}
export function getTiersRequiredForMineralHauling(mineral: Mineral, homeRoom: Room): number {
let storage = homeRoom.storage as Structure;
let spawn = homeRoom.getSpawn();
if (storage === undefined && spawn !== undefined) {
storage = spawn;
}
if (storage === undefined) {
console.log("No spawn or storage found for mineralhaulers homeroom.");
return 0;
}
let distance = PathfindingUtilities.getDistanseBetween(storage.pos, mineral.pos);
let mineralsPerTick = 4; // Todo, hardcoded, need to be maintained.
let timeUsedForRoundtrip = (distance * 2);
let mineralsPerTrip = timeUsedForRoundtrip * mineralsPerTick;
return Math.ceil(1.2 * mineralsPerTrip / 100);
}
export function getTiersRequiredForOutpostDistanceMining(
sourcePos: RoomPosition, energyCap: number, spawn: Spawn, tier: number,
possibleMiningPositions: number, distance: number ): number {
const ticksToFill = 25; // 50 capacity / 2 mined per tick
let energyPerTick = (energyCap / 300);
let workerpartsNeeded = energyPerTick / 2; // energy per tick / 2 mined per tick
let possibleWorkerpartsAtOnceWithTier = possibleMiningPositions * tier;
let workerpartsPossbleAtSource = Math.min(workerpartsNeeded, possibleWorkerpartsAtOnceWithTier);
if (sourcePos === spawn.pos) {
console.log("Should never happend");
}
let timeUsedForMining = ticksToFill / (ticksToFill + (2 * distance));
let workerpartsNeededWithTravel = Math.ceil(workerpartsPossbleAtSource / timeUsedForMining);
return workerpartsNeededWithTravel;
}
/*
Math:
useless_time_per_1500 = 2 * distance from spawn to source
efficiency = (1300 - useless_time_per_1500) / 1500
worker_parts = ceil (10 / efficiency)
miners_needed = ceil (12 / (2 * 2 * tier))
Example:
distance from spawn: 12
efficiency = 85 %
worker-parts = 12
miners = 3 T1, 2 T2, 1 T3
*/
/**
* Get number of positions that can mine a source
* TODO: Legg til caching.
*/
export function getNumberOfPossibleMiningPositions(source: Source): number {
let count = 0;
for (let x = -1; x < 2; x++) {
for (let y = -1; y < 2; y++) {
let position = new RoomPosition(source.pos.x + x, source.pos.y + y, source.room.name);
if (!(position.x === source.pos.x && position.y === source.pos.y)) {
let atPosition = position.lookFor(LOOK_TERRAIN);
if (atPosition[0] === "swamp" || atPosition[0] === "plain") {
count++;
}
}
}
}
return count;
}
/**
* Gets all mined sources. Currently mined sources means sources in rooms where I have a spawn.
*/
export function getAllMinedSources(rooms: Room[]): Source[] {
let minedSources: Source[] = [];
for (let i = 0; i < rooms.length; i++) {
minedSources = minedSources.concat(getAllSourcesInRoom(rooms[i]));
}
return minedSources;
}
/**
* Gets all sources in a room.
* TODO: Caching
*/
export function getAllSourcesInRoom(room: Room): Source[] {
return room.find(FIND_SOURCES) as Source[];
}
function getDistanceToSource(room: Room, source: Source): number {
let saved = source.getDistanceFrom(room.name);
if (saved === undefined) {
let spawn = room.getSpawn();
if (spawn === undefined) {
return 50;
}
let distance = PathfindingUtilities.getDistanseBetween(spawn.pos, source.pos);
source.setDistanceFrom(room.name, distance);
return distance;
}
return saved;
}
export function getSourcesNeedingHauling(room: Room): string[] {
let sources: Source[] = [];
for (let source of getAllSourcesInRoom(room)) {
let container = source.getMiningContainer();
if (container instanceof StructureContainer) {
let distanceFromBase = getDistanceToSource(room, source);
let limit = 1400 - (distanceFromBase * 16);
if (container.store[RESOURCE_ENERGY] > Math.max(limit, 100)) {
sources.push(source);
}
}
}
let outposts = RoomRepository.getBasicOutposts(room);
for (let outpost of outposts) {
if (Game.rooms[outpost] !== undefined) {
for (let source of getAllSourcesInRoom(Game.rooms[outpost])) {
let container = source.getMiningContainer();
if (container instanceof StructureContainer) {
let distanceFromBase = getDistanceToSource(room, source);
let limit = 1400 - (distanceFromBase * 16);
if (container.store[RESOURCE_ENERGY] > Math.max(limit, 100)) {
sources.push(source);
}
}
}
}
}
let lairs = RoomRepository.getLairOutposts(room);
for (let outpost of lairs) {
if (Game.rooms[outpost] !== undefined) {
for (let source of getAllSourcesInRoom(Game.rooms[outpost])) {
let container = source.getMiningContainer();
if (container instanceof StructureContainer) {
let distanceFromBase = getDistanceToSource(room, source);
let limit = 1400 - (distanceFromBase * 28);
if (container.store[RESOURCE_ENERGY] > Math.max(limit, 100)) {
sources.push(source);
}
}
}
}
}
return _.shuffle(_.map(sources, function (c: Source) {return c.id}));
}
|
Java
|
UTF-8
| 3,350
| 2.109375
| 2
|
[] |
no_license
|
package org.bigjava.test;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;
/**
* @ProjectName: JavaEE
* @ClassName: TestGenerate
* @Description: TODO
* @Author: 洛笙
* @Date: 2020-08-15 13:11
* @Version v1.0
*/
public class TestGenerate {
/**
* 代码生成器
* @data: 2020-08-15-13:11
* @method: test
* @params: []
* @return: void
*/
@Test
public void testGenerate(){
//1、设置全局配置
GlobalConfig config = new GlobalConfig();
//设置是否支持AR模式
config.setActiveRecord(true);
//设置作者
config.setAuthor("洛笙");
//设置生成路径
config.setOutputDir("C:\\Users\\洛笙\\IdeaProjects\\JavaEE\\day16_MyBatisPlus\\src\\main\\java");
//设置文件是否覆盖
config.setFileOverride(true);
//设置主键策略
config.setIdType(IdType.AUTO);
//设置生成的service接口的名字的首字母是否为I
config.setServiceName("%sService");
//XML ResultMap
config.setBaseResultMap(true);
//XML columList
config.setBaseColumnList(true);
//2、数据源配置
DataSourceConfig sourceConfig = new DataSourceConfig();
//设置数据库类型
sourceConfig.setDbType(DbType.MYSQL);
sourceConfig.setDriverName("com.mysql.jdbc.Driver");
sourceConfig.setUsername("root");
sourceConfig.setPassword("123456");
sourceConfig.setUrl("jdbc:mysql://localhost:3306/test");
//3、策略配置
StrategyConfig strategyConfig = new StrategyConfig();
//设置全局大写命名
strategyConfig.setCapitalMode(true);
//设置指定表名 字段名是否使用下划线
strategyConfig.setDbColumnUnderline(true);
//数据库表映射到实体的命名策略
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
//指定数据库表前缀
strategyConfig.setTablePrefix("tbl_");
//指定需要生成的表
strategyConfig.setInclude("tbl_employee");
//4、包名策略配置
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("org.bigjava");
packageConfig.setMapper("mapper");
packageConfig.setService("service");
packageConfig.setController("controller");
packageConfig.setEntity("beans");
packageConfig.setXml("mapper");
//5、整合配置
AutoGenerator autoGenerator = new AutoGenerator();
autoGenerator.setGlobalConfig(config);
autoGenerator.setDataSource(sourceConfig);
autoGenerator.setStrategy(strategyConfig);
autoGenerator.setPackageInfo(packageConfig);
//6、执行
autoGenerator.execute();
/**
*
*
*/
}
}
|
Markdown
|
UTF-8
| 6,378
| 2.65625
| 3
|
[] |
no_license
|
# Distribuidos-Parcial2
# Balanceador de cargas
Balanceador de cargas automatizado
Daniel Steven Ocampo
A00053980
https://github.com/DanielOcampo23/Distribuidos-Parcial2
# Objetivos
-Realizar de forma autónoma el aprovisionamiento automático de infraestructura
-Diagnosticar y ejecutar de forma autónoma las acciones necesarias para lograr infraestructuras estables
-Integrar servicios ejecutándose en nodos distintos
# Descripción
Deberá realizar el aprovisionamiento de un ambiente compuesto por los siguientes elementos: un servidor encargado de realizar balanceo de carga, tres servidores web con páginas estáticas. Se debe probar el funcionamiento del balanceador realizando peticiones y mostrando servidores distintos atendiendo las peticiones.

# Herramientas
-Docker
-Docker-compose
-Nginx
-Html (para probar las páginas web)
# Procedimiento
Primero configuramos el Dockerfile del nginx para su respectiva instalación, el cual va a ser la herramienta encargada de hacer el balanceo de las web, por eso tenemos que asegurarnos de su funcionamiento antes de configurar las web:
```
FROM nginx
# Remove the default Nginx configuration file
RUN rm /etc/nginx/conf.d/default.conf && rm -r /etc/nginx/conf.d
# Copy a configuration file from the current directory
ADD nginx.conf /etc/nginx/nginx.conf
# Append "daemon off;" to the beginning of the configuration
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
# Set the default command to execute
# when creating a new container
CMD service nginx start
```
En este Dockerfile se hace los respectivos pasos para poder garantizar su instalación, uno de los pasos importantes es remover el archivo de configuración que viene por defecto del ngnix y remplazarlo por el nuevo que mostraré a continuación, el cual lo llamaremos nginx.conf:
```
http {
sendfile on;
upstream app_servers {
server web1;
server web2;
server web3;
}
server {
listen 80;
location / {
proxy_pass http://app_servers;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
}
```
En este archivo configuramos cuales son las web que el ngnix balanceará sin necesidad de especificar el puerto 80 ya que el nginx escucha por el puerto 80, por esta razón no hay necesidad de volverlo a describir.
# Docker-compose.yml
Después de configurar el dockerfile del nginx, pasamos a configurar el docker-compose.yml el cual es el encargado de montar toda las infraestructura mostrada en el diagrama de deployment anteriormente, este docker-compose debería quedar así con sus respectivas web:
```
version: '2'
services:
web1:
build: ./web1
volumes:
- dataWeb1:/usr/local/apache2/htdocs
web2:
build: ./web2
volumes:
- dataWeb2:/usr/local/apache2/htdocs
web3:
build: ./web3
volumes:
- dataWeb3:/usr/local/apache2/htdocs
proxy:
build: ./nginx
ports:
- "8080:80"
volumes:
- volNgin:/etc/nginx/volNgin
volumes:
dataWeb1:
dataWeb2:
dataWeb3:
volNgin:
```
En este docker-compose configuramos los servicios, osea las web que va a balancear el nginx y su respectivo volumen en donde se almacenará, después se configura el proxy (nginx) en el cual se le indica la carpeta en donde esta su respectivo Dockerfile y nginx.config que configuramos en anteriormente, después de esto se describe los puertos del nginx y su volumen.
Por ultimo se mencionan todos los volumenes descritos en todo el docker-compose en el "volumes". Tener cuidado con la identación del último "volumes", por que se pueden producir errores al creer que el "volumes" pertenece a un servicio y no a la descripción de todos los volumenes del archivo.
# Configuración de las carpetas con sus archivos de las web
Después de mencionar las carpetas de las web en el docker-compose.yml, procedemos a crearlas y configurarlas con sus respectivos archivos:
-Dockerfile
-index.html
Para el Dockerfile lo configuraremos de esta manera:
```
FROM httpd
#Ubicacion de la index
ADD index.html /usr/local/apache2/htdocs/index.html
```
En este archivo simplemente mencionamos donde se encuentra el html de la web1
Para el index.hmtl
Simplemente adentro de este archivo escribimos el nombre de la web para diferenciarlo de las demás algo como:
```
Pagina web 1
```
Después realizamos lo mismo con las demás web (web2 y web3) para poder tener las tres web requeridas para el balaceo
Las carpetas de la actividad con sus respectivos archivos deberia ser algo como:

# Ejecución
Finalmente después de haber configurado correctamente todos los archivos antes mencionados, procedemos a ejecutar el docker-compose el cual es el encargado de ejecutar toda la infraestructura como lo mencione anteriormente, para esto ejecutamos el siguiente comando:
```
docker-compose up
```
Prueba de funcionamiento:

## Cambios en el contenedor
Por último, es pertinente explicar de manera adecuada como realizar cambios en los archivos y poder hacer aplicar los cambios ya que con solamente bajar el Docker no se efecuarán, para esto es necesario eliminar todas las imagenes de esta manera:
```
docker rm $(docker ps -a -q) -f
```
Después ejecutamos
```
docker-compose build
```
Para poder que lea el Dockerfile con sus nuevos cambios
Por ultimo ejecutamos nuestro
```
docker-compose up
```
# Problematica
Durante la realización de este ejercicio se presentaron una serie de problemas que con el tiempo se fueron solucionando, algunas fueron:
-Aplicar los cambios realizados en el Dockerfile o en cualquier otro archivo, la solución de este problema lo describo anteriomente en "Cambios en el contenedor"
-Otro problema dificil de encontrar fue, la importacia de la identación del archivo docker-compose.yml, ya que si no identamos de manera correcta las etiquetas descritas en este archivo, el sistema puede interpretarlo de otra manera.
|
Java
|
UTF-8
| 1,024
| 3.265625
| 3
|
[
"Unlicense"
] |
permissive
|
public class IfStatement {
public static void main(String[] args) {
boolean isBluetoothEnable = false;
int fileSend = 0;
if (isBluetoothEnable){
System.out.println("Sending the file");
fileSend++;
}else if (fileSend == 0){
System.out.println("No has mandado ningun archivo primero tienes que encender el BT");
}else {
System.out.println("The bluetooth is not enable. Sorry you now this problem before");
}
var age = 3;
switch (age){
case 3:
case 10:
System.out.println("Eres un nino aun");
break;
case 18:
System.out.println("Eres un adulto en Mexico");
break;
case 21:
System.out.println("Eres un adulto en Estados unidos");
break;
default:
System.out.println("Tu edad es aburrida");
break;
}
}
}
|
Java
|
UTF-8
| 3,197
| 1.984375
| 2
|
[] |
no_license
|
package com.olukoye.hannah.bakingapp.UserInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.olukoye.hannah.bakingapp.Adapters.RecipeAdapter;
import com.olukoye.hannah.bakingapp.Pojos.RecipeObjects;
import com.olukoye.hannah.bakingapp.R;
import com.olukoye.hannah.bakingapp.RecipesInterfaceApi;
import com.olukoye.hannah.bakingapp.RetrofitBuilder;
import com.olukoye.hannah.bakingapp.SimpleIdlingResource;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.olukoye.hannah.bakingapp.UserInterface.BakingAppActivity.ALL_RECIPES;
public class MasterFragment extends Fragment {
public MasterFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RecyclerView recyclerView;
View rootView = inflater.inflate(R.layout.recipe_fragment_body_part, container, false);
recyclerView = rootView.findViewById(R.id.recipe_recycler);
final RecipeAdapter recipesAdapter =new RecipeAdapter((BakingAppActivity)getActivity());
recyclerView.setAdapter(recipesAdapter);
if (rootView.getTag()!=null && rootView.getTag().equals("phone-land")){
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(),4);
recyclerView.setLayoutManager(mLayoutManager);
}
else {
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
}
RecipesInterfaceApi iRecipe = RetrofitBuilder.Retrieve();
Call<ArrayList<RecipeObjects>> recipe = iRecipe.getRecipe();
final SimpleIdlingResource idlingResource = (SimpleIdlingResource)((BakingAppActivity)getActivity()).getIdlingResource();
if (idlingResource != null) {
idlingResource.setIdleState(false);
}
recipe.enqueue(new Callback<ArrayList<RecipeObjects>>() {
@Override
public void onResponse(Call<ArrayList<RecipeObjects>> call, Response<ArrayList<RecipeObjects>> response) {
Integer statusCode = response.code();
Log.v("status code: ", statusCode.toString());
ArrayList<RecipeObjects> recipes = response.body();
Bundle recipesBundle = new Bundle();
recipesBundle.putParcelableArrayList(ALL_RECIPES, recipes);
recipesAdapter.setRecipeData(recipes,getContext());
if (idlingResource != null) {
idlingResource.setIdleState(true);
}
}
@Override
public void onFailure(Call<ArrayList<RecipeObjects>> call, Throwable t) {
Log.v("http fail: ", t.getMessage());
}
});
return rootView;
}
}
|
Java
|
UTF-8
| 1,021
| 2.15625
| 2
|
[] |
no_license
|
package com.xyl.mmall.itemcenter.dao.category;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.xyl.mmall.framework.dao.PolicyObjectDaoSqlBaseOfAutowired;
import com.xyl.mmall.itemcenter.intf.DaoInitialInterface;
import com.xyl.mmall.itemcenter.meta.Category;
import com.xyl.mmall.itemcenter.meta.CategoryOSizeMap;
@Repository
public class CategoryOSizeMapDaoImpl extends PolicyObjectDaoSqlBaseOfAutowired<CategoryOSizeMap> implements
CategoryOSizeMapDao, DaoInitialInterface {
public static Map<Long, Long> OPT_MAP = new HashMap<Long, Long>();
@Override
public void loadData() {
List<CategoryOSizeMap> list = _getAllData();
for (CategoryOSizeMap map : list) {
OPT_MAP.put(map.getCategoryId(), map.getOriginalSizeId());
}
}
@Override
public long getCategoryOSizeMap(long categoryId) {
return OPT_MAP.get(categoryId);
}
private List<CategoryOSizeMap> _getAllData() {
return queryObjects(genSelectSql());
}
}
|
JavaScript
|
UTF-8
| 558
| 2.546875
| 3
|
[] |
no_license
|
const PubSub = require('../helpers/pub_sub.js');
const DetailView = require('./details_view.js');
const ListView = function (element) {
this.element = element;
}
ListView.prototype.bindEvents = function () {
PubSub.subscribe('Munros:region-ready', (event) => {
this.data = event.detail;
this.element.innerHTML = "";
this.render();
})
};
ListView.prototype.render = function () {
this.data.forEach( (munro) => {
const detailView = new DetailView(this.element, munro);
detailView.display();
})
};
module.exports = ListView;
|
Java
|
UTF-8
| 918
| 2.765625
| 3
|
[] |
no_license
|
package com.cloudfly.algorithm.juc.thread;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Test_3_ScheduledThreadPoolExecutor {
public static void main(String[] args) {
ScheduledExecutorService threadPoolExecutor = new ScheduledThreadPoolExecutor(1);
for (int i = 0; i < 2; i++) {
RedeliveryConfig redeliveryConfig = new RedeliveryConfig();
redeliveryConfig.setMaximumRedelivery(5);
redeliveryConfig.setBackOffMultiplier(2);
redeliveryConfig.setInitialRedeliveryDelay(2);
redeliveryConfig.setUseMultipleBackOff(true);
threadPoolExecutor.schedule(new MyRunnable(redeliveryConfig, threadPoolExecutor, i),
redeliveryConfig.getInitialRedeliveryDelay(), TimeUnit.SECONDS);
}
}
}
|
Markdown
|
UTF-8
| 2,852
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post-light-feature
title: "Rads and Camping"
description: "Last Friday I completed 15 daily sessions of Radiotherapy, and then went camping for the weekend."
category: articles
tags: [doctors, therapy, drugs]
comments: true
---
The actual treatment itself wasn't too bad, especially once I got on top of the whole breath holding technique. The tediousness came from having to tip off down to Elstree everyday. A boring journey in the back of a taxi. I did see quite a lot of Red Kites, buzzards and kestrals though, which helped pass the time somewhat.
The side effects will continue for another 2 weeks when they peak, and then I should start to get some energy back. It's nowhere near as draining as chemo but still leaves me quite tired and unable to do as much as I want to.
I'm so glad that it's over now, I feel like it's the end of another leg in this epic cancer journey we are on. In December/January, I'll finish the 18 Herceptin treatments that I have every 3 weeks, and that'll be the end of active treatment. That's over a year after diagnosis.
Despite being absolutely shattered after Friday's treatment, I decided I was well enough to go camping. I didn't have to do much, Ross put the tent up with a bit of anti-help from the kids, and I entertained Joni, Greg and Rachel's gorgeous smiley baby. I then stayed around the camp and enjoyed some really good Gin Club company. There's a few changes that have to be made though, for next time. I've realised I can't sleep on our lovely space saving camping mattress. I'm going to have to revert to the old faithful airbed. I'm also going to have to have a proper pillow. The scars and the swelling from the surgery make it just too uncomfortable so I need some extra padding. But the next camping trip can't come soon enough. I really enjoyed it.
In other news, Felix has lost his first two teeth! We also got to test the Tooth Fairy, and she does indeed visit campsites. My boy is growing up so fast. I've just realised that I haven't mentioned on the blog that he turned 6 at the end of May. He had a fabulous birthday and really enjoyed having some friends come round and basically run riot for 2 hours. Five boys were collected by their parents sweaty and happy...Good times!
Imogen has got her birthday next week. She is looking forward to going bowling with her friends followed by a McDonalds.
Ross and I have got some new bikes so we can go out with the bairns when they are on theirs. We've realised that Imogen needs a new bike so Felix can have hers. Felix really needs a bike with gears. They are enjoying having some days where they cycle to and from school and as a side plus point, it's improving my stamina.
And so it continues...keeping on, keeping on. Trying to keep things normal as best we can and I think we are doing ok.
Jx
|
Shell
|
UTF-8
| 953
| 2.90625
| 3
|
[] |
no_license
|
# Maintainer: Anatol Pomozov <anatol@google.com>
pkgname=google-coredumper
pkgver=1.2.1
pkgrel=1
pkgdesc='Library can be compiled into applications to create core dumps of the running program -- without terminating.'
url='https://code.google.com/p/google-coredumper/'
license=(GPL)
arch=(i686 x86_64)
# Upstream is currently broken.
# Here are fixs for upstream https://github.com/anatol/google-coredumper
source=(https://google-coredumper.googlecode.com/files/coredumper-$pkgver.tar.gz
fixes.diff)
sha1sums=('8f770458bca2d0eea878689b5ae2329d7d21d450'
'11d4cc83b2e02210d21271fda608c9a2c2ac8716')
prepare() {
cd coredumper-$pkgver
patch -p1 < "$srcdir/fixes.diff"
}
build() {
cd coredumper-$pkgver
./configure --prefix=/usr
make
}
check() {
cd coredumper-$pkgver
# The tests are broken because they expect binaries with debug symbols. Fix the tests.
# make check
}
package() {
cd coredumper-$pkgver
make install DESTDIR="$pkgdir"
}
|
PHP
|
UTF-8
| 1,547
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Contains the Reflection meta class.
*
* @author Lukas Rezek <lukas@miratronix.com>
* @license MIT
* @filesource
* @version GIT: $Id$
*/
namespace LRezek\Arachnid\Meta;
/**
* Deals with converting english property names to real ones through singularization.
*
* @package Arachnid
* @subpackage Meta
*/
class Reflection
{
/**
* Gets the property relating to a method name for searching.
*
* @param string $methodName Name of the method called.
* @return string Property name.
*/
public static function getProperty($methodName)
{
$property = substr($methodName, 3);
return self::normalizeProperty($property);
}
/**
* Normalizes a property name, by making it lowercase and stripping off "ies" or "s"
*
* @param string $property Property name to sigularize.
* @return string Singularized property name.
*/
public static function normalizeProperty($property)
{
//Remove an underscore, so you can do get_date()
if(substr($property,0,1) == '_')
{
$property = substr($property, 1);
}
$property = lcfirst($property);
// //Deal with famil-'ies', make it 'family'
// if ('ies' == substr($property, -3)) {
// $property = substr($property, 0, -3) . 'y';
// }
//
// //Deal with 'friends', make it 'friend'
// if (preg_match('/[^s]s$/', $property))
// {
// $property = substr($property, 0, -1);
// }
return $property;
}
}
|
C#
|
UTF-8
| 1,607
| 2.671875
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Animation3D : MonoBehaviour
{
private Animator anim;
GameObject thePlayer;
[SerializeField] float theDist;
[SerializeField] string boolForPlay;
bool playIsHappening = false;
AudioSource mySound;
void Start()
{
anim = GetComponent<Animator>();
thePlayer = PlayerScript.instance.gameObject;
mySound = GetComponent<AudioSource>();
}
void CheckForPlayer()
{
if (thePlayer)
{
float dist = Vector3.Distance(transform.position, thePlayer.transform.position);
if (dist < theDist)
{
if (playIsHappening == false) // a flag so we don't perpetually 'SetBool' when within distance
{
anim.SetBool(boolForPlay, true);
playIsHappening = true;
}
}
else
{
if (playIsHappening ) // a flag so we don't perpetually 'SetBool' when OUT of distance
{
anim.SetBool(boolForPlay, false);
playIsHappening = false;
}
}
}
}
void CheckForSound()
{
if (playIsHappening )
{
if (!mySound.isPlaying)
mySound.Play();
}
else
{
if (mySound.isPlaying)
mySound.Stop();
}
}
void Update()
{
CheckForPlayer();
CheckForSound();
}
}
|
Python
|
UTF-8
| 642
| 3.71875
| 4
|
[] |
no_license
|
# Polymorphism
# an object can take on many from
# 1 the same class method works in a similiar way for different classes
# using method overriding by having a method in base or parent class that is overridden by a subclass
# each subclass will have a different implementation of the method
class Animal:
def speak(self):
raise NotImplementedError("Sublcass needs to implement this method")
class Dog(Animal):
def speak(self):
return "woof"
class Cat(Animal):
def speak(self):
return "meow"
class Fish(Animal):
pass
# 2 the same operation works for different kinds of objects
8 + 2 # 10 integers
"8" + "2" #82 strings
|
JavaScript
|
UTF-8
| 306
| 2.546875
| 3
|
[] |
no_license
|
// server.js
const http = require("http");
const quotes= require('./quotes');
const onRequest= (request, response) => {
response.writeHead(200, { "Content-Type": "text/plain" });
response.write(`${quotes.randomQuote().quote}`);
response.end();
}
http.createServer(onRequest).listen(3000);
|
Java
|
UTF-8
| 760
| 2.234375
| 2
|
[] |
no_license
|
package com.rjsoft.uums.api.controller.vo.dict;
import com.rjsoft.common.vo.BaseVO;
import com.rjsoft.uums.facade.dict.entity.UmsDictionaryType;
public class DictTypeForSelectVO implements BaseVO {
private String id;
private String name;
@Override
public void convertPOToVO(Object poObj) {
if(poObj != null){
UmsDictionaryType dictType = null;
if(poObj instanceof UmsDictionaryType){
dictType = (UmsDictionaryType)poObj;
}
if(dictType != null){
this.id = dictType.getId();
this.name = dictType.getValue();
}
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
Java
|
UTF-8
| 1,949
| 2.171875
| 2
|
[] |
no_license
|
package com.zibowh.config;
import com.zibowh.constants.AppConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "spring.redis")
@Component
public class RedisConfig {
private Integer database;
private String host;
private Integer port;
private String password;
private Integer timeout;
private Integer maxTotal;
private Integer maxWaitMillis;
private String seralizerType;
public String getSeralizerType() {
if(StringUtils.isBlank(seralizerType)){
return AppConstants.SerializerTypeEnum.HESSIAN.name();
}
return seralizerType;
}
public void setSeralizerType(String seralizerType) {
this.seralizerType = seralizerType;
}
public Integer getMaxTotal() {
return maxTotal;
}
public void setMaxTotal(Integer maxTotal) {
this.maxTotal = maxTotal;
}
public Integer getMaxWaitMillis() {
return maxWaitMillis;
}
public void setMaxWaitMillis(Integer maxWaitMillis) {
this.maxWaitMillis = maxWaitMillis;
}
public Integer getDatabase() {
return database;
}
public void setDatabase(Integer database) {
this.database = database;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
}
|
Python
|
UTF-8
| 4,565
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
import os
import yaml
def multiqc_config(self):
"""Make sure basic multiQC plugins are installed and plots are exported
Basic template:
.. code-block:: yaml
report_comment: >
This report has been generated by the <a href="https://github.com/nf-core/quantms" target="_blank">nf-core/quantms</a>
analysis pipeline. For information about how to interpret these results, please see the
<a href="https://nf-co.re/quantms" target="_blank">documentation</a>.
report_section_order:
software_versions:
order: -1000
nf-core-quantms-summary:
order: -1001
export_plots: true
"""
passed = []
failed = []
# Remove field that should be ignored according to the linting config
ignore_configs = self.lint_config.get("multiqc_config", [])
fn = os.path.join(self.wf_path, "assets", "multiqc_config.yml")
# Return a failed status if we can't find the file
if not os.path.isfile(fn):
return {"ignored": ["'assets/multiqc_config.yml' not found"]}
try:
with open(fn, "r") as fh:
mqc_yml = yaml.safe_load(fh)
except Exception as e:
return {"failed": [f"Could not parse yaml file: {fn}, {e}"]}
# Check that the report_comment exists and matches
try:
if "report_section_order" not in mqc_yml:
raise AssertionError()
orders = {}
summary_plugin_name = f"{self.pipeline_prefix}-{self.pipeline_name}-summary"
min_plugins = ["software_versions", summary_plugin_name]
for plugin in min_plugins:
if plugin not in mqc_yml["report_section_order"]:
raise AssertionError(f"Section {plugin} missing in report_section_order")
if "order" not in mqc_yml["report_section_order"][plugin]:
raise AssertionError(f"Section {plugin} 'order' missing. Must be < 0")
plugin_order = mqc_yml["report_section_order"][plugin]["order"]
if plugin_order >= 0:
raise AssertionError(f"Section {plugin} 'order' must be < 0")
for plugin in mqc_yml["report_section_order"]:
if "order" in mqc_yml["report_section_order"][plugin]:
orders[plugin] = mqc_yml["report_section_order"][plugin]["order"]
if orders[summary_plugin_name] != min(orders.values()):
raise AssertionError(f"Section {summary_plugin_name} should have the lowest order")
orders.pop(summary_plugin_name)
if orders["software_versions"] != min(orders.values()):
raise AssertionError("Section software_versions should have the second lowest order")
except (AssertionError, KeyError, TypeError) as e:
failed.append(f"'assets/multiqc_config.yml' does not meet requirements: {e}")
else:
passed.append("'assets/multiqc_config.yml' follows the ordering scheme of the minimally required plugins.")
if "report_comment" not in ignore_configs:
# Check that the minimum plugins exist and are coming first in the summary
try:
version = self.nf_config.get("manifest.version", "").strip(" '\"")
if "report_comment" not in mqc_yml:
raise AssertionError()
if mqc_yml["report_comment"].strip() != (
f'This report has been generated by the <a href="https://github.com/nf-core/{self.pipeline_name}/{version}" '
f'target="_blank">nf-core/{self.pipeline_name}</a> analysis pipeline. For information about how to '
f'interpret these results, please see the <a href="https://nf-co.re/{self.pipeline_name}/{version}/output" '
'target="_blank">documentation</a>.'
):
raise AssertionError()
except (AssertionError, KeyError, TypeError):
failed.append("'assets/multiqc_config.yml' does not contain a matching 'report_comment'.")
else:
passed.append("'assets/multiqc_config.yml' contains a matching 'report_comment'.")
# Check that export_plots is activated
try:
if "export_plots" not in mqc_yml:
raise AssertionError()
if not mqc_yml["export_plots"]:
raise AssertionError()
except (AssertionError, KeyError, TypeError):
failed.append("'assets/multiqc_config.yml' does not contain 'export_plots: true'.")
else:
passed.append("'assets/multiqc_config.yml' contains 'export_plots: true'.")
return {"passed": passed, "failed": failed}
|
Java
|
UTF-8
| 2,554
| 2.328125
| 2
|
[] |
no_license
|
package br.com.pismo.transactions.config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import br.com.pismo.transactions.model.ErrorResponse;
import feign.FeignException;
@SuppressWarnings({"unchecked","rawtypes"})
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "Server Error", details);
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(FeignException.class)
public final ResponseEntity<Object> handleFeignException(FeignException ex, WebRequest request) {
ErrorResponse error = null;
try {
error = new ObjectMapper().readValue(ex.content(), ErrorResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity(error, HttpStatus.valueOf(ex.status()));
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
List<String> errors = new ArrayList<String>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.add(error.getField() + ": " + error.getDefaultMessage());
}
for (ObjectError error : ex.getBindingResult().getGlobalErrors()) {
errors.add(error.getObjectName() + ": " + error.getDefaultMessage());
}
ErrorResponse apiError =
new ErrorResponse(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
return handleExceptionInternal(
ex, apiError, headers, apiError.getStatus(), request);
}
}
|
C++
|
UTF-8
| 773
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include "LogSink.h"
#include "LogMessage.h"
#include <vector>
namespace dode
{
class Logger
{
public:
void AddSink(LogSink _Sink);
void RemoveAllSinks();
inline LogMessage CreateMessage(LogLevel _Level, std::string _File, uint32 _Line)
{
return LogMessage(this, _Level, std::move(_File), _Line);
}
void Flush(const LogMessage* _Message);
private:
std::vector<LogSink> m_LogSinks;
};
}
#define DLOG_DEBUG(Logger) Logger.CreateMessage(dode::LogLevel::Debug, __FILE__, __LINE__)
#define DLOG_WARNING(Logger) Logger.CreateMessage(dode::LogLevel::Warning, __FILE__, __LINE__)
#define DLOG_ERROR(Logger) Logger.CreateMessage(dode::LogLevel::Error, __FILE__, __LINE__)
|
C
|
UTF-8
| 161
| 2.859375
| 3
|
[] |
no_license
|
#include<stdio.h>
int incr(int i)
{
static int count=0;
count=count+i;
return (count);
}
int main()
{
int i,j;
for(i=0;i<=4;i++)
j=incr(i);
}
|
C++
|
UTF-8
| 2,575
| 3.453125
| 3
|
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <utility>
#include <vector>
#include <math.h>
#define MOD 1000000007
using namespace std;
int cache[101];
/*
비 대칭 타일링: https://algospot.com/judge/problem/read/ASYMTILING
이 문제는 비 대칭인 타일들의 개수를 구하는 문제이다.
다시 생각해 보면 저번에 풀었던 TILING2 문제에서 대칭인 타일을 제거하는 문제이다.
내가 가장 먼저 들었던 생각은 모든 경우의 수 에서 대칭인 타일만 구하면 되겟다 그 다음에 빼면 되겠다는 생각이었다.
- 저번에 만들었던 tiling 함수를 이용하여 해당 width에 대한 모든 경우의 수를 구했다.
- 그 다음에 양쪽이 1개짜리로 채워지거나 2개짜리로 채워지는 방법의 경우의 수를 구했다.
- 그 다음 그 둘을 뺐다.
이 방법은 아직까지도 이론적으로 가능하다고 생각하지만 예제 테스트케이스도 통과하지 못했다. 뭔가 구현이 어렵다.
이러한 시도 끝에 책을 보았고 다른 방법, 생각의 접근법을 생각 했다.
타일을 채우는 방법의 수 중 대칭인 타일을 찾는 방법의 수는 크게 세가지로 나눌 수 있다.
- width까 홀수인 경우, 가운데는 길쭉한 걸로 채우고 양쪽을 대칭이도록 채우는 경우의 수
- width가 짝수인경우 정확히 반반 대칭인경우
- width가 짝수인경우 정 가운데는 가로가 2인 타일 두개로 채우는 경우
이렇게 세가지 경우에서 양쪽을 채울때, 한쪽만 채우면 다른쪽은 자연스럽게 결정된다고 생각하면 된다 왜냐하면 대칭이니까.
따라서 저번에 만든 tiling 함수로 이 세가지를 구현하면 된다. 전체에서 나머지 반쪽을 채우는 방법의 수를 계산하여 뺀다.
*/
int tiling(int n) {
if (cache[n] != -1) {
return cache[n];
}
if (n == 0 || n == 1) {
return 1;
}
return cache[n] = (tiling(n - 1) + tiling(n - 2)) % MOD;
}
int asymmetry(int width) {
if (width % 2 == 1) {
return (tiling(width) - tiling(width / 2) + MOD) % MOD;
}
int total = tiling(width);
total = (total - tiling(width / 2) + MOD) % MOD;
total = (total - tiling(width/2 - 1) + MOD) % MOD;
return total;
}
int main() {
int testCaseNum;
scanf("%d", &testCaseNum);
memset(cache, -1, sizeof(int) * 101);
while(testCaseNum--) {
int n;
scanf("%d", &n);
printf("%d\n", asymmetry(n));
}
return 0;
}
|
Java
|
UTF-8
| 552
| 2.015625
| 2
|
[] |
no_license
|
package com.bms.order.services;
import org.springframework.transaction.annotation.Transactional;
import com.bms.order.archive.impl.Operator;
import com.bms.order.bean.param.ORDR0901IBean;
/**
* 买手退货单创建接口Service
*
* @author li_huiqian
*/
public interface ORDR0901IService {
/**
* 接收买手退货信息,创建买手退货订单
*
* @param operator 操作者
* @param bean ORDR0901IBean
*/
@Transactional
public Long execute(Operator operator, ORDR0901IBean bean,String returnType);
}
|
Java
|
UTF-8
| 603
| 2.109375
| 2
|
[] |
no_license
|
package com.ericsson.dto.request;
public class LinkProfileRequestDTO {
private String requesterDeviceId;
private String userName;
public String getRequesterDeviceId() {
return requesterDeviceId;
}
public void setRequesterDeviceId(String requesterDeviceId) {
this.requesterDeviceId = requesterDeviceId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "LinkProfileRequestDTO [requesterDeviceId=" + requesterDeviceId + ", userName=" + userName + "]";
}
}
|
Java
|
UTF-8
| 670
| 2.71875
| 3
|
[] |
no_license
|
package cz.sam.cubix.util;
public class MathHelper {
public static int ceiling_double_int(double d) {
int i = (int)d;
return d > (double)i ? i + 1 : i;
}
public static long floor_double_long(double par0) {
long i = (long)par0;
return par0 < (double)i ? i - 1L : i;
}
public static final float sqrt_float(float par0) {
return (float)Math.sqrt((double)par0);
}
public static int floor_double(double par0) {
int var2 = (int)par0;
return par0 < (double)var2 ? var2 - 1 : var2;
}
public static int bucketInt(int par0, int par1) {
return par0 < 0 ? -((-par0 - 1) / par1) - 1 : par0 / par1;
}
}
|
Python
|
UTF-8
| 2,765
| 2.546875
| 3
|
[] |
no_license
|
import json
from selenium import webdriver as wd
import requests
from bs4 import BeautifulSoup
import time
def get_tag(code):
url = 'https://www.youtube.com/'+code
driver = wd.Chrome(executable_path='chromedriver.exe')
driver.get(url)
time.sleep(2)
html = driver.page_source
driver.quit()
soup = BeautifulSoup(html, 'lxml')
try:
tag = soup.find(
class_='style-scope ytd-rich-metadata-renderer', id='title').get_text()
except:
tag = ''
print('tag is none')
return tag
def get_url(code):
url = 'https://www.youtube.com/channel/'+code+'/videos'
driver = wd.Chrome(executable_path='chromedriver.exe')
driver.get(url)
html = driver.page_source
driver.quit()
soup = BeautifulSoup(html, 'lxml')
codes = soup.select('a#video-title')
code_list = []
for i in codes:
code_list.append(i.get('href'))
print(code_list)
return code_list
def run(channel_code):
a = get_url(channel_code)
game_tag_list = []
for i in range(3):
game_tag_list.append(get_tag(a[i]))
return game_tag_list
def run_video(video_id):
url = 'https://www.youtube.com/watch?v='+video_id
driver = wd.Chrome(executable_path='chromedriver.exe')
driver.get(url)
time.sleep(2)
html = driver.page_source
driver.quit()
soup = BeautifulSoup(html, 'lxml')
try:
tag = soup.find(
class_='style-scope ytd-rich-metadata-renderer', id='title').get_text()
if tag == 'YouTube Kids 사용해 보기':
tag = ''
print('tag is none')
except:
tag = ''
print('tag is none')
return tag
with open('./DB_video_data_add.json', 'rt', encoding='utf-8') as f:
origin_json_data = json.load(f)
db_json = {
'channels': []
}
stop_it = False
for i, channel in enumerate(origin_json_data['channels']):
if stop_it == True:
break
# if i > 2:
# break
db_data = {
'id': '',
'videos': []
}
db_data['id'] = channel['id']
for j, video in enumerate(channel['videos']):
if j >= 10:
break
video_data = {
'id': '',
'game_tag': ''
}
video_data['id'] = video['id']
try:
video_data['game_tag'] = run_video(video_data['id'])
print(video_data['game_tag'])
except Exception as e:
print('err', e)
stop_it = True
break
db_data['videos'].append(video_data)
db_json['channels'].append(db_data)
print('{} ok'.format(db_data['id']))
with open('DB_video_data_tag.json', 'wt', encoding='utf-8') as f:
json.dump(db_json, f, ensure_ascii=False, indent='\t')
|
Java
|
UTF-8
| 485
| 2.828125
| 3
|
[] |
no_license
|
package SerializationEx;
public class Employee {
private String name;
private String dept;
private String title;
public Employee(String name, String dept, String title) {
super();
this.name = name;
this.dept = dept;
this.title = title;
}
public String toString() {
return name+":"+dept+":"+title;
}
public String getSerialData() {
String data = "name = "+name+ "\r\n";
data += "dept = "+dept+"\r\n";
data += "title = "+title;
return data;
}
}
|
Go
|
UTF-8
| 242
| 2.703125
| 3
|
[] |
no_license
|
package main
import (
"fmt"
"github.com/acharyab15/test-with-go/math"
)
func main() {
sum := math.Sum([]int{10, -2, 3})
if sum != 11 {
msg := fmt.Sprintf("FAIL: Wanted 11 but received %d", sum)
panic(msg)
}
fmt.Println("PASS")
}
|
C++
|
UTF-8
| 9,614
| 2.609375
| 3
|
[] |
no_license
|
#define D1c 0
#define D1d 1
#define D1e 2
#define D1g 3
#define D1f 4
#define D1b 5
#define D1a 6
#define D2f 7
#define D2b 8
#define D2a 9
#define D2c 10
#define D2g 11
#define D2d 12
#define D2e 13
int COUNT = 0;//count integer for 0-9 increment
int COUNT2 = 1;//count integer for 0-9 increment
void setup(){
for (int i = 0; i <= 13; i++)
pinMode(i, OUTPUT); //Set all pins from 0 to 13 as OUTPUT
}
void loop(){
if (COUNT < 10){
tenths();
ones();
}
if (COUNT == 10){
digitalWrite(D1a, LOW);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, LOW);
digitalWrite(D1e, LOW);
digitalWrite(D1f, LOW);
digitalWrite(D1g, LOW);
COUNT++;
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, LOW);
}
if (COUNT > 10){
greaterones();
greatertens();
}
}
void tenths() {
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, LOW);
delay (100);
digitalWrite(D2a, LOW);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, LOW);
digitalWrite(D2e, LOW);
digitalWrite(D2f, LOW);
digitalWrite(D2g, LOW);
delay(100);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, LOW);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, LOW);
digitalWrite(D2g, HIGH);
delay(100);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, LOW);
digitalWrite(D2f, LOW);
digitalWrite(D2g, HIGH);
delay(100);
digitalWrite(D2a, LOW);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, LOW);
digitalWrite(D2e, LOW);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(100);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, LOW);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, LOW);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(100);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, LOW);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(100);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, LOW);
digitalWrite(D2e, LOW);
digitalWrite(D2f, LOW);
digitalWrite(D2g, LOW);
delay(100);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(100);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, LOW);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(100);
COUNT++;
}
void ones() {
if (COUNT == 0){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, HIGH);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, LOW);
//delay (1000);
}
if (COUNT == 1){
digitalWrite(D1a, LOW);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, LOW);
digitalWrite(D1e, LOW);
digitalWrite(D1f, LOW);
digitalWrite(D1g, LOW);
// delay(1000);
}
if (COUNT == 2){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, LOW);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, HIGH);
digitalWrite(D1f, LOW);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT == 3){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, LOW);
digitalWrite(D1f, LOW);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT == 4){
digitalWrite(D1a, LOW);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, LOW);
digitalWrite(D1e, LOW);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT == 5){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, LOW);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, LOW);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT == 6){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, LOW);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, HIGH);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT == 7){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, LOW);
digitalWrite(D1e, LOW);
digitalWrite(D1f, LOW);
digitalWrite(D1g, LOW);
// delay(1000);
}
if (COUNT == 8){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, HIGH);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT == 9){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, LOW);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
}
void greaterones(){
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, LOW);
delay (1000);
digitalWrite(D2a, LOW);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, LOW);
digitalWrite(D2e, LOW);
digitalWrite(D2f, LOW);
digitalWrite(D2g, LOW);
delay(1000);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, LOW);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, LOW);
digitalWrite(D2g, HIGH);
delay(1000);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, LOW);
digitalWrite(D2f, LOW);
digitalWrite(D2g, HIGH);
delay(1000);
digitalWrite(D2a, LOW);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, LOW);
digitalWrite(D2e, LOW);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(1000);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, LOW);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, LOW);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(1000);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, LOW);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(1000);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, LOW);
digitalWrite(D2e, LOW);
digitalWrite(D2f, LOW);
digitalWrite(D2g, LOW);
delay(1000);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, HIGH);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(1000);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, HIGH);
digitalWrite(D2c, HIGH);
digitalWrite(D2d, HIGH);
digitalWrite(D2e, LOW);
digitalWrite(D2f, HIGH);
digitalWrite(D2g, HIGH);
delay(1000);
COUNT2++;
if (COUNT2 == 10){
COUNT2 = 1;
COUNT = 0;
}
}
void greatertens(){
if (COUNT2 == 2){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, LOW);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, HIGH);
digitalWrite(D1f, LOW);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT2 == 3){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, LOW);
digitalWrite(D1f, LOW);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT2 == 4){
digitalWrite(D1a, LOW);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, LOW);
digitalWrite(D1e, LOW);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT2 == 5){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, LOW);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, LOW);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT2 == 6){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, LOW);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, HIGH);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT2 == 7){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, LOW);
digitalWrite(D1e, LOW);
digitalWrite(D1f, LOW);
digitalWrite(D1g, LOW);
// delay(1000);
}
if (COUNT2 == 8){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, HIGH);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
if (COUNT2 == 9){
digitalWrite(D1a, HIGH);
digitalWrite(D1b, HIGH);
digitalWrite(D1c, HIGH);
digitalWrite(D1d, HIGH);
digitalWrite(D1e, LOW);
digitalWrite(D1f, HIGH);
digitalWrite(D1g, HIGH);
//delay(1000);
}
}
|
Python
|
UTF-8
| 2,071
| 2.78125
| 3
|
[] |
no_license
|
import re
import arrow
from reddit_api import reddit_api
import datetime
from datetime import timedelta
import time
from .cleaner.banned_words import banned_words
from .cleaner.clean_word import clean_word
from .cleaner.remove_space import remove_space
from app import session
from app.models import *
subs = ['bitcoin',
'monero',
'Bitcoincash',
'ethereum',
'Stellar',
'cardano',
'dogecoin',
'Chainlink'
]
class TerminalColors:
HEADER = '\033[95m'
BLACK = '\033[40m'
WHITE = '\033[47m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def print_results(submission):
the_time_posted = determine_time(submission)
print("")
print(f"{TerminalColors.ENDC}{TerminalColors.WARNING}r/{submission.subreddit}{TerminalColors.ENDC}")
print(the_time_posted)
print(submission.id)
print(f"{TerminalColors.ENDC}{TerminalColors.OKCYAN}{submission.title}{TerminalColors.ENDC}")
print("")
def determine_time(submission):
# account for time zone distance in california
then_now = datetime.fromtimestamp(submission.created) - (timedelta(hours=8))
utc = arrow.get(then_now)
local = utc.to('local')
readable_time = local.humanize()
return readable_time
def valid_symbol(word):
if word.startswith('$'):
return True
elif (len(word) == 3 or len(word) == 4) and word.isupper():
return True
else:
return False
def main():
reddit = reddit_api
for sub in subs:
time.sleep(3)
subreddit = reddit.subreddit(sub)
if sub == 'wallsteetbetsnew':
limit_amount = 10
elif sub == 'wallstreetbets':
limit_amount = 20
else:
limit_amount = 5
submissions = subreddit.new(limit=limit_amount)
for submission in submissions:
time.sleep(3)
print_results(submission)
|
Ruby
|
UTF-8
| 1,012
| 2.671875
| 3
|
[] |
no_license
|
require 'rbcoremidi.bundle'
module CoreMIDI
module API
MidiPacket = Struct.new(:timestamp, :data)
end
# Unused, but left here for documentation
def self.number_of_sources
API.get_num_sources
end
class Packet
attr_accessor :type, :note, :volume
def initialize(api_packet)
self.type = {146 => :on, 130 => :off}[api_packet.data[0]]
self.note = api_packet.data[1]
self.volume = api_packet.data[2]
end
end
class Input
def self.register(client_name, port_name, source)
raise "name must be a String!" unless client_name.class == String
client = API.create_client(client_name)
port = API.create_input_port(client, port_name)
API.connect_source_to_port(API.get_sources.index(source), port)
while true
data = API.check_for_new_data
if data && !data.empty?
data.each do |packet|
yield(Packet.new(packet))
end
end
sleep 0.001
end
end
end
end
|
Java
|
UTF-8
| 651
| 2.28125
| 2
|
[] |
no_license
|
package com.waldo.inventory.gui.dialogs.editprojectdialog;
import com.waldo.inventory.classes.dbclasses.ProjectObject;
public class ProjectObjectPreview {
private final ProjectObject projectObject;
private boolean addToProject;
public ProjectObjectPreview(ProjectObject projectObject) {
this.projectObject = projectObject;
this.addToProject = true;
}
public ProjectObject getProjectObject() {
return projectObject;
}
public boolean isAddToProject() {
return addToProject;
}
public void setAddToProject(boolean addToProject) {
this.addToProject = addToProject;
}
}
|
C
|
UTF-8
| 273
| 3.28125
| 3
|
[] |
no_license
|
#include <stdio.h>
void main(){
float n1,n2,media;
for(int x = 1;x<=10;x++){
scanf("%f %f",&n1,&n2);
media = (n1+n2)/2;
if(media >= 7){
printf("Passou direto!");
}else{
printf("Nao passou direto!");
}
printf("Media Final: %.2f",media);
}
return;
}
|
Python
|
UTF-8
| 491
| 2.890625
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 25 15:24:50 2019
@author: alexrandall
"""
import pyautogui, time
time.sleep(5)
pyautogui.click()
distance = 100
while distance > 0:
pyautogui.dragRel(distance, 0, duration = 0.001)
distance = distance - 5
pyautogui.dragRel(0, distance, duration=0.001)
pyautogui.dragRel(-distance, 0, duration=0.001)
distance = distance - 5
pyautogui.dragRel(0, -distance, duration=0.001)
|
Java
|
UTF-8
| 588
| 3.578125
| 4
|
[] |
no_license
|
package designPatterns.State;
/**
* @author wql
* @desc PeacefulState
* @date 2021/5/31
* @lastUpdateUser wql
* @lastUpdateDesc
* @lastUpdateTime 2021/5/31
*/
public class PeacefulState implements State {
private final Mammoth mammoth;
public PeacefulState(Mammoth mammoth) {
this.mammoth = mammoth;
}
@Override
public void observe() {
System.out.println(String.format("%s 平静而祥和。", mammoth));
}
@Override
public void onEnterState() {
System.out.println(String.format("%s 冷静下来。", mammoth));
}
}
|
Python
|
UTF-8
| 5,179
| 2.90625
| 3
|
[] |
no_license
|
#!/usr/bin/python
#-*-coding:utf-8-*-
import urlparse
import requests
import time
class domainRecorder():
'''
用来记录域名,判断子域名的可用性,
记录在同一个域名下的路径
记录子域名的个数
'''
def __time(self):
return time.strftime("%H:%M:%S",time.localtime(time.time()))
def __init__(self,scheme="http",rootDomain='',domain='',path='/',isSubDomain=False):
self.rootDomain=rootDomain.strip()
self.domain=domain.strip() if domain else rootDomain.strip()
self.path=path.strip()
self.scheme=scheme.strip()
self.count=0
self.isSubDomain=isSubDomain
self.url=self.path #self.url 跟self.path是不一样的,
if self.isSubDomain:
self.__GetStatus()
def __GetStatus(self):
url=self.getUrl()
try:
response=requests.get(url)
except requests.exceptions.ConnectionError,e: #说明这是一个顶级域名
self.domain="www."+self.domain
def printSelf(self):
if self.isSubDomain: #获取了subdomain
print "[%s] [INFO] Get subdomain:[%s],RootDomain:[%s],Num:[%d]"%(self.__time(),self.domain,self.rootDomain,self.count)
else:
print "[%s] [INFO] Get path:[%s],in subdomain:[%s],in RootDomain:[%s],Num:[%d]"%(self.__time(),self.path,self.domain,self.rootDomain,self.count)
def judgeDomain(self): #判断是否是一个子域名
domain_list=self.domain.split('.')
rootDomain_list=self.rootDomain.split('.')
# print domain_list
domain_len=len(domain_list)
rootDomain_len=len(rootDomain_list)
if domain_len>rootDomain_len: #判断是否是一个子域名
domain='.'.join([domain_list[i] for i in range(domain_len-rootDomain_len,domain_len)])
if domain!=self.rootDomain:
return False
if domain_len==rootDomain_len:
if self.domain!=self.rootDomain:
return False
return True
def __eq__(self,other): #重载== 号运算符,判断两个url是否是在同一个目录下,简单的,就判定了一级目录
if (self.path=='/') or (other.path=='/'): # 如果任意一个url是根目录,就返回false
if (self.path!="/") or (other.path!='/'):
return False
if self.domain==other.domain:
path1=[]
path2=[]
path_tmp1=self.path.split('/')
for i in path_tmp1:
if 1!='':
path1.append(i)
path_tmp2=other.path.split('/')
for i in path_tmp2:
if 1!='':
path2.append(i)
if path1[0]==path2[0]:
return True
return False
def getPath(self):
path=urlparse.urljoin(self.scheme+"://"+self.domain,self.path)
return path.rstrip('/')+'/'
def getUrl(self): #返回此条记录的url
url=urlparse.urljoin(self.scheme+"://"+self.domain,self.url)
#如果是路径,就要保证最后一定是用/ 结尾
path=self.url.split('/')
if path[-1]=="":
maybeFile=path[-2]
else:
maybeFile=path[-1]
if "." not in maybeFile: #表明是一个路径
#说明最后一个是文件名
# # print removeNum
url=url.rstrip('/')+"/" #必须用/结尾
else:
url=url.rstrip('/')
return url
# def getPath
def reInit(self,url): #用一个url来重新初始化此类
self.url=url
url=urlparse.urlparse(url)
removeNum=-1
self.scheme=url.scheme
self.domain=url.netloc
# if self.rootDomain!=self.domain:
# self.isSubDomain=True
path=url.path
if path=="":
path="/"
path=path.split('/')
if path[-1]=="":
maybeFile=path[-2]
removeNum=-2
else:
maybeFile=path[-1]
removeNum=-1
if "." in maybeFile:
#说明最后一个是文件名
# print removeNum
path[removeNum]=""
self.path=('/').join(path)
else:
self.path=('/').join(path)
while "//" in self.path:
self.path=self.path.replace("//",'/') #把url中的//变为/
if __name__=='__main__':
while True:
a=domainRecorder(domain='search.nwpu.edu.cn',rootDomain='nwpu.edu.cn')
print a.judgeDomain()
|
Markdown
|
UTF-8
| 1,014
| 2.71875
| 3
|
[] |
no_license
|
# Frontend Mentor - Order summary card solution
This is a solution to the [Order summary card challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/order-summary-component-QlPmajDUj). Frontend Mentor challenges help you improve your coding skills by building realistic projects.
## Table of contents
- [Overview](#overview)
- [The challenge](#the-challenge)
- [Screenshot](#screenshot)
- [Links](#links)
- [Built with](#built-with)
- [Author](#author)
## Overview
### Screenshot


### Links
- Live Site URL: [https://stormking969.github.io/Frontend-Mentor---Order-Summary/](https://stormking969.github.io/Frontend-Mentor---Order-Summary/)
### Built with
- Semantic HTML5 markup
- CSS custom properties
- Flexbox
- Mobile-first workflow
## Author
- Website - [Sajana Wijesinghe](https://sajana-wijesinghe.com/)
- Frontend Mentor - [@StormKing969](https://www.frontendmentor.io/profile/StormKing969)
|
Java
|
UTF-8
| 3,553
| 2.109375
| 2
|
[
"MIT"
] |
permissive
|
package ee.tuleva.onboarding.mandate.content.thymeleaf;
import ee.tuleva.onboarding.epis.contact.ContactDetails;
import ee.tuleva.onboarding.fund.Fund;
import ee.tuleva.onboarding.mandate.FundTransferExchange;
import ee.tuleva.onboarding.mandate.Mandate;
import ee.tuleva.onboarding.mandate.application.ApplicationType;
import ee.tuleva.onboarding.user.User;
import ee.tuleva.onboarding.user.address.Address;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import org.thymeleaf.context.Context;
public class ContextBuilder {
private Context ctx = new Context();
public static ContextBuilder builder() {
return new ContextBuilder();
}
public Context build() {
return ctx;
}
public ContextBuilder user(User user) {
ctx.setVariable("email", user.getEmail());
ctx.setVariable("firstName", user.getFirstName());
ctx.setVariable("lastName", user.getLastName());
ctx.setVariable("idCode", user.getPersonalCode());
ctx.setVariable("phoneNumber", user.getPhoneNumber());
return this;
}
public ContextBuilder mandate(Mandate mandate) {
DateTimeFormatter formatterEst =
DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault());
String documentDate = formatterEst.format(mandate.getCreatedDate());
DateTimeFormatter formatterEst2 =
DateTimeFormatter.ofPattern("dd.MM.yyyy").withZone(ZoneId.systemDefault());
String documentDatePPKKAAAA = formatterEst2.format(mandate.getCreatedDate());
ctx.setVariable("documentDate", documentDate);
ctx.setVariable("documentDatePPKKAAAA", documentDatePPKKAAAA);
return this;
}
public ContextBuilder funds(List<Fund> funds) {
// sort because by law, funds need to be in alphabetical order
funds.sort(
(Fund fund1, Fund fund2) ->
fund1.getNameEstonian().compareToIgnoreCase(fund2.getNameEstonian()));
ctx.setVariable("funds", funds);
ctx.setVariable(
"fundIsinNames",
funds.stream().collect(Collectors.toMap(Fund::getIsin, Fund::getNameEstonian)));
return this;
}
public ContextBuilder transactionId(String transactionId) {
ctx.setVariable("transactionId", transactionId);
return this;
}
public ContextBuilder futureContributionFundIsin(String futureContributionFundIsin) {
ctx.setVariable("selectedFundIsin", futureContributionFundIsin);
return this;
}
public ContextBuilder documentNumber(String documentNumber) {
ctx.setVariable("documentNumber", documentNumber);
return this;
}
public ContextBuilder fundTransferExchanges(List<FundTransferExchange> fundTransferExchanges) {
ctx.setVariable("fundTransferExchanges", fundTransferExchanges);
return this;
}
public ContextBuilder applicationTypeToCancel(ApplicationType applicationTypeToCancel) {
ctx.setVariable("applicationTypeToCancel", applicationTypeToCancel);
return this;
}
public ContextBuilder contactDetails(ContactDetails contactDetails) {
ctx.setVariable("contactDetails", contactDetails);
if (ctx.getVariable("email") == null) {
ctx.setVariable("email", contactDetails.getEmail());
}
return this;
}
public ContextBuilder address(Address address) {
ctx.setVariable("addressLine1", address.getStreet());
ctx.setVariable("countryCode", address.getCountryCode());
ctx.setVariable("postCode", address.getPostalCode());
ctx.setVariable("districtName", address.getDistrictCode());
return this;
}
}
|
Markdown
|
UTF-8
| 5,587
| 2.625
| 3
|
[] |
no_license
|
# Getting Started
Learn the essentials of iOS app development by building a fully functional app using SwiftUI.
Before you start the course, take a few minutes to familiarize yourself with the background requirements, key concepts behind SwiftUI, and the app that you’ll build.
<!---->
5 min Estimated Time
<!---->
<!---->
## 關於本課程
這些教程是為SwiftUI新手而設計的。在開始之前,您需要了解一些有關Swift的知識,因此,請首先回顧一下Swift編程語言的[The Basics](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html)。語法,數據類型和獨特的語言功能(例如可選)的概述。另外,請查看[Closures](https://docs.swift.org/swift-book/LanguageGuide/Closures.html)部分,因為您將在SwiftUI中頻繁使用它們。
## SwiftUI概述
SwiftUI是用於任何Apple平台構建應用程序的聲明性框架。使用SwiftUI通過一種語言和通用API定義應用程序的UI和行為。
借助以下關鍵的SwiftUI功能,可以更快,更少錯誤地創建應用程序:
* 聲明性語法-使用簡單的Swift結構定義在屏幕上顯示的視圖。您的視圖會自動保持最新狀態。
* 複合API-使用內置視圖和修飾符快速創建和迭代UI。通過合併更簡單的視圖來構成更複雜的視圖。
* 強大的佈局系統-當現有的視圖和控件無法滿足您的需求時,您可以自己繪製。
* 視圖反映了應用程序數據-定義視圖的數據依存關係,SwiftUI會在數據更改時自動更新視圖,從而避免了無效視圖狀態導致的錯誤。
* 自動輔助功能支持-SwiftUI添加了基本的輔助功能,您將學習到這些基本的輔助功能,從而可以輕鬆完成。
##應用程序之旅
許多軟件工程團隊使用稱為Scrum的日常會議來計劃其當天的工作。 Scrum是簡短的會議,每個參與者在會議上討論他們昨天的成就,今天的工作以及可能影響其工作的任何障礙。
本課程將指導您開發Scrumdinger,這是一個iOS應用程序,可幫助用戶管理其日常Scrum。為了幫助使Scrum簡短而集中,Scrumdinger使用視覺和音頻提示來指示每個與會者何時和多長時間發言。該應用程序還顯示進度視圖,顯示會議中剩餘的時間,並創建一個記錄,供用戶以後參考。
這是您在本課程中將要學習的內容的詳細介紹。
### Scrum 列表
該應用程序的主屏幕顯示了用戶每天的日常消費摘要。用戶可以點擊列表中的一行以查看Scrum的詳細信息,也可以通過點擊導航欄中的Add(+)按鈕來創建新的Scrum。
<picture data-v-6f999518=""><!----><img alt="Screenshot of list of scrums under Daily Scrums heading" srcset="https://docs-assets.developer.apple.com/published/0a6ca8a678102b11bf19cd5ee489a147/600/A010-002-001.png 1x, https://docs-assets.developer.apple.com/published/968cc808ec1b585c32edfde46c72cded/600/A010-002-001@2x.png 2x" src="https://docs-assets.developer.apple.com/published/0a6ca8a678102b11bf19cd5ee489a147/600/A010-002-001.png" width="287" height="auto"></picture>
### Scrum 詳細信息和編輯
詳細信息視圖顯示有關Scrum的更多信息,包括每個與會者的姓名和以前的會議列表。用戶可以通過點擊"編輯"按鈕來修改Scrum的任何屬性。點擊列表頂部的"開始會議"按鈕將啟動一個新的會議計時器。
<picture data-v-6f999518=""><!----><img alt="Screenshot of scrum details shown in grouped lists, including Meeting info, Attendees, and History" srcset="https://docs-assets.developer.apple.com/published/4d4f7cadb47ff1d6d232910c82b928e2/600/A010-002-002.png 1x, https://docs-assets.developer.apple.com/published/251d0bbb5276d29d4088900fe761225a/600/A010-002-002@2x.png 2x" src="https://docs-assets.developer.apple.com/published/4d4f7cadb47ff1d6d232910c82b928e2/600/A010-002-002.png" width="287" height="auto"></picture>
###會議計時器
會議計時器頂部的進度條顯示會議的經過時間和剩餘時間。該應用程序在屏幕中央顯示當前揚聲器的名稱,並在屏幕底部顯示一個前進至下一個揚聲器的按鈕。
每個與會者由圓形進度環中的一個部分錶示。與會者的時間到時,Scrumdinger會播放"叮"聲,並將新的片段添加到鈴聲中。鈴響了,會議結束了。
<picture data-v-6f999518=""><!----><img alt="Screenshot of meeting timer screen with three main sections" srcset="https://docs-assets.developer.apple.com/published/8fd7656901879e616d44d2239f7a68cd/600/A010-002-003.png 1x, https://docs-assets.developer.apple.com/published/d8f494c0fd9861bcdfcbb19ff4973d92/600/A010-002-003@2x.png 2x" src="https://docs-assets.developer.apple.com/published/8fd7656901879e616d44d2239f7a68cd/600/A010-002-003.png" width="255" height="auto"></picture>
##成功秘訣
*邊做邊學。每個教程都包括入門項目和已完成的項目。打開入門項目,並完成教程中的每個步驟。
*在學習中發揮積極作用。閱讀每個步驟,並在查看代碼差異之前考慮如何完成給定的任務。
*確保安裝了[最新版本的Xcode](https://apps.apple.com/us/app/xcode/id497799835?mt=12)。
##開始建設
既然您已經了解了Scrumdinger,現在就可以構建它了。而且不用擔心會卡住。您可以在學習教程時查看每個步驟的代碼差異,也可以下載並查看Xcode中已完成的項目。您也可以訪問[開發者論壇](https://developer.apple.com/forums/tags/swiftui),以獲得有關各種開發主題的幫助。
|
Python
|
UTF-8
| 3,164
| 2.640625
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
# coding: utf-8
# File: chatBot.py
# Author: lhy<lhy_in_blcu@126.com,https://huangyong.github.io>
# Date: 19-3-29
import urllib.request
from urllib.parse import quote_plus
from lxml import etree
import json
class ZhidaoChatbot:
def __init__(self):
return
'''获取搜索页'''
def get_html(self, url):
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.17"}
req = urllib.request.Request(url, headers=headers)
html = urllib.request.urlopen(req).read().decode('utf-8')
return html
'''采集问答首页'''
def collect_urls(self, url):
html = self.get_html(url)
print(url)
selector = etree.HTML(html)
questions = [i.xpath('string(.)').replace('搜狗问问','').replace('搜狗', '').replace('-','') for i in selector.xpath('//div[@class="vrwrap"]/h3[@class="vrTitle"]/a')]
links = ['https://wenwen.sogou.com/z/' + i.split('.htm&')[0].split('2F')[-1] + '.htm' for i in selector.xpath('//div[@class="vrwrap"]/div/a/@href')]
pairs = list(zip(questions, links))
return pairs[:3]
'''采集答案'''
def parser_answer(self, url):
html = self.get_html(url)
selector = etree.HTML(html)
answers = [i.xpath('string(.)').replace('\u3000','').replace('\n', '').replace('\xa0', '').replace(' ', '。').replace('\r', '') for i in selector.xpath('//pre')]
answers = [i for i in answers if '?' not in i and '?' not in i and len(set(i)) > 2 and '为什么' not in i]
answer_dict = {answer:len(answer) for answer in answers}
answers = [i[0] for i in sorted(answer_dict.items(), key=lambda asd:asd[1])]
return answers
'''收集答案'''
def collect_answers(self, url):
answers_all = []
url_pairs = self.collect_urls(url)
for question, answer_url in url_pairs:
answers = self.parser_answer(answer_url)
answers_all += answers
answer_dict = {answer:len(answer) for answer in answers_all}
best_answers = [i[0] for i in sorted(answer_dict.items(), key=lambda asd:asd[1])][:5]
return best_answers
'''扩展问句'''
def expand_question(self, question):
url = 'https://wenwenfeedapi.sogou.com/sgapi/web/related_search_new?key=' + quote_plus(question)
data = json.loads(self.get_html(url))
others = data["data"]
return others
'''问答'''
def qa_main(self, question):
url = 'https://www.sogou.com/sogou?query='+quote_plus(question) +'&ie=utf8&s_from=result_up&insite=wenwen.sogou.com'
answers = self.collect_answers(url)
other_questions = self.expand_question(question)
return answers, other_questions
'''测试'''
def test():
handler = ZhidaoChatbot()
# while 1:
# question = input('qu').strip()
answers, other_questions = handler.qa_main("降准以后会怎样")
print('回答:', answers)
# print('你可能还想问:', other_questions)
# print('*******'*6)
if __name__ == '__main__':
test()
|
C++
|
UTF-8
| 574
| 2.6875
| 3
|
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,k;
cin >> n >> k;
int arr[n];
for(int i=0;i<n;i++){
cin >> arr[i];
}
sort(arr,arr+n);
int ans = arr[n-1] - arr[0];
int small = arr[0] + k;
int big = arr[n-1] - k;
if(small > big){
swap(small,big);
}
for(int i=1;i<n-1;i++){
int sub = arr[i] - k;
int add = arr[i] + k;
if(!(sub>=small || add<=big)){
if(big-sub <= add-small){
small = sub;
}
else{
big = add;
}
}
}
cout << min(ans,big-small) << endl;
return 0;
}
|
JavaScript
|
UTF-8
| 1,266
| 2.5625
| 3
|
[] |
no_license
|
/* eslint-disable */
import createElement from "../../../js/Utils/createElement";
import Helpers from "../../../js/Utils/Helpers";
export function MainInit() {
const main = createElement("div", "main-container");
document.body.prepend(main);
}
function createParsedUrl(request) {
return (
(request.resource ? `/${request.resource}` : "/") +
(request.id ? "/:id" : "") +
(request.verb ? `/${request.verb}` : "")
);
}
// TODO: How to stop block render if state the same ?
export function Main(state, getPage) {
const main = document.querySelector(".main-container");
const url = state.url.value;
const request = Helpers.parseRequestURL(url);
main.innerHTML = "";
switch (request.resource) {
case "":
case "categories":
main.appendChild(getPage("Categories"));
break;
case "category":
main.appendChild(getPage("Cards"));
break;
case "stats":
main.appendChild(getPage("Stats"));
break;
case "win":
main.appendChild(getPage("Win"));
break;
case "fail":
main.appendChild(getPage("Fail"));
break;
default:
break;
}
}
|
Python
|
UTF-8
| 1,806
| 3.5
| 4
|
[] |
no_license
|
class Coffee_Machine_Handler:
def __init__(self, coffee_machine):
self.coffee_machine = coffee_machine
def check_resources(self, coffee):
issues = []
if self.coffee_machine.water < coffee.water:
issues.append("Not Enough Water")
if self.coffee_machine.milk < coffee.milk:
issues.append("Not Enough Milk")
if self.coffee_machine.coffee < coffee.coffee:
issues.append("Not Enough Coffee")
if len(issues) == 0:
return True
return issues
def handle_money(self, money, coffee):
issues = []
if money < coffee.cost:
issues.append(
f"Not enough money, received only ${money} and the cost is: ${coffee.cost}"
)
if len(issues) == 0:
return True
return issues
def give_coffee(self, coffee):
return f"Please enjoy your {coffee}. See you soon!"
def make_transaction(self, money, coffee):
self.coffee_machine.water -= coffee.water
self.coffee_machine.milk -= coffee.milk
self.coffee_machine.coffee -= coffee.coffee
self.coffee_machine.money += coffee.cost
def handle_transaction(self, money, coffee):
resources_result = self.check_resources(coffee)
if type(resources_result) is list:
return resources_result
handle_money_result = self.handle_money(money, coffee)
if type(handle_money_result) is list:
return handle_money_result
self.make_transaction(money, coffee)
return self.give_coffee(coffee)
def get_report(self):
return f"Water: {self.coffee_machine.water}\nMilk: {self.coffee_machine.milk}\nCoffee {self.coffee_machine.coffee}\nMoney: ${self.coffee_machine.money}"
|
JavaScript
|
UTF-8
| 1,249
| 4.125
| 4
|
[] |
no_license
|
//Esercizi-3 js
//write a funciton that randomizes two numbers and prints the smallest number that is greater than one,
//such that both numbers are divided by it with no remainder.
//For instance, for 9 and 6 you should print 3. If there isn't one a proper note should be printed
//************************ GENERAZIONE DELL'INPUT
//Funzione che che estre un numero casuale compreso nell'intervallo (0,int] di base è [0,10]
function randomNatural(min,max,int){
var array = [];
if(isNaN(int))
int = 0;
if(isNaN(max))
max = 0;
if(isNaN(min))
min = 0;
while(int--)
array.push(randomInt(min,max));
return array;
}
//Funzione che che estre un numero casuale compreso nell'intervallo (0,int] di base è [0,10]
function randomInt(min,max){
return Math.floor(Math.random()*(max-min+1)+min);;
}
//************************ Esercizio 012
//Implementazione ONE-LINE
function ex12(min,max){
var rand1 = randomInt(min,max);
var rand2 = randomInt(min,max);
console.log("Estratto "+rand1+", "+rand2);
var d = 1;
var find = false;
while( !find && (d <= rand1) && (d <= rand2) ){
if(d > 1 && rand1%d==0 && rand2%d==0){
find = true;
}
if(!find)
d++;
}
if (find)
return d;
}
//************************ TESTING
ex12(0,100);
|
Go
|
UTF-8
| 3,145
| 3.046875
| 3
|
[] |
no_license
|
package wet
import (
"os"
"compress/gzip"
"bufio"
"regexp"
"strconv"
"strings"
)
type WETEntry struct {
Version string
Headers map[string]string
Body []byte
}
type WETReader struct {
reader *bufio.Reader
gzip *gzip.Reader
header *WETEntry
}
/**
* Builds a new WETReader from a GZip file, or returns an error if cannot process
* the given file
*/
func FromGZip(file string) (wr *WETReader, err error) {
if fr, err := os.Open(file); err == nil {
if gzr, err := gzip.NewReader(fr); err == nil {
wr = &WETReader { bufio.NewReader(gzr), gzr, nil }
err = wr.init()
}
}
return
}
/**
* Returns the header describing this WET file
*/
func (reader *WETReader) Header() *WETEntry {
return reader.header
}
/**
* Returns the next entry on the WET file, or an error if could not parse it. If
* the end of the file was reached, return an io.EOF error.
*/
func (wet *WETReader) Channel() (<-chan struct { Entry *WETEntry; Err error }) {
channel := make(chan struct { Entry *WETEntry; Err error })
go func() {
defer func() {
wet.Close()
close(channel)
}()
for {
entry, err := wet.extractEntry()
channel <- struct { Entry *WETEntry; Err error }{ entry, err }
if err != nil {
return
}
}
}()
return channel
}
func (wet *WETReader) Close() {
wet.gzip.Close()
}
func (wet *WETReader) init() (err error) {
header, err := wet.extractEntry()
if err != nil {
return
}
wet.header = header
return
}
var versionRegex = regexp.MustCompile("WARC/(.*)")
var headerRegex = regexp.MustCompile("([^:]+): (.*)")
func (wet *WETReader) extractEntry() (entry *WETEntry, err error) {
defer func() {
r := recover()
if r != nil {
err = r.(error)
}
}()
version := wet.parseVersion()
headers := wet.parseHeaders()
bodyLength, err := strconv.Atoi(headers["Content-Length"])
if err != nil {
return
}
body := wet.parseBody(bodyLength)
wet.nextLine()
wet.nextLine()
entry = &WETEntry { version, headers, body }
return
}
func (wet *WETReader) nextLine() string {
line, err := wet.reader.ReadString(byte('\n'))
if err != nil {
panic(err)
}
return strings.TrimSpace(string(line))
}
func (wet *WETReader) parseVersion() string {
line := wet.nextLine()
return versionRegex.FindStringSubmatch(line)[1]
}
func (wet *WETReader) parseHeaders() (headers map[string]string) {
headers = make(map[string]string)
line := wet.nextLine()
for line != "" {
match := headerRegex.FindStringSubmatch(line)
headers[match[1]] = match[2]
line = wet.nextLine()
}
return
}
func (wet *WETReader) parseBody(length int) (body []byte) {
body = make([]byte, length)
total := 0
for total < length {
read, err := wet.reader.Read(body[total:])
if err != nil {
panic(err)
}
total += read
}
return
}
|
Markdown
|
UTF-8
| 630
| 3.015625
| 3
|
[
"Vim"
] |
permissive
|
# vim-hugo
Blogging from the command line should not be tedious.
This script is intended to automate the process of creating
[Hugo](https://gohugo.io/) blog posts from within
[vim](http://www.vim.org/).
This is a complete rewrite of
[parkr/vim-jekyll](https://github.com/parkr/vim-jekyll)
## Commands
The `:HugoPost` (Hugo post) command is used to create blog posts.
:HugoPost[!] [{name}] Create the specified post. With no argument,
you will be prompted to select a post or enter a title.
## Configuration
See `:help hugo-configuration`.
## License
Same as Vim itself, see `:help license`.
|
JavaScript
|
UTF-8
| 1,316
| 2.84375
| 3
|
[] |
no_license
|
function button_handler() {
let elem = document.getElementById("textarea");
let currentSize = getComputedStyle(elem, null).fontSize
let intCurrentSize = parseInt(currentSize);
elem.style.fontSize = (intCurrentSize + 2) + "pt";
}
function button_click() {
setInterval(button_handler, 500);
}
function box_checked() {
let textareavar = document.getElementById("textarea");
if (document.getElementById("bling").checked) {
textareavar.style.fontWeight = "bold";
textareavar.style.color = "green";
textareavar.style.textDecoration = "underline";
document.body.style.backgroundImage = "url('https://www.pixelstalk.net/wp-content/uploads/2016/07/4k-Images-Free-Download.jpg')";
} else {
textareavar.style.fontWeight = "normal";
textareavar.style.color = "black";
textareavar.style.textDecoration = "none";
document.body.style.backgroundImage = "none";
}
}
function malko() {
let textareavar = document.getElementById("textarea");
let data = textareavar.value;
let array = data.toString().split(" ");
textareavar.value = array.map(word => {
if (word.length >= 5) return "Malkovich";
else return word;
}).toString()
.replaceAll(",", " \n")
}
|
Shell
|
UTF-8
| 1,711
| 3.859375
| 4
|
[] |
no_license
|
#!/usr/bin/env bash
echo "Member leave/join script triggered" >> /var/log/serf.log
BACKEND_UNREGISTERED=false
# We iterate over stdin
while read -a values; do
# We extract the hostname, the ip, the role of each line and the tags
HOSTNAME=${values[0]}
HOSTIP=${values[1]}
HOSTROLE=${values[2]}
HOSTTAGS=${values[3]}
# We only remove the backend nodes
if [[ "$HOSTROLE" == "backend" ]]; then
echo "Member $SERF_EVENT event received from: $HOSTNAME with role $HOSTROLE" >> /var/log/serf.log
# We simply remove the file that was used to track the registered node
rm /nodes/$HOSTNAME
# We have at least one new node that leave the cluster
BACKEND_UNREGISTERED=true
fi
done
# We only update the HAProxy configuration if we have at least a backend that
# left the cluster. The process to generate the HAProxy configuration is the
# same than for the member-join script.
if [[ "$BACKEND_UNREGISTERED" = true ]]; then
# To build the collection of nodes
HOSTS=""
# We iterate over each backend node registered
for hostfile in $(ls /nodes); do
# We convert the content of the backend node file to a JSON format: { "host": "<hostname>", "ip": "<ip address>" }
CURRENT_HOST=`cat /nodes/$hostfile | awk '{ print "{\"host\":\"" $1 "\",\"ip\":\"" $2 "\"}" }'`
# We concatenate each host
HOSTS="$HOSTS$CURRENT_HOST,"
done
# We process the template with handlebars. The sed command will simply remove the
# trailing comma from the hosts list.
handlebars --addresses "[$(echo $HOSTS | sed s/,$//)]" < /config/haproxy.cfg.hb > /usr/local/etc/haproxy/haproxy.cfg
# TODO: [CFG] Add the command to restart HAProxy
s6-svc -h /var/run/s6/services/ha
fi
|
Java
|
UTF-8
| 3,527
| 2.671875
| 3
|
[] |
no_license
|
public class mainHtmlPrint
{
String htmlOneTestServ = "<html>\n"+"<head>\n"+"<title>\n"+"Das Schwarze Hahnchen\n"+"</title>\n"+"<style>\n"+
"\n"+"td{\n"+"font-style: italic;\n"+"position: relative;\n"+"text-align: center;\n"+"}\n"+"\n"
+"body {\n"+"background-color: #93B874;\n"+"}\n"+"\n"+"pre {\n"+"background-color: rgb(200,0,0);\n"+
"text-align: center;\n"+"\n"+"}\n"+"\n"+"li{\n"+"\n"+"height:20px;\n"+"width:320px;\n"+"display:block;\n"+
"float:left;\n"+"text-align: center;\n"+"background-color: rgb(108,135,86);\n"+"color: red;\n"+"}\n"+"";
String htmlTwoTestServ = "</style>\n"+"</head>\n"+"\n"+"<!-- Creates the first table (Includes the restaurant name, and logo in the border -->\n"+
"\n"+"<table width='80%' align=\"center\" style=\"border:5px double black;\">\n"+"<tr>\n"+"<td>\n"+
"<img style=\"width:150px;height:128px;\" src=\"logo.png\" alt=\"logo\"></td>\n"+"<td>\n"+
"<h1 style =\"font-size: 450%\">Das Schwarze Hahnchen</h1>\n"+"</td>\n"+"</tr>\n"+"\n"+"</table>\n"+"\n"+"<hr>\n"+
"\n"+"\n"+"<div id=\"footer\">\n"+"<nav>\n"+"<ul>\n"+
"<li><a href=\"home.html\">Home</a></li><li><form action=\"menu.html\"><input type =\"submit\" value=\"Menu\"/></form></li><li><form action=\"order.html\"><input type=\"submit\" value=\"Order\"/></form></li><li><a href=\"contact.html\">Contact</a></li><li><a href=\"login.html\">Login</a></li>\n"+
"</ul>\n"+"</nav>\n"+"<br>\n"+"</div>\n"+"<br>\n"+"<hr>";
String htmlOneMenuLoad ="<html>\n"+"<head>\n"+"<title>\n"+"Das Schwarze Hahnchen\n"+"</title>\n"+"<style>\n"+
"\n"+"td{\n"+"font-style: italic;\n"+"position: relative;\n"+"text-align: center;\n"+"}\n"+
"\n"+"body {\n"+"background-color: #93B874;\n"+"}\n"+"\n"+"pre {\n"+"background-color: rgb(200,0,0);\n"+
"text-align: center;\n"+"\n"+"}\n"+"\n"+"li{\n"+"\n"+"height:20px;\n"+"width:320px;\n"+
"display:block;\n"+"float:left;\n"+"text-align: center;\n"+"background-color: rgb(108,135,86);\n"+
"color: red;\n"+"}\n"+"";
String htmlTwoMenuLoad = "</style>\n"+"</head>\n"+"\n"+"<!-- Creates the first table (Includes the restaurant name, and logo in the border -->\n"+
"\n"+"<table width='80%' align=\"center\" style=\"border:5px double black;\">\n"+"<tr>\n"+"<td>\n"+
"<img style=\"width:150px;height:128px;\" src=\"logo.png\" alt=\"logo\"></td>\n"+"<td>\n"+"<h1 style =\"font-size: 450%\">Das Schwarze Hahnchen</h1>\n"+"</td>\n" +
"</tr>\n"+"\n"+"</table>\n"+"\n"+"<hr>\n"+"\n"+"\n"+"<div id=\"footer\">\n"+"<nav>\n"+"<ul>\n"+
"<li><a href=\"home.html\">Home</a></li><li><form action=\"menu.html\"><input type =\"submit\" value=\"Menu\"/></form></li><li><form action=\"order.html\"><input type=\"submit\" value=\"Order\"/></form></li><li><a href=\"contact.html\">Contact</a></li><li><a href=\"login.html\">Login</a></li>\n" +
"</ul>\n"+"</nav>\n"+"<br>\n"+"</div>\n"+"<br>\n"+"<hr>";
public String htmlReturn()
{
return htmlOneTestServ;
}
public String secondHtmlReturn()
{
return htmlTwoTestServ;
}
public String htmlMenuLoadOne()
{
return htmlOneMenuLoad;
}
public String htmlMenuLoadTwo()
{
return htmlTwoMenuLoad;
}
}
|
C++
|
UTF-8
| 3,019
| 3.328125
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
#include "datamanipulation.h"
template <class INPUT, class OUTPUT>
void Convert_2(const std::string & s_input, const std::string & s_output)
{
std::vector<INPUT > vec_in = read_vector<INPUT>(s_input);
std::vector<OUTPUT> vec_out;
for (const auto& elem : vec_in)
vec_out.push_back(static_cast<OUTPUT>(elem));
write_to_file(s_output, vec_out);
}
template <class INPUT>
void Convert_1(const std::string & s_input, const std::string & s_output)
{
std::string ending_output = s_output.substr(s_output.rfind(".") + 1, s_output.length());
switch (Ending_to_DataType(ending_output))
{
//case DataType::Old: return Convert_2<INPUT, CDataset_Old >(s_input, s_output);
case DataType::Position_Score: return Convert_2<INPUT, CDataset_Position_Score >(s_input, s_output);
case DataType::Position_Score_PV: return Convert_2<INPUT, CDataset_Position_Score_PV >(s_input, s_output);
case DataType::Position_FullScore: return Convert_2<INPUT, CDataset_Position_FullScore>(s_input, s_output);
case DataType::Edax: return Convert_2<INPUT, CDataset_Edax >(s_input, s_output);
//case DataType::Position: return Convert_2<INPUT, CPosition >(s_input, s_output);
//case DataType::PositionScore: return Convert_2<INPUT, CPositionScore >(s_input, s_output);
}
}
void Convert(const std::string & s_input, const std::string & s_output)
{
std::string ending_input = s_input.substr(s_input.rfind(".") + 1, s_input.length());
switch (Ending_to_DataType(ending_input))
{
case DataType::Position_Score: return Convert_1<CDataset_Position_Score >(s_input, s_output);
case DataType::Position_Score_PV: return Convert_1<CDataset_Position_Score_PV >(s_input, s_output);
case DataType::Position_FullScore: return Convert_1<CDataset_Position_FullScore>(s_input, s_output);
case DataType::Edax: return Convert_1<CDataset_Edax >(s_input, s_output);
//case DataType::Position: return Convert_1<CPosition >(s_input, s_output);
//case DataType::PositionScore: return Convert_1<CPositionScore >(s_input, s_output);
}
}
int main(int argc, char* argv[])
{
bool b_s_input = false;
bool b_s_output = false;
std::string s_input;
std::string s_output;
for (int i = 0; i < argc; ++i)
{
if (std::string(argv[i]) == "-i"){
s_input = std::string(argv[++i]);
b_s_input = true;
}
else if (std::string(argv[i]) == "-o"){
s_output = std::string(argv[++i]);
b_s_output = true;
}
else if (std::string(argv[i]) == "-h")
std::cout << "Convertes a file from one type to an other." << std::endl <<
"Arguments:" << std::endl <<
"-i\tInput filename." << std::endl <<
"-o\tOutput filename." << std::endl <<
"-h\tDisplays help." << std::endl;
}
if (b_s_input && b_s_output)
Convert(s_input, s_output);
else
std::cerr << "Not enough parameters provided." << std::endl;
return 0;
}
|
Python
|
UTF-8
| 4,158
| 3.03125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
"""Tests for the Frank-Wolfe algorithm."""
import numpy as np
import pytest
from scipy import optimize
import copt as cp
np.random.seed(0)
n_samples, n_features = 20, 16
A = np.random.randn(n_samples, n_features)
w = np.random.randn(n_features)
b = A.dot(w) + np.random.randn(n_samples)
# we will use a logistic loss, which can't have values
# greater than 1
b = np.abs(b / np.max(np.abs(b)))
LOSS_FUNCS = [cp.loss.LogLoss, cp.loss.SquareLoss]
def test_fw_api():
"""Check that FW takes the right arguments and raises the right exceptions."""
# test that the algorithm does not fail if x0
# is a tuple
f = cp.loss.LogLoss(A, b, 1.0 / n_samples)
cb = cp.utils.Trace(f)
alpha = 1.0
l1ball = cp.constraint.L1Ball(alpha)
cp.minimize_frank_wolfe(
f.f_grad,
[0] * n_features,
l1ball.lmo,
tol=0,
lipschitz=f.lipschitz,
callback=cb,
)
# check that we riase an exception when the DR step-size is used
# but no lipschitz constant is given
with pytest.raises(ValueError):
cp.minimize_frank_wolfe(f.f_grad, [0] * n_features, l1ball.lmo, step="DR")
@pytest.mark.parametrize("alpha", [0.1, 1.0, 10.0, 100.0])
@pytest.mark.parametrize("loss_grad", LOSS_FUNCS)
def test_fw_l1(loss_grad, alpha):
"""Test result of FW algorithm with L1 constraint."""
f = loss_grad(A, b, 1.0 / n_samples)
cb = cp.utils.Trace(f)
l1ball = cp.constraint.L1Ball(alpha)
opt = cp.minimize_frank_wolfe(
f.f_grad,
np.zeros(n_features),
l1ball.lmo,
tol=1e-3,
lipschitz=f.lipschitz,
callback=cb,
)
assert np.isfinite(opt.x).sum() == n_features
ss = 1 / f.lipschitz
grad = f.f_grad(opt.x)[1]
grad_map = (opt.x - l1ball.prox(opt.x - ss * grad, ss)) / ss
assert np.linalg.norm(grad_map) < 0.3
def test_callback():
"""Make sure that the algorithm exists when the callback returns False."""
def cb(_):
return False
l1ball = cp.constraint.L1Ball(1)
f = cp.loss.SquareLoss(A, b)
opt = cp.minimize_frank_wolfe(f.f_grad, np.zeros(n_features), l1ball.lmo, callback=cb)
assert opt.nit < 2
def exact_line_search(kw):
def f_on_line(gamma):
return kw["func_and_grad"](kw["x"] + gamma * kw["update_direction"])[0]
line_sol = optimize.minimize_scalar(f_on_line, method='bounded', bounds=[0, kw["max_step_size"]])
return line_sol.x
@pytest.mark.parametrize("alpha", [0.1, 1.0, 10.0, 100.0])
@pytest.mark.parametrize("obj", LOSS_FUNCS)
@pytest.mark.parametrize("step", ["DR", "backtracking", "sublinear", exact_line_search])
def test_fw_backtrack(obj, step, alpha):
"""Test FW with different options of the line-search strategy."""
f = obj(A, b, 1.0 / n_samples)
traceball = cp.constraint.TraceBall(alpha, (4, 4))
opt = cp.minimize_frank_wolfe(
f.f_grad,
np.zeros(n_features),
traceball.lmo,
tol=0,
lipschitz=f.lipschitz,
step=step,
max_iter=1000,
)
assert np.isfinite(opt.x).sum() == n_features
ss = 1 / f.lipschitz
grad = f.f_grad(opt.x)[1]
# this is the proximal mapping, zero at optimum
grad_map = (opt.x - traceball.prox(opt.x - ss * grad, ss)) / ss
assert np.linalg.norm(grad_map) < 0.4
@pytest.mark.parametrize("alpha", [0.1, 1.0, 10.0, 100.0])
@pytest.mark.parametrize("obj", LOSS_FUNCS)
@pytest.mark.parametrize("step", ["DR", "backtracking", exact_line_search])
def test_pairwise_fw(obj, step, alpha):
"""Test the Pairwise FW method."""
f = obj(A, b, 1.0 / n_samples)
l1ball = cp.constraint.L1Ball(alpha)
x0 = np.zeros(A.shape[1])
x0[0] = alpha
cb = cp.utils.Trace(f)
opt = cp.minimize_frank_wolfe(
f.f_grad, x0, l1ball.lmo_pairwise, x0_rep=(1., 0),
step=step, lipschitz=f.lipschitz, callback=cb,
variant='pairwise'
)
assert np.isfinite(opt.x).sum() == n_features
ss = 1 / f.lipschitz
grad = f.f_grad(opt.x)[1]
# this is the proximal mapping, zero at optimum
grad_map = (opt.x - l1ball.prox(opt.x - ss * grad, ss)) / ss
assert np.linalg.norm(grad_map) < 0.2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.