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
|
|---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 951
| 2.484375
| 2
|
[] |
no_license
|
package com.example.home.myapplication.vo;
/**
* 浏览记录
*
* @author liu
*
*/
public class ProdcutHistory extends ProductListVo implements Comparable<ProdcutHistory>{
/** 浏览时间 */
private long time;
public ProdcutHistory() {
}
public ProdcutHistory(int id, String name, String pic, double marketprice, double price, int comment_count,
long time) {
super(id, name, pic, marketprice, price, comment_count);
this.time = time;
}
public ProdcutHistory(ProductListVo productListVo) {
super(productListVo.getId(), productListVo.getName(), productListVo.getPic(), productListVo.getMarketprice(),
productListVo.getPrice(), productListVo.getComment_count());
this.time = System.currentTimeMillis();
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
@Override
public int compareTo(ProdcutHistory another) {
return time > another.time ? 1 : -1;
}
}
|
Java
|
UTF-8
| 5,375
| 2.28125
| 2
|
[] |
no_license
|
package org.qcri.micromappers.nlp.service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.log4j.Logger;
import org.deeplearning4j.models.embeddings.loader.WordVectorSerializer;
import org.deeplearning4j.models.embeddings.wordvectors.WordVectors;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.buffer.util.DataTypeUtil;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.accum.distances.CosineSimilarity;
import org.nd4j.linalg.factory.Nd4j;
import org.qcri.micromappers.nlp.model.TextDisambiguitorOutput;
import org.qcri.micromappers.nlp.utility.Twokenize;
import org.qcri.micromappers.nlp.utility.configurator.MicromappersConfigurationProperty;
import org.qcri.micromappers.nlp.utility.configurator.MicromappersConfigurator;
/**
* @author Kushal
*
*/
public class TextDisambiguitor {
private static Logger logger = Logger.getLogger(TextDisambiguitor.class);
private static WordVectors model;
private INDArray firstLabelCentroid;
private INDArray secondLabelCentroid;
private int ndim = 200;
private String DISAMBIGUATE_WORD;
private static MicromappersConfigurator configProperties = MicromappersConfigurator.getInstance();
static{
String modelFile = Paths.get(configProperties.getProperty(MicromappersConfigurationProperty.WORD_VECTOR_MODEL_FILE_PATH)).toString();
try {
model = WordVectorSerializer.loadTxtVectors(new File(modelFile));
} catch (IOException e) {
logger.error("Exception in WORD_VECTOR_MODEL_FILE_PATH", e);
}
}
public TextDisambiguitor(String topic, String firstLabelTags, String secondLabelTags) {
try{
DataTypeUtil.setDTypeForContext(DataBuffer.Type.FLOAT);
DISAMBIGUATE_WORD = topic;
firstLabelCentroid = get_centroid_vector(firstLabelTags.trim().split("\\s*,\\s*"), ndim);
secondLabelCentroid = get_centroid_vector(secondLabelTags.trim().split("\\s*,\\s*"), ndim);
}
catch (Exception e){
logger.error("Exception whilie finding the centroid ", e);
}
}
private INDArray get_centroid_vector(String[] list_of_words, int ndim) {
INDArray vector = Nd4j.zeros(1, ndim);
for(String word : list_of_words) {
try{
word = word.replaceAll("[^A-Za-z0-9]","");
vector = vector.addi(model.getWordVectorMatrix(word));
}catch (Exception e) {
logger.error("Exception while processing the label tags", e);
}
}
vector = vector.divi(list_of_words.length);
return vector;
}
public TextDisambiguitorOutput processText(String text){
TextDisambiguitorOutput output = null;
String originalText = text;
text = text.toLowerCase();
try{
Twokenize twokenize = new Twokenize();
if(text.contains(DISAMBIGUATE_WORD)){
List<String> token_list = twokenize.tokenizeRawTweetText(text);
output = this.findAvgSimilarity(originalText, token_list);
}else{
output = new TextDisambiguitorOutput(0.0, 0.0);
}
}catch (Exception e) {
logger.error("Exception while processing the text", e);
}
finally {
return output;
}
}
private TextDisambiguitorOutput findAvgSimilarity(String item, List<String> token_list){
List<String> context_words = this.get_context_words(token_list);
double avg_first_label_centroid = 0;
double avg_second_label_centroid = 0;
try{
avg_first_label_centroid = getavgsimilarity_centroid(context_words.toArray(), firstLabelCentroid);
avg_second_label_centroid = getavgsimilarity_centroid(context_words.toArray(), secondLabelCentroid);
}catch (Exception e) {
logger.error("Exception while calculating avg similarity");
}finally {
return new TextDisambiguitorOutput(avg_first_label_centroid, avg_second_label_centroid);
}
}
private double getavgsimilarity_centroid(Object[] context_words, INDArray centroid){
double sim = 0.0;
int total_pass = 0;
for(Object o : context_words){
String word = o.toString();
for(int i = 0; i < word.length(); i++){
String word_to_search = word.substring(0, word.length() - i);
try{
INDArray vector = model.getWordVectorMatrix(word_to_search);
double ret2 = Nd4j.getExecutioner().execAndReturn(new CosineSimilarity(vector, centroid)).getFinalResult().doubleValue();
double simx = ret2 ;
sim = sim + simx;
total_pass = total_pass + 1 ;
}
catch (Exception e){
continue;
}
}
}
return sim/(total_pass+0.00001);
}
private List<String> get_context_words(List<String> token_list){
List<String> context_words = new ArrayList<String>();
context_words = token_list.stream()
.filter(item -> !item.equalsIgnoreCase(DISAMBIGUATE_WORD))
.collect(Collectors.toList());
return context_words;
}
}
|
C#
|
UTF-8
| 1,061
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
using Newtonsoft.Json;
namespace RiotSharp.Endpoints.StaticDataEndpoint.Champion
{
/// <summary>
/// Basic information for a champion (Static API).
/// </summary>
public class InfoStatic
{
internal InfoStatic() { }
/// <summary>
/// Number between 1 and 10 representing the attack power of a champion.
/// </summary>
[JsonProperty("attack")]
public int Attack { get; set; }
/// <summary>
/// Number between 1 and 10 representing the defense power of a champion.
/// </summary>
[JsonProperty("defense")]
public int Defense { get; set; }
/// <summary>
/// Number between 1 and 10 representing the difficulty of a champion.
/// </summary>
[JsonProperty("difficulty")]
public int Difficulty { get; set; }
/// <summary>
/// Number between 1 and 10 representing the magic power of a champion.
/// </summary>
[JsonProperty("magic")]
public int Magic { get; set; }
}
}
|
Python
|
UTF-8
| 179
| 2.890625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:
s = 'Whereof one cannot speak, thereof one must be silent'
print s.upper()
|
Java
|
UTF-8
| 312
| 3.34375
| 3
|
[] |
no_license
|
package week6;
public class Engineer extends Person{
String genre;
public Engineer(String name, int age, String gender){
this.age = age;
this.gender = gender;
this.name = name;
}
public void doJob(){
System.out.println(name+" is " +genre);
}
}
|
C#
|
UTF-8
| 2,393
| 2.796875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _30._10._2019
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
toolStripLabelquantitychar.Text = textBox1.Text.Length.ToString() + " / " + numericUpDown1.Maximum + " Symbols";
textBox1.MaxLength = (int)numericUpDown1.Value;
//textBox1.BackColor = Color.Green;
this.BackColor = textBox1.BackColor;
numericUpDown1.BackColor = textBox1.BackColor;
}
private void toolStripDropDownButton1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.MaxLength = (int)numericUpDown1.Value;
toolStripLabelquantitychar.Text = textBox1.Text.Length.ToString()+" / "+ (int)numericUpDown1.Value + " Symbols";
Regex digits = new Regex(@"[0-9]");
Regex letters = new Regex(@"[a-z|A-Z]");
Regex words = new Regex(@"[a-z,A-Z]+");
MatchCollection matches = digits.Matches(textBox1.Text);
toolStripLabeldigit.Text = "Digit = " + matches.Count;
matches = letters.Matches(textBox1.Text);
toolStripLabelletter.Text = "Laters = " + matches.Count;
matches = words.Matches(textBox1.Text);
toolStripLabelword.Text = "Word = " +matches.Count;
toolStripProgressBar1.Maximum= (int)numericUpDown1.Value;
toolStripProgressBar1.Value = textBox1.Text.Length;
}
private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
textBox1.MaxLength = (int)numericUpDown1.Value;
if(textBox1.TextLength> (int)numericUpDown1.Value)
textBox1.Text=textBox1.Text.Remove((int)numericUpDown1.Value);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void toolStripLabelquantitychar_Click(object sender, EventArgs e)
{
}
}
}
|
Markdown
|
UTF-8
| 928
| 2.75
| 3
|
[] |
no_license
|
<h1 align="center">Footstep-Lookup</h1>
<p align="center"><img src="https://image.freepik.com/free-vector/customer-using-mobile-app-tracking-order-delivery_74855-5229.jpg" /></p>
This is an activity tracking application. It lets you to see the name of the window opened, the total time for which the user was on the window. If the window is Google Chrome (or any other browser) then it will even show the URL on which the user was. All these data is stored in a JSON file(footsteps.json).
### Setting Up in Local environment
1. Clone this repository - `https://github.com/pranjals149/Footstep-Lookup.git`
2. Move into the project's directory - `cd Footstep-Lookup`
3. Install the required dependencies - `npm i`
4. Now, open the terminal and run - `npm link`
5. Now, just type `flookup` for starting the application and tracking your activity.
### Screenshot
<img src='./Footstep-Lookup.gif' />
**Hope you like it !!** 😄
|
Java
|
UTF-8
| 4,018
| 2.046875
| 2
|
[] |
no_license
|
package com.example.poliakov.barcodescanner;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* create an instance of this fragment.
*/
public class SelectFragment extends Fragment implements OnClickListener {
public static final String IMPORT_FRAGMENT_TAG = "fragment:import";
// private OnFragmentInteractionListener mListener;
public SelectFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Select");
View RootView = inflater.inflate(R.layout.fragment_select, container, false);
FloatingActionButton importButton = (FloatingActionButton) RootView.findViewById(R.id.import_button);
importButton.setOnClickListener(this);
DaoSession daoSession = ((App) getActivity().getApplication()).getDaoSession();
BarcodeDatabaseDao BarcodeDatabaseDao = daoSession.getBarcodeDatabaseDao();
List barcodeDatabaseList = BarcodeDatabaseDao.loadAll();
RecyclerView recyclerView = (RecyclerView) RootView.findViewById(R.id.barcode_database_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
BarcodeDatabaseAdapter adapter = new BarcodeDatabaseAdapter(barcodeDatabaseList, new BarcodeDatabaseAdapter.OnItemClickListener() {
@Override public void onItemClick(BarcodeDatabase item) {
Fragment barcodeDatabaseFragment = BarcodeDatabaseFragment.newInstance(item.getId());
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContent, barcodeDatabaseFragment, BarcodeDatabaseFragment.BARCODE_DATABASE_FRAGMENT_TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
recyclerView.setAdapter(adapter);
//Add divider between items of RecyclerView
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
recyclerView.addItemDecoration(dividerItemDecoration);
return RootView;
}
@Override
public void onClick(View view) {
final SelectFragment fragment = this;
switch (view.getId()) {
case R.id.import_button:
Fragment importFragment = new ImportFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContent, importFragment, IMPORT_FRAGMENT_TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}
|
Java
|
UTF-8
| 192
| 1.734375
| 2
|
[] |
no_license
|
/**
*
*/
package searchaction;
import java.io.File;
/**
* @author jzero2
*
*/
public interface FileAction {
public int doAction(File sourceFile, String[] matchGroup);
}
|
Markdown
|
UTF-8
| 1,131
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
# diff-generator
A Django REST based API to compare a list of filepaths against two different commits.
Commits can be specified in the form of branches, tags or specific commit hashes.
### Prerequisites
Ensure you have pip and sqlite installed on your machine
### Installation
```bash
git clone git@bitbucket.org:3yourmind/diff_generator.git
cd diff_generator
pip install -r requirements.txt
python manage.py migrate
python manage.py createsuperuser # Follow instructions
python manage.py runserver
```
add a `settings_local.py` files in `diff_generator/` and add `REPO_PATH=path/to/repo` replacing the path with your
own relative path to a repo root.
### Usage
Create some FilePath objects in the admin panel `localhost:8000/admin` using the superuser you created - these will be the filepaths
you wish the diff command to display an output for when comparing between commits.
### Deployment with Docker
`docker build -t diff_generator .`
`docker run -it -e DJANGO_DEBUG=<0|1> -v <REPO_PATH>:/app/repo -p 80:8000 diff_generator`
The source can also be mounted into `/app/src` to avoid rebuilding the image on every code change.
|
Markdown
|
UTF-8
| 11,793
| 2.53125
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: 将自定义任务窗格与功能区按钮同步
ms.date: 02/02/2017
ms.topic: conceptual
dev_langs:
- VB
- CSharp
helpviewer_keywords:
- custom task panes [Office development in Visual Studio], showing and hiding
- showing custom task panes
- Ribbon [Office development in Visual Studio], custom task panes
- toggle buttons [Office development in Visual Studio]
- custom task panes [Office development in Visual Studio], synchronizing with Ribbon button
- user interfaces [Office development in Visual Studio], custom task panes
- synchronization [Office development in Visual Studio], custom task panes
- task panes [Office development in Visual Studio], showing and hiding
- custom task panes [Office development in Visual Studio], creating
- hiding custom task panes
- task panes [Office development in Visual Studio], creating
- task panes [Office development in Visual Studio], synchronizing with Ribbon button
author: John-Hart
ms.author: johnhart
manager: jillfra
ms.workload:
- office
ms.openlocfilehash: ad910f94c6b6a4345f6973e84e02c85d4fe1f0e4
ms.sourcegitcommit: 7eb2fb21805d92f085126f3a820ac274f2216b4e
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 06/22/2019
ms.locfileid: "67328339"
---
# <a name="walkthrough-synchronize-a-custom-task-pane-with-a-ribbon-button"></a>演练:将自定义任务窗格与功能区按钮同步
本演练演示如何创建用户可以隐藏或通过单击功能区上的切换按钮显示的自定义任务窗格。 应始终创建一个可供用户单击以显示或隐藏你的自定义任务窗格的用户界面 (UI) 元素,如按钮,因为 Microsoft Office 应用程序不提供用户用于显示或隐藏自定义任务窗格的默认方式。
[!INCLUDE[appliesto_olkallapp](../vsto/includes/appliesto-olkallapp-md.md)]
虽然本演练具体使用的是 Excel,但其中所阐释的概念同样适用于上面所列的应用程序。
本演练阐释了以下任务:
- 设计自定义任务窗格的 UI。
- 向功能区添加切换按钮。
- 使用自定义任务窗格同步切换按钮。
> [!NOTE]
> 以下说明中的某些 Visual Studio 用户界面元素在计算机上出现的名称或位置可能会不同。 这些元素取决于你所使用的 Visual Studio 版本和你所使用的设置。 有关详细信息,请参阅[个性化设置 Visual Studio IDE](../ide/personalizing-the-visual-studio-ide.md)。
## <a name="prerequisites"></a>系统必备
你需要以下组件来完成本演练:
- [!INCLUDE[vsto_vsprereq](../vsto/includes/vsto-vsprereq-md.md)]
- Microsoft Excel 或 Microsoft [!INCLUDE[Excel_15_short](../vsto/includes/excel-15-short-md.md)]。
## <a name="create-the-add-in-project"></a>创建外接程序项目
在此步骤中,将为 Excel 创建的 VSTO 外接程序项目。
### <a name="to-create-a-new-project"></a>创建新项目
1. 使用 Excel 外接程序项目模板,创建一个名为 **SynchronizeTaskPaneAndRibbon**的 Excel 外接程序项目。 有关详细信息,请参阅[如何:在 Visual Studio 中创建 Office 项目](../vsto/how-to-create-office-projects-in-visual-studio.md)。
[!INCLUDE[vsprvs](../sharepoint/includes/vsprvs-md.md)] 打开 **ThisAddIn.cs** 或 **ThisAddIn.vb** 代码文件,并将 **SynchronizeTaskPaneAndRibbon** 项目添加到 **“解决方案资源管理器”** 。
## <a name="add-a-toggle-button-to-the-ribbon"></a>向功能区添加切换按钮
Office 应用程序的设计准则之一是:用户应始终能控制 Office 应用程序 UI。 若要让用户可以控制自定义任务窗格,可以添加一个可显示和隐藏任务窗格的功能区切换按钮。 若要创建一个切换按钮,则将 **“功能区(可视化设计器)”** 项添加到项目。 设计器可帮助你添加和放置控件、设置控件属性以及处理控件事件。 有关详细信息,请参阅[功能区设计器](../vsto/ribbon-designer.md)。
### <a name="to-add-a-toggle-button-to-the-ribbon"></a>若要添加到功能区切换按钮
1. 在 **“项目”** 菜单上,单击 **“添加新项”** 。
2. 在 **“添加新项”** 对话框中,选择 **“功能区(可视化设计器)”** 。
3. 将新功能区更名为 **ManageTaskPaneRibbon**,然后单击“添加” 。
**ManageTaskPaneRibbon.cs** 或 **ManageTaskPaneRibbon.vb** 文件将在功能区设计器中打开,并显示一个默认选项卡和组。
4. 在功能区设计器中,单击“Group1” 。
5. 在“属性” 窗口中,将“Label”属性 设置为 **Task Pane Manager**。
6. 从“工具箱” 的“Office 功能区控件” 选项卡中,将 **ToggleButton** 拖到“Task Pane Manager” 组。
7. 单击“toggleButton1” 。
8. 在“属性” 窗口中,将“Label”属性 设置为 **Show Task Pane**。
## <a name="design-the-user-interface-of-the-custom-task-pane"></a>设计自定义任务窗格的用户界面
没有针对自定义任务窗格的可视化设计器,但可以设计具有所需布局的用户控件。 稍后在本演练中,你将向自定义任务窗格添加用户控件。
### <a name="to-design-the-user-interface-of-the-custom-task-pane"></a>若要设计自定义任务窗格的用户界面
1. 在 **“项目”** 菜单上,单击 **“添加用户控件”** 。
2. 在“添加新项” 对话框中,将用户控件的名称更改为 **TaskPaneControl**,然后单击“添加” 。
用户控件将在设计器中打开。
3. 从“工具箱” 的“公共控件” 选项卡中,将 **TextBox** 控件拖到用户控件中。
## <a name="create-the-custom-task-pane"></a>创建自定义任务窗格
若要在 VSTO 外接程序启动时创建自定义任务窗格,请将用户控件添加到 VSTO 外接程序的 <xref:Microsoft.Office.Tools.AddIn.Startup> 事件处理程序中的任务窗格中。 默认情况下,自定义任务窗格将不可见。 稍后在本演练中,您将添加代码,将显示或隐藏任务窗格中,当用户单击切换按钮添加到功能区。
### <a name="to-create-the-custom-task-pane"></a>若要创建自定义任务窗格
1. 在 **“解决方案资源管理器”** 中,展开 **“Excel”** 。
2. 右键单击 **ThisAddIn.cs** 或 **ThisAddIn.vb** ,然后单击“查看代码” 。
3. 向 `ThisAddIn` 类添加下面的代码。 此代码将 `TaskPaneControl` 的实例声明为 `ThisAddIn`的成员。
[!code-csharp[Trin_TaskPaneRibbonSynchronize#1](../vsto/codesnippet/CSharp/Trin_TaskPaneRibbonSynchronize/ThisAddIn.cs#1)]
[!code-vb[Trin_TaskPaneRibbonSynchronize#1](../vsto/codesnippet/VisualBasic/Trin_TaskPaneRibbonSynchronize/ThisAddIn.vb#1)]
4. 将 `ThisAddIn_Startup` 事件处理程序替换为以下代码。 此代码向 `TaskPaneControl` 字段添加 `CustomTaskPanes` 对象,但它不显示自定义任务窗格(默认情况下, <xref:Microsoft.Office.Tools.CustomTaskPane.Visible%2A> 类的 <xref:Microsoft.Office.Tools.CustomTaskPane> 属性是 **false**)。 Visual C# 代码还会将一个事件处理程序附加到 <xref:Microsoft.Office.Tools.CustomTaskPane.VisibleChanged> 事件。
[!code-csharp[Trin_TaskPaneRibbonSynchronize#2](../vsto/codesnippet/CSharp/Trin_TaskPaneRibbonSynchronize/ThisAddIn.cs#2)]
[!code-vb[Trin_TaskPaneRibbonSynchronize#2](../vsto/codesnippet/VisualBasic/Trin_TaskPaneRibbonSynchronize/ThisAddIn.vb#2)]
5. 将以下方法添加到 `ThisAddIn` 类。 此方法处理 <xref:Microsoft.Office.Tools.CustomTaskPane.VisibleChanged> 事件。 当用户通过单击 **“关闭”** 按钮 (X) 来关闭任务窗格时,此方法将更新功能区上切换按钮的状态。
[!code-csharp[Trin_TaskPaneRibbonSynchronize#3](../vsto/codesnippet/CSharp/Trin_TaskPaneRibbonSynchronize/ThisAddIn.cs#3)]
[!code-vb[Trin_TaskPaneRibbonSynchronize#3](../vsto/codesnippet/VisualBasic/Trin_TaskPaneRibbonSynchronize/ThisAddIn.vb#3)]
6. 向 `ThisAddIn` 类添加以下属性。 此属性对其他类公开私有 `myCustomTaskPane1` 对象。 稍后在本演练中,你将向使用此属性的 `MyRibbon` 类添加代码。
[!code-csharp[Trin_TaskPaneRibbonSynchronize#4](../vsto/codesnippet/CSharp/Trin_TaskPaneRibbonSynchronize/ThisAddIn.cs#4)]
[!code-vb[Trin_TaskPaneRibbonSynchronize#4](../vsto/codesnippet/VisualBasic/Trin_TaskPaneRibbonSynchronize/ThisAddIn.vb#4)]
## <a name="hide-and-show-the-custom-task-pane-by-using-the-toggle-button"></a>隐藏和显示通过使用切换按钮的自定义任务窗格
最后一步是添加可在用户单击功能区上的切换按钮时显示或隐藏自定义任务窗格的代码。
### <a name="to-display-and-hide-the-custom-task-pane-by-using-the-toggle-button"></a>通过使用切换按钮显示和隐藏自定义任务窗格
1. 在功能区设计器中,双击“显示任务窗格” 切换按钮。
Visual Studio 会自动生成名为 `toggleButton1_Click`的事件处理程序,它将处理切换按钮的 <xref:Microsoft.Office.Tools.Ribbon.RibbonToggleButton.Click> 事件。 Visual Studio 还会打开代码编辑器中的 *MyRibbon.cs* 或 *MyRibbon.vb* 文件。
2. 将 `toggleButton1_Click` 事件处理程序替换为以下代码。 当用户单击切换按钮时,此代码显示或隐藏自定义任务窗格,具体取决于是按下还是未按下切换按钮。
[!code-vb[Trin_TaskPaneRibbonSynchronize#5](../vsto/codesnippet/VisualBasic/Trin_TaskPaneRibbonSynchronize/ManageTaskPaneRibbon.vb#5)]
[!code-csharp[Trin_TaskPaneRibbonSynchronize#5](../vsto/codesnippet/CSharp/Trin_TaskPaneRibbonSynchronize/ManageTaskPaneRibbon.cs#5)]
## <a name="test-the-add-in"></a>测试的外接程序
运行项目时,Excel 会打开,但不显示自定义任务窗格。 单击要测试的代码的功能区上的切换按钮。
### <a name="to-test-your-vsto-add-in"></a>测试 VSTO 外接程序
1. 按**F5**运行你的项目。
确认 Excel 打开,并**外接程序**选项卡显示在功能区。
2. 单击**外接程序**功能区上的选项卡。
3. 在 **“任务窗格管理器”** 组中,单击 **“显示任务窗格”** 切换按钮。
验证当点击切换按钮时,任务窗格交替显示和隐藏。
4. 当任务窗格可见时,单击任务窗格一角的 **“关闭”** 按钮 (X)。
验证切换按钮显示为未按下。
## <a name="next-steps"></a>后续步骤
可从以下主题了解有关如何创建自定义任务窗格的详细信息:
- 在 VSTO 外接程序中的其他应用程序中创建自定义任务窗格。 有关支持自定义任务窗格的应用程序的详细信息,请参阅[自定义任务窗格](../vsto/custom-task-panes.md)。
- 从自定义任务窗格自动化应用程序。 有关详细信息,请参见[演练:自动执行应用程序从自定义任务窗格](../vsto/walkthrough-automating-an-application-from-a-custom-task-pane.md)。
- 为 Outlook 中打开的每封电子邮件创建自定义任务窗格。 有关详细信息,请参见[演练:在 Outlook 中显示的电子邮件消息的自定义任务窗格](../vsto/walkthrough-displaying-custom-task-panes-with-e-mail-messages-in-outlook.md)。
## <a name="see-also"></a>请参阅
- [自定义任务窗格](../vsto/custom-task-panes.md)
- [如何:向应用程序添加自定义任务窗格](../vsto/how-to-add-a-custom-task-pane-to-an-application.md)
- [演练:自动执行从自定义任务窗格应用程序](../vsto/walkthrough-automating-an-application-from-a-custom-task-pane.md)
- [演练:在 Outlook 中显示电子邮件消息的自定义任务的窗格](../vsto/walkthrough-displaying-custom-task-panes-with-e-mail-messages-in-outlook.md)
- [功能区概述](../vsto/ribbon-overview.md)
|
JavaScript
|
UTF-8
| 479
| 2.5625
| 3
|
[] |
no_license
|
//Dependencies
var mongoose = require('mongoose');
// Save a reference to the Schema constructor
var Schema = mongoose.Schema;
// Creating the note schema
var NoteSchema = new Schema({
username: {
type: String,
required: false
},
comment: {
type: String,
required: false
},
date: {
type: Date,
default: Date.now
}
});
//Create a model using Mongoose
var Note = mongoose.model('Note', NoteSchema);
//Export the note
module.exports = Note;
|
Java
|
UTF-8
| 2,001
| 2.421875
| 2
|
[
"ICU",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-jdom",
"MIT",
"MPL-1.1",
"JSON",
"LGPL-2.1-or-later",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
/**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mina.core.file;
import java.nio.channels.FileChannel;
/**
* Indicates the region of a file to be sent to the remote host.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public interface FileRegion {
/**
* The open <tt>FileChannel<tt> from which data will be read to send to
* remote host.
*
* @return An open <tt>FileChannel<tt>.
*/
FileChannel getFileChannel();
/**
* The current file position from which data will be read.
*
* @return The current file position.
*/
long getPosition();
/**
* Updates the current file position based on the specified amount. This
* increases the value returned by {@link #getPosition()} and
* {@link getWrittenBytes} by the given amount and decreases the value
* returned by {@link #getCount()} by the given {@code amount}.
*
* @param amount The new value for the file position.
*/
void update(long amount);
/**
* The number of bytes remaining to be written from the file to the remote
* host.
*
* @return The number of bytes remaining to be written.
*/
long getRemainingBytes();
/**
* The total number of bytes already written.
*
* @return The total number of bytes already written.
*/
long getWrittenBytes();
}
|
Python
|
UTF-8
| 1,853
| 3.125
| 3
|
[] |
no_license
|
import subprocess
from os import system
def setweb():
system("tput setaf 2")
print("\nApache websever has loaded properly")
system("tput setaf 7")
print("""Tell me from where you want to load the website :
1.download web page from github
2.copy local web page to the webserver
3.back
""")
choice= int(input("Enter your choice : "))
if choice==1:
url =input("Enter the github url: ")
name = input("Ener your github's project name: ")
ip= subprocess.getoutput(["hostname -I | awk '{print $1}'"])
system("clear")
subprocess.run(["yum","install","git","-y"])
system("git clone {0} /var/www/html/{1} ".format(url,name))
system("/usr/sbin/httpd -k restart")
system("tput setaf 2")
print("\nweb server started successfully !!")
system("tput setaf 1")
print("\nurl of webserver is : {0}/{1}/ ".format(ip,name))
system("tput setaf 2")
input("\nPress enter for continue...")
system("tput setaf 7")
elif choice==2:
location = input("Enter your website full local location that you want to deploy : ")
ip= subprocess.getoutput(["hostname -I | awk '{print $1}"])
system("sudo yes | cp {} /var/www/html/ ".format(location))
system("/usr/sbin/httpd -k restart")
system("tput setaf 2")
print(" web server started successfully !!")
system("tput setaf 1")
print("\nurl of webserver is : {0}/{1}/ ".format(ip,name))
system("tput setaf 2")
input("\nPress enter for continue...")
system("tput setaf 7")
def webserver():
try:
subprocess.run(["yum","install","httpd","-y"])
except Exception as e:
subprocess.run(["tput","setaf","1"])
print("Error")
print(e)
else:
setweb()
|
Java
|
UTF-8
| 465
| 1.960938
| 2
|
[] |
no_license
|
package pl.edu.wat.wcy.isi.siecsilowni.events;
import javafx.event.Event;
import javafx.event.EventType;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class SearchSubmitEvent extends Event {
public static final EventType<SearchSubmitEvent> SEARCH_SUBMIT_EVENT =
new EventType<>(Event.ANY, "SEARCH_SUBMIT_EVENT");
public SearchSubmitEvent() {
super(SEARCH_SUBMIT_EVENT);
}
}
|
JavaScript
|
UTF-8
| 633
| 3.328125
| 3
|
[] |
no_license
|
const Heap = require('./collections/heap');
const find_Kth_smallest = function (lists, k) {
let currPos = 0,
nextSmallNum = -1;
const minHeap = new Heap([], null, (a, b) => b[0] - a[0]);
lists.forEach((list, i) => {
minHeap.push([list.shift(), i]);
});
while (currPos < k && minHeap.length) {
nextSmallNum = minHeap.pop();
currPos++;
minHeap.push([lists[nextSmallNum[1]].shift(), nextSmallNum[1]]);
}
if (!minHeap.length && currPos < k) return -1;
return nextSmallNum[0];
};
console.log(
`Kth smallest number is: ${find_Kth_smallest(
[
[5, 8, 9],
[1, 7],
],
3
)}`
);
|
Java
|
UTF-8
| 430
| 2.15625
| 2
|
[] |
no_license
|
package com.hw.common.constant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
public class LocalCache {
public static Map map =new ConcurrentHashMap();
public static Object get(String key) throws ExecutionException {
return map.get(key);
}
public static void set(Object key, Object value) {
map.put(key, value);
}
}
|
Markdown
|
UTF-8
| 1,421
| 2.765625
| 3
|
[] |
no_license
|
# API Gateway
Suppose a company named XYZ developed the API for its internal purpose. There are two
ways in which it exposes that API for external use:
- Exposes it using authentication from known clients
- Exposes it as an API as a service
In the first case, this API is consumed by the other services inside the company. Since they
are internal, we don't restrict the access. But in the second case, since API details are given
to the outside world, we need a broker in between to check and validate the requests. This
broker is the API gateway. An API gateway is a broker that sits in between the client and
the server and forwards the request to the server on passing specific conditions.
Things apply to an API
- Authentication
- Loggin or requests and responses
Basically, an API getaway does these things:
- Logging
- Security
- Traffic control
- Transformations
# Implementing Kong (Using Docker)
Create three containers
- Kong database
- Go container
- Kong application
// create a container along with the user and databse name passed as variables to the container
docker run -d --name kong-database \
-p 5432:5432 \
-e "POSTGRES_USER=kong" \
-e "POSTGRES_DB=kong" \
postgres:latest
// apply migrations required by Kong
docker run --rm \
--link kong-database:kong-database \
-e "KONG_DATABASE=postgres" \
-e "KONG_PG_HOST=kong-database" \
kong:1.0.3 kong migrations bootstrap && kong migrations up \
|
Ruby
|
UTF-8
| 5,010
| 2.984375
| 3
|
[] |
no_license
|
class Passport
def self.from_string(string, field_level_validation: true)
new(string.split.map(&:to_field), field_value_validation: field_level_validation)
end
attr_reader :fields
def initialize(fields, field_value_validation:)
@fields = fields
@field_level_validation = field_value_validation
end
def valid?
return false unless keys_valid?
return false unless fields_valid? if perform_field_value_validation?
true
end
private
def fields_valid?
fields.all?(&:valid?)
end
def perform_field_value_validation?
@field_level_validation
end
def keys_valid?
present_keys = fields.map(&:code)
required_keys.all? { |key| key.in?(present_keys) }
end
def required_keys
Field.required_keys
end
end
class Field
def self.for(key, value)
descendants.detect(->{ self }) { |descendant| descendant.code == key }.new(value)
end
def self.required_keys
descendants.map(&:code)
end
def self.code
end
def code
self.class.code
end
def initialize(value)
@value = value
end
def valid?
true
end
end
def validate_field(code, &block)
new_field = Class.new(Field)
new_field.define_singleton_method(:code) { code }
new_field.define_method(:valid?) { instance_exec(@value, &block) }
end
validate_field('iyr') { |value| value.to_i.between?(2010, 2020) }
validate_field('byr') { |value| value.to_i.between?(1920, 2002) }
validate_field('eyr') { |value| value.to_i.between?(2020, 2030) }
validate_field('hgt') { |value| value.to_inches.between?(59, 76) }
validate_field('hcl') { |value| value =~ /\A#[0-9a-f]{6}\z/ }
validate_field('ecl') { |value| value.in?(%w(amb blu brn gry grn hzl oth)) }
validate_field('pid') { |value| value =~ /\A\d{9}\Z/ }
class String
def to_inches
if ends_with?('cm')
(to_i / (150.to_f/59)).floor
else
to_i
end
end
def to_field
Field.for(*split(':'))
end
end
class DayFourTest < Minitest::Test
def setup
skip
end
def test_passport_validates_required_fields
missing_fields = Passport.from_string('ecl:gry')
valid_passport = Passport.from_string('ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm')
refute missing_fields.valid?
assert valid_passport.valid?
end
def test_part_one
skip
result = input.map { |fields_string| Passport.from_string(fields_string, field_level_validation: false) }.count(&:valid?)
assert_equal 254, result
end
def test_birth_year_validation_on_passport
valid_passport = Passport.from_string('byr:1972 ecl:gry pid:860033327 eyr:2020 hcl:#fffffd iyr:2017 cid:147 hgt:183cm')
invalid_passport = Passport.from_string('byr:3000 ecl:gry pid:860033327 eyr:2020 hcl:#fffffd iyr:2017 cid:147 hgt:183cm')
assert valid_passport.valid?
refute invalid_passport.valid?
end
def test_issue_year_validation
assert_within 'iyr', 2010, 2020
end
def test_expiration_year_validation
assert_within 'eyr', 2020, 2030
end
def test_height
assert Field.for('hgt', '150cm').valid?
assert Field.for('hgt', '193cm').valid?
refute Field.for('hgt', '149cm').valid?
assert Field.for('hgt', '59in').valid?
end
def test_hair_color
assert Field.for('hcl', '#3a91bc').valid?
assert Field.for('hcl', '#000000').valid?
refute Field.for('hcl', '#00000012').valid?
refute Field.for('hcl', '3a91bc').valid?
refute Field.for('hcl', '#wombat').valid?
refute Field.for('hcl', '#abc').valid?
end
def test_eye_color
assert Field.for('ecl', 'amb').valid?
refute Field.for('ecl', 'xyz').valid?
end
def test_pid
assert Field.for('pid', '012345678').valid?
refute Field.for('pid', '123').valid?
refute Field.for('pid', '123455678919').valid?
refute Field.for('pid', 'abcdefghi').valid?
end
def test_examples
skip
passports = "eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946
hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277
hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007
pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f
eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm
hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022
iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:09315471".split("\n\n")
assert passports.all? { |string| Passport.from_string(string) }
end
def test_part_two
skip
result = input.map { |fields_string| Passport.from_string(fields_string) }.count(&:valid?)
assert_equal 184, result
end
def input
File.read('day_four_input.txt').split("\n\n")
end
def assert_within(code, min, max)
assert Field.for(code, min).valid?
assert Field.for(code, max).valid?
refute Field.for(code, min - 1).valid?
refute Field.for(code, max + 1).valid?
end
end
|
TypeScript
|
UTF-8
| 619
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
import styled from 'styled-components';
import { typography } from 'styled-system';
import DEFAULT_THEME, { Theme } from '../../default-theme';
type HeadingProps = {
variant?: string;
theme?: Theme;
children?: React.ReactNode;
};
function getSize({ theme, variant }) {
return theme.headingFontSizes[variant];
}
/**
* This adds hierarchy to a section in a page.
*/
const Heading = styled.h2<HeadingProps>`
${typography};
font-weight: bold;
font-size: ${getSize}rem;
margin: 0;
`;
Heading.defaultProps = {
variant: 'medium',
theme: DEFAULT_THEME,
};
export default Heading;
|
Markdown
|
UTF-8
| 3,159
| 4.28125
| 4
|
[] |
no_license
|
##面向对象 学习
###1、学习目标
1.了解面向对象程序的特点
2.学会js模块面向对象的方法
3.理解prototype
4.理解继承
###2、面向对象程序设计
面向对象的语言有一个标志,那就是他们都有类的概念,通过类可以创建任意
多个具有相同属性和方法的对象,但是ECMAScript中没有类的概念,但是我们可以通过其他方式来模拟面向对象的类。
1.工厂模式,工厂模式是软件工厂领域中一种最广为人知的设计模式。
1.构造函数模式,比如像ECMAScript中的Array,Object,Date等都是通过构造函数来构建的。
2.动态原型模式
3.寄生构造函数模式
4.稳妥构造函数模式
###3、原型
1.我们创建的每一个函数都有一个prototype属性,这个属性是一个指针,指向一个对象。
而这个对象的用途是包含可以有特定类型的所有实例共享的属性和方法。
2.原型对象实际就是一个构造函数的实例对象,与普通的实例对象没有本质上的区别,js中每一个对象都有一个原型对象。t
不过他比较特殊,该对象包含的所有属性和方法能够供构造函数的所有实例共享,这就是其他语言所说的继承,而javascript通过原型对象来实现继承。简称原型继承,静态继承。Object prototype[method field]
3.简单实现Array中的push,pop方法。
###4、简单原型
1.之前我们掌握了原型如何使用,现在我们学习简单原型的使用方式:即直接通过对象字面量来重写整个原型对象。
2.ECMAScript的Object.defineProperty()方法可以为原型对象重新加入构造器。
3.原型的动态性(注意原型和创建实例的前后顺序)
###5、原型对象存在的问题
1.原型对象虽然可以对所有实例的属性和方法共享,但是他的局限性也是很明显的,正是因为共享的特性,也导致原型存在的最大问题。
2.我们一般组合使用构造函数和原型模式,在实际开发中,这种模式也应用最为广泛。
3.动态原型模式:就是把信息都封装到函数中,这样体现了封装的概念。
4.稳妥构造函数式:所谓稳妥模式就是没有公共属性,而且其他方法也不引用this对象,稳妥模式最适合在安全的环境中使用。
如果你的程序对于安全性要求很高,那么非常是个这种模式。
###6、继承
1.我们都知道构造函数,原型和实例直接的关系,如果我们让原型对象等于另外一个类型的实例,结果会怎样?
显然此时的原型对象将包含一个指向两外一个原型的指针。相应的两另外一个原型中也包含着一个指向另外一个构造函数的指针。
2.原型链:利用原型让一个引用类型继承另外一个引用类型的属性和方法。
3.简单继承(原型继承)
4.类继承(模板继承或借用构造函数继承)
5.混合使用继承实现完整的继承
|
Java
|
UTF-8
| 1,546
| 1.921875
| 2
|
[] |
no_license
|
package com.hlnwl.auction.ui.goods;
import androidx.annotation.Nullable;
import com.allen.library.SuperTextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hlnwl.auction.R;
import com.hlnwl.auction.bean.goods.OfferBean;
import com.hlnwl.auction.utils.photo.ImageLoaderUtils;
import java.util.List;
/**
* 版权:hlnwl 版权所有
*
* @author yougui
* 版本:1.0
* 创建日期:2019/9/24 10:05
* 描述:
*/
public class OfferAdapter extends BaseQuickAdapter<OfferBean.DataBean, BaseViewHolder> {
public OfferAdapter() {
super(R.layout.item_offer);
}
@Override
protected void convert(BaseViewHolder helper, OfferBean.DataBean item) {
SuperTextView offer=helper.getView(R.id.item_offfer);
ImageLoaderUtils.display(mContext,offer.getLeftIconIV(),item.getFace_img());
offer.setLeftTopString(item.getTheme());
offer.setLeftBottomString(mContext.getResources().getString(R.string.danwei)+item.getPrice());
if (helper.getAdapterPosition()==0){
offer.setRightTopString(mContext.getResources().getString(R.string.leading));
offer.setRightTopTextColor(mContext.getResources().getColor(R.color.main));
}else {
offer.setRightTopString(mContext.getResources().getString(R.string.out));
offer.setRightTopTextColor(mContext.getResources().getColor(R.color.default_color));
}
offer.setRightBottomString(item.getAddtime());
}
}
|
Markdown
|
UTF-8
| 7,039
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
# API
## Терминология:
+ **Узел** - любой из двух компьютеров, между которыми установлено соединение.
+ **Сервер** - узел, занимающий распределением сообщений между пользователями.
+ **Клиент** - узел, занимающийся передачей сообщений от лица одного пользователя.
+ **Пользователь** - человек, использующий клиент.
+ **Сообщение** - текстовое послание одного пользователя к другому.
+ **Пакет** - единица передачи оформленных данных между узлами.
+ **Запрос** - пакет, инициирующий активность удаленного узла и подразумевающий реакцию со сторону удаленного узла.
+ **Ответ** - пакет, сообщающий результаты выполнения запроса.
## Общие сведения
Данные между узлами передаются по протоколу WebSocket. Пакеты кодируются в JSON и имеют общий формат:
```
{
"id": <...>,
<доп. данные>,
}
<нулевой байт>
```
* `id`:строка - id пакета, который используется для ассоциации запросов с ответами. В пределах одного подключения id пар запрос-ответ не обязательно должны быть уникальными, до тех пор пока это не мешает соотносить соотносить эти пары.
Текст пакета гарантировано начинается с открывающей фигурной скобки и заканчивается закрывающей скобкой и нулевым байтом. Возможно наличие вложенных фигурных скобок.
Табуляция, пробелы и переносы строк не регламентируются.
Запросы кодируются в следующем формате:
```
{
"id": <...>,
"req": <...>,
<доп. данные>,
}
<нулевой байт>
```
* `req`:строка - тип запроса, который характеризуют запрос в целом.
Ответы кодируются:
```
{
"id": <...>,
"status": <...>,
"internal-error": <...>,
<доп. данные>,
}
<нулевой байт>
```
* `id`:строка - id запроса, на который производится ответ.
* `status`:строка
+ `ok` означает успешное выполнение задачи для всех запросов.
+ `internal-error` означает внутреннюю ошибку сервера, не предусмотренную обработчиком запроса.
+ Каждый тип может резервировать дополнительные значения статуса.
* `internal-error` - если `status = internal-error`, содержит текст внутренней ошибки. В остальных случаях отсутствует.
## Типы запросов
### **К** `hello`
Регистрация пользователя.
Запрос:
```
{
"id": <...>,
"req": "hello",
"username": <...>,
}
<нулевой байт>
```
* `username`:строка - имя пользователя.
Формат ответа:
```
{
"id": <...>,
"status": <...>,
"suggestion": <...>,
}
<нулевой байт>
```
* `status`:строка
+ `ok` - регистрация успешна, клиент может отправлять сообщения
+ `taken` - имя пользователя уже занято
* `suggestion`:строка
+ При `status=taken` возвращает предлагаемое свободное имя пользователя.
+ При `status=ok` отсутствует или пусто.
### **К** `bye`
Завершение сессии и освобождение имени пользователя. Если клиент хочет продолжить отправлять сообщения, он должен снова отправить `hello`.
Не обязательно завершать все сессии запросом `bye`, как только клиент разрывает подключение. Запрос `bye` может быть использован для переименования пользователя.
Запрос:
```
{
"id": <...>,
"req": "bye",
}
<нулевой байт>
```
Ответ:
```
{
"id": <...>,
"status": "ok",
}
<нулевой байт>
```
### **КС** `msg`
При отправлении клиенту означает получение сообщения. При отправлении серверу означает отправку.
Запрос:
```
{
"id": <...>,
"req": "msg",
"username": <...>,
"msg": <...>,
}
<нулевой байт>
```
* `username`:строка - имя отправителя сообщения (при получении клиентов) или адресата сообщения (при получении сервером).
* `msg`:строка - текст сообщения.
Ответ:
```
{
"id": <...>,
"status": <...>,
}
<нулевой байт>
```
* `status`:строка
+ `ok` - сообщение успешно доставлено.
+ `nouser` - адресат не найден.
## Пример
Клиент подключается к серверу, регистрируется, отправляет пару сообщений, меняет имя пользователя и отключается.
Содержание пакетов отображено в краткой форме.
|Клиент|Сервер|
|---|---|
|*Соединение установлено*|*Соединение установлено*|
|**hello**(id=0, username=root)|-|
|-|**taken**(id=0, suggestion=root134)|
|**hello**(id=1, username=root134)|-|
|-|**ok**(id=1)|
|**msg**(id=2, username=root, text="You took my name!")|-|
|-|**internal-error**(id=2, internal-error="Access denied")|
|**msg**(id=3, username=root1, text="Who is root?")|-|
|-|**ok**(id=3)|
|-|**msg**(id=4, username=root1, text"He's the admin")|
|**ok**(id=4)|-|
|**bye**(id=5)|-|
|-|**ok**(id=5)|
|**hello**(id=6, username=butterfly)|-|
|-|**ok**(id=6)|
|**msg**(id=7, username=root1, text="Please, free your username")|-|
|**msg**(id=8, username=root2, text="Please, free your username")|-|
|-|**ok**(id=7)|
|**msg**(id=9, username=root3, text="Please, free your username")|-|
|-|**ok**(id=8)|
|-|**ok**(id=9)|
|*Соединение закрыто клиентом*|*Соединение закрыто клиентом*|
|
Java
|
WINDOWS-1252
| 5,527
| 2.515625
| 3
|
[] |
no_license
|
package com.sevenstar.steward2016.view;
import java.util.Calendar;
import com.lib.shiguotao.utils.ConvertUtils;
import com.lib.shiguotao.utils.DialogUtils;
import com.lib.shiguotao.utils.ViewUtils;
import com.lib.shiguotao.view.wheel.OnWheelChangedListener;
import com.lib.shiguotao.view.wheel.WheelView;
import com.lib.shiguotao.view.wheel.adapters.DateWheelAdapter;
import com.sevenstar.steward2016.R;
import android.app.Activity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class SetTimeDialogLayout implements OnClickListener, OnWheelChangedListener {
private Activity activity;
private View diagLayout;
private WheelView yearWheelView;
private WheelView monthWheelView;
private WheelView dayWheelView;
private WheelView hourWheelView;
private WheelView minuteWheelView;
private int year;
private int month;
private int day;
private int hour;
private int minute;
private int nowYear;
private DateWheelAdapter yearAdapter;
private DateWheelAdapter monthAdapter;
private DateWheelAdapter dayAdapter;
private DateWheelAdapter hourAdapter;
private DateWheelAdapter minuteAdapter;
public SetTimeDialogLayout(Activity activity, final TextView showTimeTV, final OnClickListener onClickListener) {
this.activity = activity;
diagLayout = LayoutInflater.from(activity).inflate(R.layout.set_time_dialog_layout, null);
yearWheelView = (WheelView) diagLayout.findViewById(R.id.set_time_dialog_wheelView_1);
monthWheelView = (WheelView) diagLayout.findViewById(R.id.set_time_dialog_wheelView_2);
dayWheelView = (WheelView) diagLayout.findViewById(R.id.set_time_dialog_wheelView_3);
hourWheelView = (WheelView) diagLayout.findViewById(R.id.set_time_dialog_wheelView_4);
minuteWheelView = (WheelView) diagLayout.findViewById(R.id.set_time_dialog_wheelView_5);
yearAdapter = new DateWheelAdapter(activity, 0);
monthAdapter = new DateWheelAdapter(activity, 1);
dayAdapter = new DateWheelAdapter(activity, 2);
hourAdapter = new DateWheelAdapter(activity, 3);
minuteAdapter = new DateWheelAdapter(activity, 4);
yearWheelView.setViewAdapter(yearAdapter);
monthWheelView.setViewAdapter(monthAdapter);
dayWheelView.setViewAdapter(dayAdapter);
hourWheelView.setViewAdapter(hourAdapter);
minuteWheelView.setViewAdapter(minuteAdapter);
Calendar cal = Calendar.getInstance();
nowYear = cal.get(Calendar.YEAR);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
hour = cal.get(Calendar.HOUR_OF_DAY);
minute = cal.get(Calendar.MINUTE);
yearWheelView.addChangingListener(this);
monthWheelView.addChangingListener(this);
View confirm = ViewUtils.find(diagLayout, R.id.confirm_button);
View cancel = ViewUtils.find(diagLayout, R.id.cancel_button);
confirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
year = yearAdapter.getItemData(yearWheelView.getCurrentItem());
month = monthAdapter.getItemData(monthWheelView.getCurrentItem());
day = dayAdapter.getItemData(dayWheelView.getCurrentItem());
hour = hourAdapter.getItemData(hourWheelView.getCurrentItem());
minute = minuteAdapter.getItemData(minuteWheelView.getCurrentItem());
String dateTime = String.format("%s-%s-%s\t%s:%s", ConvertUtils.intTwoString(year), ConvertUtils.intTwoString(month),
ConvertUtils.intTwoString(day), ConvertUtils.intTwoString(hour), ConvertUtils.intTwoString(minute));
ViewUtils.setTextData(showTimeTV, dateTime);
month = month - 1;
DialogUtils.closeDialog();
if (onClickListener != null) {
v.setTag(dateTime);
onClickListener.onClick(v);
}
}
});
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogUtils.closeDialog();
}
});
}
public void show() {
// String time = select_time_tv.getText().toString();
// if (OtherUtils.isNotEmpty(time) && !time.equals("ѡʱ")) {
// String[] dateTimes = time.split("\t");
// String[] dates = dateTimes[0].split("-");
// year = Integer.parseInt(dates[0]);
// month = Integer.parseInt(dates[1]) - 1;
// day = Integer.parseInt(dates[2]);
// String[] times = dateTimes[1].split(":");
// hour = Integer.parseInt(times[0]);
// minute = Integer.parseInt(times[1]);
// }
ViewGroup parent = (ViewGroup) diagLayout.getParent();
if (parent != null) {
parent.removeView(diagLayout);
}
yearWheelView.setCurrentItem(year - nowYear, false);
monthWheelView.setCurrentItem(month - 1, false);
dayWheelView.setCurrentItem(day - 1, false);
hourWheelView.setCurrentItem(hour, false);
minuteWheelView.setCurrentItem(minute, false);
DialogUtils.show(activity, R.style.custom_dialog_style, 0, diagLayout, Gravity.CENTER, false);
DialogUtils.showDialog();
}
@Override
public void onClick(View v) {
show();
}
@Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
int year = 0;
int month = 0;
if (wheel == yearWheelView) {
year = yearAdapter.getItemData(newValue);
month = monthAdapter.getItemData(monthWheelView.getCurrentItem());
} else if (wheel == monthWheelView) {
year = yearAdapter.getItemData(yearWheelView.getCurrentItem());
month = newValue;
}
dayAdapter.refreshDayInfo(year, month);
}
}
|
TypeScript
|
UTF-8
| 3,183
| 3.15625
| 3
|
[] |
no_license
|
import { Bird } from './bird';
fdescribe('Bird', () => {
let bird;
describe('bird is EUROPEAN', () => {
beforeEach(() => {
bird = new Bird('EUROPEAN');
});
describe('#getSpeed', () => {
it('returns correct bird speed', () => {
expect(bird.getSpeed()).toEqual(21);
});
});
describe('#getWeight', () => {
it('returns correct bird weight', () => {
expect(bird.getWeight()).toEqual(3);
});
});
describe('#getHeight', () => {
it('returns correct bird height', () => {
expect(bird.getHeight()).toEqual(10);
});
});
});
describe('bird is AFRICAN', () => {
beforeEach(() => {
bird = new Bird('AFRICAN');
});
describe('#getSpeed', () => {
it('returns correct bird speed', () => {
expect(bird.getSpeed()).toEqual(15);
});
});
describe('#getWeight', () => {
it('returns correct bird weight', () => {
expect(bird.getWeight()).toEqual(3);
});
});
describe('#getHeight', () => {
it('returns correct bird height', () => {
expect(bird.getHeight()).toEqual(5);
});
});
});
describe('bird is NORWEGIAN BLUE', () => {
describe('bird is nailed - not sure what this means', () => {
beforeEach(() => {
bird = new Bird('NORWEGIAN_BLUE', 3, true);
});
describe('#getSpeed', () => {
it('returns correct bird speed', () => {
expect(bird.getSpeed()).toEqual(0);
});
});
describe('#getWeight', () => {
it('returns correct bird weight', () => {
expect(bird.getWeight()).toEqual(10);
});
});
describe('#getHeight', () => {
it('returns correct bird height', () => {
expect(bird.getHeight()).toEqual(10);
});
});
});
describe('bird is not nailed - not sure what this means', () => {
beforeEach(() => {
bird = new Bird('NORWEGIAN_BLUE', 3, false);
});
describe('#getSpeed', () => {
it('returns correct bird speed', () => {
expect(bird.getSpeed()).toEqual(4);
});
});
describe('#getWeight', () => {
it('returns correct bird weight', () => {
expect(bird.getWeight()).toEqual(10);
});
});
describe('#getHeight', () => {
it('returns correct bird height', () => {
expect(bird.getHeight()).toEqual(10);
});
});
});
});
describe('bird type INVALID_BIRD', () => {
beforeEach(() => {
bird = new Bird('INVALID_BIRD');
});
describe('#getSpeed', () => {
it('throws an invalid bird type error', () => {
expect(() => bird.getSpeed()).toThrowError(Error, 'Invalid Bird Type');
});
});
describe('#getWeight', () => {
it('throws an invalid bird type error', () => {
expect(() => bird.getWeight()).toThrowError(Error, 'Invalid Bird Type');
});
});
describe('#getHeight', () => {
it('throws an invalid bird type error', () => {
expect(() => bird.getHeight()).toThrowError(Error, 'Invalid Bird Type');
});
});
});
});
|
TypeScript
|
UTF-8
| 3,411
| 2.53125
| 3
|
[] |
no_license
|
import HttpPostClientSpy from '@/Data/Mocks/HttpPostClientSpy';
import { HttpStatusCode } from '@/Data/Protocols/Http/HttpResponse';
import RemoteAuthentication from '@/Data/Usecases/Authentication/RemoteAuthentication';
import { InvalidCredentialsError } from '@/Domain/Errors/InvalidCredentialsError';
import { UnexpectedError } from '@/Domain/Errors/UnexpectedError';
import { accountModelMock } from '@/Domain/Mocks/accountModelMock';
import { authenticationMock } from '@/Domain/Mocks/authenticationMock';
import { AccountModel } from '@/Domain/Models/AccountModel';
import { AuthenticationParams } from '@/Domain/Usecases/Authentication';
import faker from 'faker';
type SUTTypes = {
SUT: RemoteAuthentication;
httpPostClientSpy: HttpPostClientSpy<AuthenticationParams, AccountModel>;
};
function SUTFactory(url: string = faker.internet.url()): SUTTypes {
const httpPostClientSpy = new HttpPostClientSpy<AuthenticationParams, AccountModel>();
const SUT = new RemoteAuthentication(url, httpPostClientSpy);
return {
SUT,
httpPostClientSpy,
};
}
describe('RemoteAuthentication', () => {
it('calls HttpPostClient with correct URL', async () => {
const url = faker.internet.url();
const { SUT, httpPostClientSpy } = SUTFactory(url);
await SUT.auth(authenticationMock());
expect(httpPostClientSpy.url).toBe(url);
});
it('calls HttpPostClient with correct body', async () => {
const { SUT, httpPostClientSpy } = SUTFactory();
const authParams = authenticationMock();
await SUT.auth(authParams);
expect(httpPostClientSpy.body).toEqual(authParams);
});
it('throws InvalidCredentialsError when HttpPostClient returns 401 statusCode', async () => {
const { SUT, httpPostClientSpy } = SUTFactory();
httpPostClientSpy.data = {
statusCode: HttpStatusCode.unauthorized,
};
const promise = SUT.auth(authenticationMock());
await expect(promise).rejects.toThrow(new InvalidCredentialsError());
});
it('throws UnexpectedError when HttpPostClient returns 400 statusCode', async () => {
const { SUT, httpPostClientSpy } = SUTFactory();
httpPostClientSpy.data = {
statusCode: HttpStatusCode.badRequest,
};
const promise = SUT.auth(authenticationMock());
await expect(promise).rejects.toThrow(new UnexpectedError());
});
it('throws UnexpectedError when HttpPostClient returns 404 statusCode', async () => {
const { SUT, httpPostClientSpy } = SUTFactory();
httpPostClientSpy.data = {
statusCode: HttpStatusCode.notFound,
};
const promise = SUT.auth(authenticationMock());
await expect(promise).rejects.toThrow(new UnexpectedError());
});
it('throws UnexpectedError when HttpPostClient returns 500 statusCode', async () => {
const { SUT, httpPostClientSpy } = SUTFactory();
httpPostClientSpy.data = {
statusCode: HttpStatusCode.serverError,
};
const promise = SUT.auth(authenticationMock());
await expect(promise).rejects.toThrow(new UnexpectedError());
});
it('return AccountModel when HttpPostClient returns 200 statusCode', async () => {
const { SUT, httpPostClientSpy } = SUTFactory();
const response = accountModelMock();
httpPostClientSpy.data = {
statusCode: HttpStatusCode.ok,
body: response,
};
const account = await SUT.auth(authenticationMock());
expect(account).toEqual(response);
});
});
|
TypeScript
|
UTF-8
| 193
| 3.15625
| 3
|
[] |
no_license
|
export function removeValueFromArray<T>(array: T[], excludedValue: T): T[] {
const index = array.indexOf(excludedValue);
if (index > -1) {
array.splice(index, 1);
}
return array;
}
|
Python
|
UTF-8
| 1,586
| 2.828125
| 3
|
[
"CC-BY-2.0",
"Zlib"
] |
permissive
|
"""
Test the functions in the `logger` module
"""
import datetime
from poezio.logger import LogMessage, parse_log_line, parse_log_lines, build_log_message
from poezio.common import get_utc_time, get_local_time
def test_parse_message():
line = 'MR 20170909T09:09:09Z 000 <nick> body'
assert vars(parse_log_line(line, 'user@domain')) == vars(LogMessage('2017', '09', '09', '09', '09', '09', '0', 'nick', 'body'))
line = '<>'
assert parse_log_line(line, 'user@domain') is None
line = 'MR 20170908T07:05:04Z 003 <nick> '
assert vars(parse_log_line(line, 'user@domain')) == vars(LogMessage('2017', '09', '08', '07', '05', '04', '003', 'nick', ''))
def test_log_and_parse_messages():
msg1 = {'nick': 'toto', 'msg': 'coucou', 'date': datetime.datetime.now().replace(microsecond=0)}
msg1_utc = get_utc_time(msg1['date'])
built_msg1 = build_log_message(**msg1)
assert built_msg1 == 'MR %s 000 <toto> coucou\n' % (msg1_utc.strftime('%Y%m%dT%H:%M:%SZ'))
msg2 = {'nick': 'toto', 'msg': 'coucou\ncoucou', 'date': datetime.datetime.now().replace(microsecond=0)}
built_msg2 = build_log_message(**msg2)
msg2_utc = get_utc_time(msg2['date'])
assert built_msg2 == 'MR %s 001 <toto> coucou\n coucou\n' % (msg2_utc.strftime('%Y%m%dT%H:%M:%SZ'))
assert parse_log_lines((built_msg1 + built_msg2).split('\n'), 'user@domain') == [
{'time': msg1['date'], 'history': True, 'txt': '\x195,-1}coucou', 'nickname': 'toto'},
{'time': msg2['date'], 'history': True, 'txt': '\x195,-1}coucou\ncoucou', 'nickname': 'toto'},
]
|
Java
|
UTF-8
| 3,376
| 2.984375
| 3
|
[] |
no_license
|
package com.leetcode.extra;
import com.leetcode.TreeNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
public class SumPathTree {
private static List<Integer> listResult = new ArrayList<>();
public static void main(String args[]){
TreeNode root = new TreeNode(4);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(8);
root.left.right = new TreeNode(9);
root.left.left.left = new TreeNode(5);
root.left.right.left = new TreeNode(6);
root.right.right = new TreeNode(10);
root.right.left = new TreeNode(1);
Stack<Integer> stack = new Stack<>();
List<Integer> result2 = new ArrayList<>();
StringBuilder sb = new StringBuilder();
pathSum(root, 18);
listResult.stream().forEach(n -> sb.append(n).append("-"));
System.out.println(sb.toString());
String print = sb.toString().substring(0, sb.length()-1);
System.out.println(print);
// stackWay(root, stack, 18);
// listResult.stream().forEach(System.out::print);
}
public static void pathSum(TreeNode root, int target) {
if (root == null||!listResult.isEmpty()) return;
List<Integer> path = new ArrayList<Integer>();
dfs(root, path, target);
pathSum(root.left, target);
pathSum(root.right, target);
}
public static void dfs(TreeNode root, List<Integer> path, int target) {
if (root == null||!listResult.isEmpty()) return;
path.add(root.val);
target-=root.val;
if(target == 0&&root.left==null&&root.right==null){
listResult.addAll(path);
}else{
dfs(root.left, path, target);
dfs(root.right, path, target);
}
path.remove(path.size()-1);
}
public static void stackWay(TreeNode root, Stack<Integer> stack, int target) {
if (root == null) return;
stack.push(root.val);
if(root.left==null&&root.right==null){
determineIsPath(stack, target);
}else{
stackWay(root.left, stack, target);
stackWay(root.right, stack, target);
}
if(!stack.isEmpty()){
stack.pop();
}
}
private static void determineIsPath(Stack<Integer> stack, int target){
Stack<Integer> temp = new Stack<>();
int size = stack.size();
for(int i = 0; i<size; i++ ){
temp.add(stack.pop());
int sum = temp.stream().mapToInt(n -> n.intValue()).sum();
if(sum<target){
continue;
}else if(sum==target){
listResult.addAll(temp);
break;
}
}
Collections.reverse(stack);
temp.stream().forEach(n -> stack.push(n));
}
private static void method(Stack<Integer> result, TreeNode root, int target, int sum) {
if(sum + root.val == target){
result.push(root.val);
return;
}else if(sum + root.val>target) {
result.pop();
return;
}else if(sum + root.val< target){
result.push(root.val);
sum = sum + root.val;
method(result, root.left, target, sum);
}
}
}
|
Java
|
UTF-8
| 662
| 2.046875
| 2
|
[] |
no_license
|
package com.yongq.a_dao;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.yongq.s_dto.StudentVO;
@Repository
public class AdminFindPWDAOImpl implements AdminFindPWDAO {
@Inject
SqlSession sqlSession;
private String namespace = "com.yongq.mapper.find_password";
@Override
public StudentVO FindPW(HttpServletRequest request) {
String stu_id = request.getParameter("stu_id");
StudentVO sVo = new StudentVO();
sVo.setStu_id(stu_id);
return sqlSession.selectOne(namespace + ".find_password", sVo);
}
}
|
Markdown
|
UTF-8
| 955
| 3.046875
| 3
|
[] |
no_license
|
# CvsCSharp
this is a simple project to compare C and C# performances in computational tasks
you can test this by your self by running **compile.bat** first then **run.bat**
in run.bat you can change how many times you want to run each test
you can automate it by someting like
```
for /l %%x in (1,1,%%count) do
```
and then run your stuff there
don't forget to redirect the standard output to a file
```.run.bat >> results.txt```
## Results so far:
for detailed data for each run refere to **Results.md**
|**language** | itterations | avg. time taken | min | max
|--------|:-------------:|:------------------:|:-----:|----:
|c|10|0.555555556|0|1
|c#|10|1.222222222|1|2
|--------|-------------|------------------|-----|----|
|c|1000|68.77777778|66|73
|c#|1000|73.55555556|71|83
|--------|-------------|------------------|-----|----|
|c|100000|7186.5|7112|7242
|c#|100000|8071.25|7757|8520
|--------|-------------|------------------|-----|----|
|
Java
|
UTF-8
| 4,960
| 2.671875
| 3
|
[] |
no_license
|
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.io.Writer;
import java.util.Map;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.AbstractMap;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int rowCount = in.readInt();
int columnCount = in.readInt();
int[][] target = IOUtils.readIntTable(in, rowCount, columnCount);
int[][] test = new int[rowCount][columnCount];
ArrayUtils.fill(test, 100);
for (int i = 0; i < rowCount; i++) {
int max = 0;
for (int j = 0; j < columnCount; j++)
max = Math.max(max, target[i][j]);
for (int j = 0; j < columnCount; j++)
test[i][j] = Math.min(test[i][j], max);
}
for (int i = 0; i < columnCount; i++) {
int max = 0;
for (int j = 0; j < rowCount; j++)
max = Math.max(max, target[j][i]);
for (int j = 0; j < rowCount; j++)
test[j][i] = Math.min(test[j][i], max);
}
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++) {
if (target[i][j] != test[i][j]) {
out.printLine("Case #" + testNumber + ": NO");
return;
}
}
}
out.printLine("Case #" + testNumber + ": YES");
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
}
class ArrayUtils {
public static void fill(int[][] array, int value) {
for (int[] row : array)
Arrays.fill(row, value);
}
}
|
Java
|
UTF-8
| 646
| 2.59375
| 3
|
[] |
no_license
|
package org.ozsoft.secs.format;
import org.junit.Assert;
public abstract class TestUtils {
public static void assertEquals(byte[] expected, byte[] actual) {
boolean isEqual = (actual.length == expected.length);
for (int i = 0; isEqual && (i < actual.length); i++) {
if (actual[i] != expected[i]) {
isEqual = false;
}
}
if (!isEqual) {
B expectedB = new B(expected);
B actualB = new B(actual);
Assert.fail(String.format("Byte arrays differ -- expected: %s; actual: %s", expectedB, actualB));
}
}
}
|
JavaScript
|
UTF-8
| 923
| 3.328125
| 3
|
[] |
no_license
|
// VISI INPUTAI TURI BUTI UZDAROMI
import { useState } from "react";
// CIA NEKONTROLIUOJAMAS KOMPONENTAS, KA NORIU TA RASAU:
// function TextInput() {
// return(
// <div>
// <input type="text" />
// </div>
// )
// }
// export default TextInput;
// KONTROLIUOJAMAS KOMPONENTAS:
function TextInput() {
const [value, setValue] = useState('');
const [tvalue, setTvalue] = useState('');
// gaus argumentu eventa
const change = eventas => {
// console.log('fbdf', eventas.target.value);
setValue(eventas.target.value);
}
// gaus argumentu eventa
const tchange = eventas => {
setTvalue(eventas.target.value);
}
return (
<div className='sq'>
<input onChange={change} type="text" value={value} />
<textarea onChange={tchange} value={tvalue}></textarea>
</div>
)
}
export default TextInput;
|
PHP
|
UTF-8
| 1,229
| 3.140625
| 3
|
[] |
no_license
|
<?php
/** The AppInterface describes what it needs to build an application class.
* @package App
* @author zeropanic <zeropanic@myself.com>
* @version 1.0
* @namespace Oz\App
*/
namespace Oz\App;
interface AppInterface
{
/**
* init the application
* @access public
* @return \Oz\App instance of the class for chaining with run method
*/
public function init();
/**
* setPath set a path of the application, you can add whatever
* path you want by providing a key and a path.
* @access public
* @param string $pathKey key to store the path
* @param string $path absolute path associated with the above key
* @return void
*/
public function setPath($pathKey, $path);
/**
* getPath allows you to get a path defined with setPath
* @access public
* @param string $pathKey the key of the path you want to retrieve
* @return mixed string of the path if one exists for the supplied key
* or false if none exists
*/
public function getpath($pathKey);
/**
* run the application by calling dispatcher->dispatch() method
* @access public
* @return void
*/
public function run();
}
?>
|
C++
|
UTF-8
| 751
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include "Element.h"
#include "Parent.h"
#include "Spatial_Source.h"
namespace scenery {
class Simple_Element : public virtual Element {
protected:
Parent *parent = nullptr;
public:
Simple_Element() {
// if (parent)
// parent->add_child(unique_ptr<Element>(this));
}
~Simple_Element() {}
virtual Parent *get_parent() const override {
return parent;
}
virtual void set_parent(Parent *new_parent, bool update_others = true) override;
virtual void remove() {
parent->remove_child(*this);
}
virtual void render() override {
}
virtual void update(float delta) override {
}
};
}
|
Python
|
UTF-8
| 3,226
| 3.296875
| 3
|
[] |
no_license
|
"""
Created on 23/01/2015
@author: dave
"""
import csv
import getopt
import os.path
import sys
from GLSapp.ReferenceScraper import ReferenceScraper
from GLSapp.LinkScraper import LinkScraper
# Application handling class
class MainApp:
def __init__(self):
self.scraper = None
self.mode = None
self.urls = list()
self.fileUpdated = False
# Main application entry point
def main(self):
# Extract args
try:
opts, args = getopt.getopt(
sys.argv[1:],
"hf:u:p:l",
["help", "file=", "url=", "pattern=", "links"]
)
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
self.usage()
sys.exit(2)
# Process args
pattern_mode_option = link_mode_option = False
for o, a in opts:
if o in ("-h", "--help"):
self.usage()
sys.exit()
if o in ("-p", "--pattern"):
pattern_mode_option = True
self.scraper = ReferenceScraper(
callback=self.write_csv, pattern=str(a))
elif o in ("-l", "--links"):
link_mode_option = True
self.scraper = LinkScraper(callback=self.write_csv)
elif o in ("-f", "--file"):
_urlList = self.read_file(a)
if len(_urlList) > 0:
self.urls += _urlList
elif o in ("-u", "--url"):
self.urls.append(a)
# Checks
if not pattern_mode_option and not link_mode_option:
print("Please select either link or pattern mode")
self.usage()
sys.exit()
if pattern_mode_option and link_mode_option:
print("Cannot run both link and pattern modes")
self.usage()
sys.exit()
# Run
self.scraper.add_page_list(self.urls)
self.scraper.run()
# Display help message
def usage(self):
print("Options:")
print("help: -h, --help")
print("file: -f, --file")
print("single url: -u, --url")
print("search pattern: -p, --pattern")
print("crawl links: -l, --links")
pass
# Read list from CSV file
def read_file(self, _filename):
if os.path.isfile(_filename):
csv_list = []
with open(_filename, 'r') as f:
reader = csv.reader(f)
for line in reader:
if "http" in line[0]:
csv_list.append(line[0])
return csv_list
else:
print("File: " + _filename + " not found")
return False
# Write output into file
def write_csv(self, _results):
if not self.fileUpdated:
self.fileUpdated = True
fh = open("Results.txt", "w")
fh.write('\n'.join(sorted(_results)) + '\n')
fh.close()
print("Result written!")
# Run application from self
if __name__ == '__main__':
_app = MainApp()
_app.main()
|
JavaScript
|
UTF-8
| 3,829
| 3.40625
| 3
|
[] |
no_license
|
'use strict';
let arrayO = [];
let arrayX = [];
var defaults = {
backgroundcolor: '#000',
color: '#fff',
weekdays: ['sun','mon','tue','wed','thu','fri','sat']
};
let winners = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
];
console.log('this is it: ' + winners[1]);
document.addEventListener('DOMContentLoaded', () => {
// Your code here
let toggle = true;
document.querySelectorAll('[data-cell]').forEach((div) => {
div.addEventListener('click', (e) => {
//var clickedEl = e.target;
var cellIndex = e.target.dataset.cell;
console.log(cellIndex);
if (!e.target.innerHTML) {
e.target.innerHTML = toggle ? 'X' : 'O';
// toggle = !toggle;
// add the cell value to corresponding player array
if (e.target.innerHTML === 'X') {
arrayX.push(parseInt(e.target.dataset.cell));
}
if (e.target.innerHTML === 'O') {
arrayO.push(parseInt(e.target.dataset.cell));
}
toggle = !toggle;
console.log(arrayO);
console.log(arrayX);
// run the checkWin function
checkForWin();
} else {
alert('stop it!');
}
});
});
/*
let checkForWin = function(){
console.log('made it to check for win');
winners.winners.forEach(function (e) {
//console.log(winners.winners);
if (winners.winners[0].every(arrayO) === true) {
alert ('Player O Wins!');
}
if (winners.winners[0].every(arrayX) === true) {
alert ('Player X Wins!');
}
}
)};
*/
let checkForWin = function(){
console.log('made it to check for win');
for (let i = 0; i < winners.length; i++) {
console.log('and this ' + winners[i]);
console.log(arrayO);
console.log(arrayX);
//console.log(winners.winners[i]);
arrayO = arrayO.sort();
arrayX = arrayX.sort();
if (arrayO.join().includes(winners[i].join())){
alert ('Player O Wins!');
}
if (arrayX.join().includes(winners[i].join())){
alert ('Player X Wins!');
}
/*
if (winners[i].join() == arrayO.join()){
alert ('Player O Wins!');
}
if (winners[i].join() == arrayX.join()){
alert ('Player X Wins!');
}
*/
/*
if (winners.winners[i].includes() === true) {
alert ('Player O Wins!');
}
if (winners.winners[i].includes(arrayX) === true) {
alert ('Player X Wins!');
}*/
}
};
/*
if (arrayO.includes(0, 1, 2 || 3,4,5 || 6,7,8 || 0,3,6 || 1,4,7 || 2,5,8 ||
0,4,8 || 2,4,6)){
alert('Player O Wins!');
}
*/
/*
if (arrayX.includes((0 && 1 && 2) || (3 && 4 && 5) || (6 && 7 && 8) || (0 && 3 && 6) || (1 && 4 && 7) || (2 && 5 && 8) ||
(0 && 4 && 8) || (2 && 4 && 6)) ){
alert('Player X Wins!');
}
*/
/*
if (arrayO.includes(("0" && "1" && "2") || ("3" && "4" && "5") || ("6" && "7" && "8") || ("0" && "3" && "6") ||
("1" && "4" && "7") || ("2" && "5" && "8") || ("0" && "4" && "8") || ("2" && "4" && "6")) ){
alert('Player O Wins!');
}
if (arrayX.includes(("0" && "1" && "2") || ("3" && "4" && "5") || ("6" && "7" && "8") || ("0" && "3" && "6") ||
("1" && "4" && "7") || ("2" && "5" && "8") || ("0" && "4" && "8") || ("2" && "4" && "6")) ){
alert('Player X Wins!');
}
if (arrayO.every)*/
document.querySelector('button').addEventListener('click', (e) => {
document.querySelectorAll('[data-cell]').forEach((div) => {
div.innerHTML = '';
arrayO = [];
arrayX = [];
});
});
});
//try every or sum try creating an object of winning combinations
// if O array contains 012, 345, 678, 036, 147, 258, 048, 246
// if X array contains 012, 345, 678, 036, 147, 258, 048, 246
//https://stackoverflow.com/questions/44348092/retrieving-div-value-to-javascript
|
Markdown
|
UTF-8
| 460
| 2.734375
| 3
|
[] |
no_license
|
<h1>Music App</h1>
<p>Tap Music allows you to play sounds like a keyboard.</p>
<p>To use just click on a colored square and let the sounds fly; literally. Every time you click a color you will see a bubble style animation of the same color fly on the screen. </p>
<p>Check out the video below to see how it works or download and enjoy the sounds.</p>
<img src="https://media.giphy.com/media/3NcpPIoSSUhlktl0mk/giphy.gif"/>
Thanks for checking it out!
|
Java
|
UTF-8
| 230
| 1.625
| 2
|
[] |
no_license
|
package com.tuncay.credit.domain;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode
public class CreditScoreResult {
private String identity_number;
private int credit_score;
}
|
Ruby
|
UTF-8
| 1,753
| 3.59375
| 4
|
[] |
no_license
|
#!/usr/bin/ ruby
# ========= Class Animal =========
class Animal
attr_reader :legs, :sound
attr_writer :type
attr_accessor :name
# static Array
@@history_name = Array.new
# ========= Constructors =========
def initialize(legs = 4, sound = "MmmmKROOOOOOOO", type = "Platypus", name = "Martin")
@legs = legs
@sound = sound
@type = type
@name = name
@@history_name.push(@name)
end
# ========= Methods =========
def speak
puts @sound
end
def to_s
@nb = @@history_name.index(@name)+1
if (@nb == 11 || @nb == 12 || @nb == 13)
"#{@sound}, I am #{@name} of type #{@type} I have 4 legs and I am the #{@@history_name.index(@name)+1} th animal created"
elsif (@nb % 10) == 1
"#{@sound}, I am #{@name} of type #{@type} I have 4 legs and I am the #{@@history_name.index(@name)+1} st animal created"
elsif (@nb % 10) == 2
"#{@sound}, I am #{@name} of type #{@type} I have 4 legs and I am the #{@@history_name.index(@name)+1} nd animal created"
elsif (@nb % 10) == 3
"#{@sound}, I am #{@name} of type #{@type} I have 4 legs and I am the #{@@history_name.index(@name)+1} rd animal created"
else
"#{@sound}, I am #{@name} of type #{@type} I have 4 legs and I am the #{@@history_name.index(@name)+1} th animal created"
end
end
def history
@@history_name
end
end
# Tests
#animal = Animal.new(2, 'Youhou', 'monkey', 'Sambo')
#puts animal
#an = Animal.new(4,'TEST','TEST','TEST')
#puts animal
#puts an
#puts an.history
#puts animal.inspect
#animal.legs = 1
# puts animal.name
# puts animal.legs
# animal.type = "afeuabv"
# puts animal.sound
|
Java
|
UTF-8
| 406
| 1.742188
| 2
|
[] |
no_license
|
package com.paladin.qos.mapper.address;
import com.paladin.qos.model.address.Address;
import com.paladin.qos.service.address.vo.AddressVo;
import com.paladin.qos.service.analysis.data.*;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface AddressMapper {
List<Address> getAddressInfo(@Param("type") Integer type);
Address get(@Param("id") String id);
}
|
Markdown
|
UTF-8
| 10,218
| 2.578125
| 3
|
[
"CC-BY-4.0"
] |
permissive
|
# Ciencia libre con drones
Desde 2017 hemos venido desarrollando un prototipo de kit de herramientas para hacer ciencia abierta con drones, accesible por igual para comunidades marginales, activistas o investigadores, y útil para estudios o relevamientos de datos en los que esta tecnología ya se utiliza pero está dominada por herramientas de código cerrado. Vuela se basa en hardware y software [libres](https://www.gnu.org/philosophy/free-sw.html) disponibles, los que se integran en un proceso abierto, iterativo y colaborativo. Este proyecto ha recibido fondos de Knowledge-Culture-Ecologies/NUMIES, Mozilla Science, PROCISUR y Shuttleworth Foundation.
Enfatizar de igual manera el **[quién](#qui%C3%A9nes)**, el **[por qué](#por-qu%C3%A9)**, y el **[cómo](#c%C3%B3mo)**, tanto como el **[qué](#qu%C3%A9)**, es un aspecto distintivo del proyecto.
### Quiénes
Creemos que personas sin experiencia técnica previa pueden y deben trabajar codo a codo, y como iguales, con quienes poseen experiencia o entrenamiento oficial. Este tipo de colaboración tiene el poder de promover los objetivos de democratizar la ciencia y la tecnología, pero también de mejorar la relevancia, la efectividad y el impacto de éstas en la sociedad.
Los miembros de nuestra ‘tripulación’ son aficionadas, activistas de la sociedad civil, investigadores, vecinos, estudiantes, desarrolladoras, y en los talleres hemos hablado español, criollo haitiano, inglés, francés y portugués. Damos la bienvenida y alentamos la participación de todas y todos, sin importar cómo alguien se identifique o cómo la/lo perciban los demás, siempre y cuando interactúen de manera constructiva y se adhieran al [código de conducta](https://github.com/vuelaendron/vuela/blob/master/CODE_OF_CONDUCT.md#c%C3%B3digo-de-conducta-de-vuela---espa%C3%91ol).

### Por qué
Conseguir instrumental científico no es fácil, menos aún para grupos tales como activistas ambientales o científicas/cos de instituciones con poco presupuesto. Su participación en la ciencia se ve dificultada porque las herramientas que necesitan para levantar datos o hacer mediciones fueron diseñadas para otros contextos, son muy caras y/o no están disponibles en sus territorios. Esto, entre otras cosas, impide el accionar científico a nivel local. Y es importante puesto que la acción local es capaz de enfocarse en los problemas relevantes en un determinado contexto o territorio que la agenda científica global bien podría no llegar a priorizar o simplemente ignorar.
Nuestro proyecto apunta al desarrollo de herramientas científicas que puedan ser útiles a grupos o comunidades que aborden problemas locales, definidos localmente, y así fomentar su participación en la ciencia. Herramientas en línea y comunidades globales están actualmente ayudando a que las tecnologías abiertas sean accesibles, tanto como para quienes están dentro de instituciones ‘de conocimiento’ tradicionales, tales como universidades e institutos de investigación, como para quienes están fuera. Pero aún existen barreras importantes y con Vuela hemos querido abordar algunas de ellas.
Un problema que observamos es el énfasis en el desarrollo de nuevos instrumentos científicos (y en sus ‘inventores’) por sobre la adaptación de instrumentos ya existentes, lo que replica el modelo de proveedores y usuarios/clientes del hardware comercial cerrado. Las definiciones de código abierto se refieren a la capacidad de replicar, modificar, adaptar y redistribuir, pero estos pasos generalmente se dan por sentados y no son particularmente fomentados o estudiados. Queremos comprender qué es necesario para que grupos puedan replicar, modificar, y redistribuir hardware libre. Y si identificamos barreras, intentar abordarlas. Creemos que la ciencia abierta necesita un tipo diferente de ‘usuaria/o’ de herramientas científicas, que no solamente sea una usuaria sino también una colaboradora.
Una de las principales barreras a la participación en estos procesos es el idioma. El inglés es el idioma dominante entre comunidades de tecnología abierta, limitando así el acceso en América Latina, donde solo una minoría, generalmente la más privilegiada, habla este idioma. Por este motivo es que la documentación de Vuela estará en español, haitiano criollo, portugués, francés e inglés. La diversidad lingüística en la región latinoamericana es tremenda ([420 lenguas habladas](https://www.unicef.es/prensa/unicef-presenta-el-atlas-sociolinguistico-de-pueblos-indigenas-en-america-latina)), así es que estamos conscientes de que este sólo es un muy pequeño aporte.
Otro tipo de barreras observadas son aquellas de tipo cultural. El intercambio científico tiende a darse entre actores ligados a la academia, y es el conocimiento producido dentro de ésta el que es considerado como valioso y relevante. Es inusual observar a científicos académicos trabajar a la par de, por ejemplo, grupos de la sociedad civil aquejados por un determinado problema, a pesar de que ambos grupos aborden o estudien exactamente el mismo problema. Reconsiderar quiénes pueden o deben hacer ciencia implica además replantearse qué implica hacer ciencia, dónde se puede hacer, y de qué conocimientos deben ser considerados científicos. El movimiento por la descolonización del conocimiento no es ajeno al hardware científico libre.
Link a una [lista de lecturas](https://docs.google.com/document/d/1k4ZBxsfz7rYyhF1m0xfVF_XYalut5TSyiolKbZMcTcc/edit#) (en Inglés) sobre decolonialismo.

### Qué
Los drones pueden ser una poderosa herramienta para la investigación en disciplinas como la agricultura y las ciencias ambientales, permitiendo la captura de imágenes aéreas con gran flexibilidad. Pero la ciencia abierta requiere instrumentos y materiales abiertos, y los drones no deberían ser una excepción. Con nuestro ‘por qué’ en mente, en lugar de desarrollar una herramienta desde cero, comenzamos este proyecto replicando, probando e identificando posibles mejoras para un dron de código abierto ya disponible llamado ‘Flone’ ([flone.cc](http://flone.cc/)), en una serie de talleres abiertos y colaborativos que comenzamos en 2017.
En los talleres fuimos identificando varias posibles mejoras, modificaciones y adiciones al diseño original del ‘Flone’, necesarios para utilizar el dron con fines de investigación. En un uso ‘típico’ en investigación, un dron necesita poder posicionarse de manera confiable sobre el terreno estudiado y capturar imágenes de alta calidad que luego puedan procesarse para obtener una imagen o mapa de alta resolución del área estudiada. Estas mejoras fueron el objetivo de las actividades del proyecto durante 2018.
Con estas modificaciones el drone terminó siendo bastante diferente al Flone original, y lo llamamos [OVLI](ovli) (Objeto Volador LIbre). Además, trabajamos en identificar otras herramientas de hardware y software libre necesarias, de forma de contar con una [‘caja de herramientas’](toolkit) completa.

### Cómo
Hemos querido desarrollar Vuela a través de un proceso iterativo y colaborativo.
El kit ha sido construido con diversas personas: estudiantes secundarios, científicos tradicionales afiliados a instituciones académicas, periodistas, miembros de comunidades sin formación académica o tecnológica, científicas trabajando en agricultura, niños, adultos, personas con y sin experiencia fabricando o utilizando drones. Inicialmente, e idealmente, queríamos tener en el grupo a personas que ya estuvieran abordando problemas locales, para los cuales los drones podrían ser útiles. Hasta ahora, sin embargo, sólo un grupo trabajó con necesidades específicas en mente: los investigadores en agricultura.
Entre junio de 2017 y enero de 2019 trabajamos con más de 100 personas para arribar a este prototipo en más de 30 talleres locales y presenciales, y también a través de un trabajo permanente en línea utilizando herramientas de colaboración como [GitHub](https://github.com/vuelaendron/vuela). Estamos además desarrollando documentación en diferentes idiomas (inglés, español y criollo haitiano), y en un formato que sea fácil de modificar y traducir. Entre agosto de 2018 y enero de 2019 trabajamos para mejorar el prototipo y ponerlo a prueba para investigación agrícola en 5 países de Sudamérica: Argentina, Brasil, Chile, Paraguay y Uruguay.
{% include vimeo_player.html id=271803564 %}
<p><a href="https://vimeo.com/271803564">Talleres Vuela 2017</a></p>
<video src="https://github.com/vuelaendron/vuela/blob/master/docs/img/talleres_vuela.mp4?raw=true" controls="controls" style="max-width: 480px"></video>
Talleres Vuela 2018-2019
### Más información
Puedes encontrar más información sobre cómo comenzó el proyecto en estas historias:
[Medium](https://medium.com/@PazByC/cr%C3%B3nica-de-un-vuelo-anunciado-fdf3062b1b3e)
[Revista Liinc](http://revista.ibict.br/liinc/article/view/4237)
Y algunas fotos y videos acá:
[Instagram](https://www.instagram.com/sombrerohill/)
[Vimeo](https://vimeo.com/user67511666)
Podés conectarte con nosotros a través del foro: http://foro.vuela.cc/ o por email a vuelaendron@gmail.com
Y aprender cómo construirte tu propio OVLI con la [guía de construcción](https://vuelaendron.github.io/vuela/guia).
### Cómo contribuir
¡Necesitamos mucha ayuda para este proyecto! Por suerte hay muchas maneras de contribuir. Para comenzar, lee el archivo [CONTRIBUTING.md](https://github.com/vuelaendron/vuela/blob/master/CONTRIBUTING.md#c%C3%B3mo-contribuir---espa%C3%91ol) y la [lista de problemas abiertos (issues)](https://github.com/vuelaendron/vuela/issues).
### Normas de participación
Este proyecto se adhiere a un [código de conducta](https://github.com/vuelaendron/vuela/blob/master/CODE_OF_CONDUCT.md#c%C3%B3digo-de-conducta-de-vuela---espa%C3%91ol). Al participar, se espera que cumplas este código. Puedes hacer preguntas o informar conductas inadecuadas a vuelaendron@gmail.com.
|
Python
|
UTF-8
| 970
| 2.5625
| 3
|
[] |
no_license
|
'''
Created on 20 janv. 2017
@author: Adnene
'''
from math import sqrt
#from numba import jit
def outcome_representation_in_reviews(dataset,position_attribute,vector_of_outcome=None,method_aggregation_outcome='VECTOR_VALUES'): #[vector_of_outcome=['attr1,'attr2]]
if vector_of_outcome is None or method_aggregation_outcome=='VECTOR_VALUES':
vector_of_outcome=None
vector_of_actions=tuple(sorted(set(x[position_attribute] for x in dataset)))
#print 'possible Outcomes are : ', vector_of_actions
for x in dataset:
if vector_of_outcome is None :
x[position_attribute]={x[position_attribute]:1.}
else :
vector_of_actions=vector_of_outcome
x[position_attribute]={f:x[f] for f in vector_of_actions}
x[position_attribute]=tuple([x[position_attribute].get(pos,0.) for pos in vector_of_actions])
return dataset
|
C#
|
UTF-8
| 1,478
| 3.640625
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace JaggedArrayModification
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[][] jagged = new int[n][];
for (int i = 0; i < n; i++)
{
int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray();
jagged[i] = input;
}
string[] act = Console.ReadLine().Split();
while (act[0] != "END")
{
int row = int.Parse(act[1]);
int col = int.Parse(act[2]);
int val = int.Parse(act[3]);
if (row >= 0 && row < jagged.Length &&
col >= 0 && col < jagged[row].Length)
{
if (act[0] == "Add")
{
jagged[row][col] += val;
}
else if (act[0] == "Subtract")
{
jagged[row][col] -= val;
}
}
else
{
Console.WriteLine("Invalid coordinates");
}
act = Console.ReadLine().Split();
}
for (int i = 0; i < jagged.Length; i++)
{
Console.WriteLine(string.Join(" ", jagged[i]));
}
}
}
}
|
Python
|
UTF-8
| 2,889
| 3.015625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
"""
Script for summarizing data for statistics generation.
Invocation:
$ python summarize.py data/enriched/*.json -o summary.csv
"""
import argparse
import csv
import json
import os
import sys
from common import write_json_file, progress, read_records
def summarize(data):
artwork_links = 0
if('sameas' in data):
artwork_links = len(data['sameas'])
persons = 0
if('persons' in data):
persons = len([person for person in data['persons']])
links_person_gnd = 0
links_person_dbpedia = 0
links_person_viaf = 0
if('persons' in data):
for person in data['persons']:
if('sameas' in person):
links = [link for link in person['sameas']]
links_person_gnd += len([link for link in links
if 'gnd' in link])
links_person_dbpedia += len([link for link in links
if 'dbpedia' in link])
links_person_viaf += len([link for link in links
if 'viaf' in link])
related_europeana_items = 0
if('related_europeana_items' in data):
related_europeana_items = len(data['related_europeana_items'])
entry = {
'id': data['aleph_id'],
'links_artwork': artwork_links,
'persons': persons,
'links_person_gnd': links_person_gnd,
'links_person_dbpedia': links_person_dbpedia,
'links_person_viaf': links_person_viaf,
'related_europeana_items': related_europeana_items
}
return entry
# Main summarization routine
def summarize_records(inputfiles, outputfile):
print("Summarizing", len(inputfiles), "records in", outputfile)
with open(outputfile, 'w') as csvfile:
fieldnames = ['id',
'links_artwork',
'persons',
'links_person_gnd',
'links_person_dbpedia',
'links_person_viaf',
'related_europeana_items']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for filename, record in read_records(inputfiles):
data = json.loads(record)
entry = summarize(data)
writer.writerow(entry)
# Command line parsing
parser = argparse.ArgumentParser(
description="Collecting data for dataset statistics.")
parser.add_argument('inputfiles', type=str, nargs='+',
help="Input files to be processed")
parser.add_argument('-o', '--outputfile', type=str, nargs='?',
default="data/summary.csv",
help="Output file")
if len(sys.argv) < 2:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
summarize_records(args.inputfiles, args.outputfile)
|
Python
|
UTF-8
| 1,772
| 3.859375
| 4
|
[] |
no_license
|
from random import randint
import copy
class Player(object):
def __init__(self, name, symbol):
self.name_str = name
self.symbol = symbol
def prompt_move(self):
return (0, self.symbol)
# to string method
def __str__(self):
return "{0} ({1})".format(self.name_str, self.symbol)
class HumanPlayer(Player):
# Make a move
def prompt_move(self):
print "{}'s move".format(self)
col = raw_input("Col #:")
return (int(col), self.symbol)
class ComputerPlayer(Player):
def __init__(self, name, symbol, opp_symbol, board):
Player.__init__(self, name, symbol)
self.board = board
self.opp_symbol = opp_symbol
# Computer plays randomly unless it sees potential win or loss on
# following turn
def prompt_move(self):
move = (randint(0, self.board.m - 1), self.symbol)
# try all possible next moves using both player's symbols
# First try all computer moves to see if possible win
possible_win = False
for i in xrange(self.board.m):
future_board = copy.deepcopy(self.board)
future_board.accepts_move((i, self.symbol))
if future_board.has_winner():
move = (i, self.symbol)
break
# Then try all human moves to see if possible loss
if not possible_win:
for i in xrange(self.board.m):
future_board = copy.deepcopy(self.board)
future_board.accepts_move((i, self.opp_symbol))
if future_board.has_winner():
move = (i, self.symbol)
break
print "{}'s move".format(self)
print "Col #: {}".format(move[0])
return move
|
Go
|
UTF-8
| 1,931
| 3.609375
| 4
|
[
"MIT"
] |
permissive
|
package reader
import (
"encoding/binary"
"io"
)
// LittleEndianReader is a wrapper around `bytes.Reader` with respect towards
// handling little endian byte streams
type LittleEndianReader struct {
base
}
// CreateLittleEndianReader wraps an io.Reader with logic to read little-endian
// byte content. Operations in the reader are relative to the provided
// baseOffset.
func CreateLittleEndianReader(r io.ReadSeeker, baseOffset int64) *LittleEndianReader {
return &LittleEndianReader{
base: base{r, baseOffset},
}
}
// ReadUint8FromUint32 reads uint8s off the provided uint32, up to a maximum of
// count
func (r *LittleEndianReader) ReadUint8FromUint32(count, data uint32) ([]uint32, error) {
result := make([]uint32, count)
result[0] = data & 0xff000000 >> 24
if count > 1 {
result[1] = data & 0xff0000 >> 16
if count > 2 {
result[2] = data & 0xff00 >> 8
if count > 3 {
result[3] = data & 0xff
}
}
}
return result, nil
}
// ReadUint16 reads 16 bits of unsigned data
func (r *LittleEndianReader) ReadUint16() (uint16, error) {
t, err := readBytes(r.r, 2)
if err != nil {
return 0, err
}
return binary.LittleEndian.Uint16(t), nil
}
// ReadUint16FromUint32 reads uint16s off the provided uint32, up to a maximum
// of count
func (r *LittleEndianReader) ReadUint16FromUint32(count, data uint32) ([]uint32, error) {
result := make([]uint32, count)
result[0] = data & 0xffff0000 >> 16
if count > 1 {
result[1] = data & 0xffff
}
return result, nil
}
// ReadUint32 reads 32 bits of unsigned data
func (r *LittleEndianReader) ReadUint32() (uint32, error) {
t, err := readBytes(r.r, 4)
if err != nil {
return 0, err
}
return binary.LittleEndian.Uint32(t), nil
}
// ReadUint64 reads 64 bits of unsigned data
func (r *LittleEndianReader) ReadUint64() (uint64, error) {
t, err := readBytes(r.r, 8)
if err != nil {
return 0, err
}
return binary.LittleEndian.Uint64(t), nil
}
|
Markdown
|
UTF-8
| 2,408
| 4.15625
| 4
|
[] |
no_license
|
null是JavaScript语言的关键字,它表示一个特殊值,常用来描述“空值”。对null执行typeof预算,结果返回字符串"object",也就是说,可以将null认为是一个特殊的对象值,含义是“非对象”。但实际上,通常认为null是它自有类型的唯一一个成员,它可以表示数字、字符串和对象是“无值”的。大多数编程语言和JavaScript一样含有null:你可能对null或nil很眼熟。
```js
var res = null;
document.write(typeof (res));//object
```
JavaScript还有第二个值来表示值的空缺。用未定义的值表示更深层次的“空值”。它是变量的一种取值,表明变量没有初始化,
1. 如果要查询对象属性或数组元素的值时返回undefined则说明这个属性或元素不存在。
2. <font color="red">如果函数没有返回任何值,则返回undefined</font>。
3. 引用没有提供实参的函数形参的值也只会得到undefined。
undefined是预定义的全局变量(它和null不一样,它不是关键字),它的值就是“<font color="red">未定义</font>”。在ECMAScript 3中,undefined是可读/写的变量,可以给它赋任意值。这个错误在ECMAScript 5中做了修正,undefined在该版本中是只读的。如果使用typeof运算符得到undefined的类型,则返回"undefined",表明这个值是这个类型的唯一成员。
<font color="red">尽管null和undefined是不同的,但它们都表示“值的空缺”,两者往往可以互换。判断相等运算符“==”认为两者是相等的(要使用严格相等运算符“===”来区分它们)</font>
```js
var res = null;
var res1;
document.write(res == res1); //true
document.write(res === res1); //false
// document.write(typeof (res));//object
```
在希望值是布尔类型的地方它们的值都是假值,和false类似。<font color="red">null和undefined都不包含任何属性和方法</font>。实际上,使用“.”和“[]”来存取这两个值的成员或方法都会产生一个类型错误。你或许认为undefined是表示系统级的、出乎意料的或类似错误的值的空缺,而null是表示程序级的、正常的或在意料之中的值的空缺。<font color="red">如果你想将它们赋值给变量或者属性,或将它们作为参数传入函数,最佳选择是使用null</font>。
|
Java
|
UTF-8
| 1,207
| 2.515625
| 3
|
[] |
no_license
|
package nitinka.quartzrest.domain;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import java.util.List;
/**
* Wrapper Around Job Details exposed by quartz
*/
public class RunTimeJobDetail {
private JobDetail jobDetail;
private List<? extends Trigger> triggers;
public JobDetail getJobDetail() {
return jobDetail;
}
public RunTimeJobDetail setJobDetail(JobDetail jobDetail) {
this.jobDetail = jobDetail;
return this;
}
public List<? extends Trigger> getTriggers() {
return triggers;
}
public RunTimeJobDetail setTriggers(List<? extends Trigger> triggers) {
this.triggers = triggers;
return this;
}
public String getJobId() {
return jobDetail.getKey().getGroup() + "." + jobDetail.getKey().getName();
}
public Trigger getTrigger(String triggerGroup, String triggerName) {
if (triggers != null) {
for (Trigger trigger : triggers) {
if (trigger.getKey().getGroup().equals(triggerGroup) && trigger.getKey().getName().equals(triggerName)) {
return trigger;
}
}
}
return null;
}
}
|
C++
|
UTF-8
| 1,724
| 3.265625
| 3
|
[] |
no_license
|
/*
* Reference.cpp
*
* Created on: 26.12.2019
* Author: Marcin
*/
#include "Reference.h"
Reference::Reference(float midValue, float calculationLimit, float referenceDeviationLimit, uint32_t stableSamples) :
midValue(midValue),
calculationLimit(calculationLimit),
referenceDeviationLimit(referenceDeviationLimit),
stableSamples(stableSamples)
{
referenceValue = midValue;
}
// calculates reference according to input values
void Reference::calculateReference(float inputValue)
{
if ((inputValue > midValue - calculationLimit) &&
(inputValue < midValue + calculationLimit))
{
// input value in the allowed range of reference value
if (++noOfAveragedSamples == 1)
{
// the first valid sample
averageValue = inputValue;
}
if (fabs(inputValue - averageValue) < referenceDeviationLimit)
{
// input value in allowed deviation range
averageValue = (averageValue * (noOfAveragedSamples - 1) + inputValue) / noOfAveragedSamples;
}
else
{
// input value out of allowed deviation range
noOfAveragedSamples = 0;
}
if (noOfAveragedSamples > stableSamples) // sufficient number of stable samples within limit
{
referenceValue = averageValue;
if(noOfAveragedSamples > stableSamples * 10)
{
// recalculate reference value after some time
noOfAveragedSamples = 0;
}
}
}
else
{
// input value out of allowed range
noOfAveragedSamples = 0;
}
}
|
Markdown
|
UTF-8
| 3,558
| 2.625
| 3
|
[] |
no_license
|
GCJ: Java без JVM
======
Да, именно так: Java без JVM. В данной статье рассмотрим работу с Java (компиляция/запуск), не используя такие средства, как JVM/JDK и подобное. Ах да, и никаких on-line инструментов, все только локально :) А воспользуемся мы таким инструментом, как GCJ:
> GNU Compiler for Java (GCJ или gcj) — это свободный компилятор языка Java, являющийся частью GNU Compiler Collection. GCJ может компилировать исходный код Java в байткод виртуальной машины Java, либо непосредственно в машинный код многих процессорных архитектур. Он также может компилировать файлы классов, содержащие байткод, или целые JAR, содержащие такие файлы, в машинный код.
### Установка
В unix-системах достаточно выполнить команду установки пакета `apt-get`:
```bash
$ sudo apt-get install gcj-jdk
```
В результате будет скачано и установлено около десяти мегабайт ресурсов. После чего инструмент готов к использованию.
### Использование
Пишем Java код, компилируем в бинарник и запускаем:
```bash
asaskevich@asaskevich-U31SD:~$ cat > Test.java
public class Test {
public static void main(String[] args) {
System.out.println("Hi from gcj!");
}
}
^C
asaskevich@asaskevich-U31SD:~$ gcj --main=Test Test.java
asaskevich@asaskevich-U31SD:~$ ./a.out
Hi from gcj!
```
Строка `--main=Test` говорит о том, что точка входа в приложение находится в классе `Test`.
### Плюсы
* Не требует установки JVM для запуска
* Только машинный код
* Преобразует в машинный код файлы типа `*.java *.jar *.class`
* Приложение запускается быстрее, чем через JVM
### Минусы
* Код исполняется не всегда быстрее, чем байт-код в JVM
* Размер выходного файла обычно больше аналогичного `*.class` файла
* Применение бинарника ограничено платформой, для которой файл был скомпилирован
### Заключение
Конечно, плюсов и минусов может быть больше - я лишь поверхностно рассмотрел данный вопрос. Использовать JVM/JDK все же привычнее, но не стоит упускать из вида и данный инструмент - например, если вдруг придется писать приложение для устройства, ограниченного в ресурсах, а для этих целей хочется использовать язык, который знаешь лучше всего (в данном случае Java).
### Ссылки
* [Документация GCJ](https://gcc.gnu.org/onlinedocs/gcj/index.html)
* [Содержание](README.md)
|
C
|
UTF-8
| 238
| 3.09375
| 3
|
[] |
no_license
|
#include<stdio.h>
void sankaku(int);
int main(void)
{
sankaku(2);
sankaku(3);
sankaku(4);
sankaku(5);
return 0;
}
void sankaku(int M)
{
int i,j;
for(i=1;i<=M;i++){
for(j=1;j<=i;j++){
printf("*");
}
printf("\n");
}
}
|
Java
|
UTF-8
| 178
| 2.046875
| 2
|
[] |
no_license
|
package io.github.sweehaw.utils;
/**
* @author sweehaw
*/
public class CommUtils {
public static String trim(String s) {
return s != null ? s.trim() : s;
}
}
|
Java
|
UTF-8
| 4,096
| 2.203125
| 2
|
[] |
no_license
|
package wdm.tpe;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import wdm.match.Match;
import wdm.matcher.MatcherOpt;
import wdm.util.Pair;
import wdm.xml.XMLNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class StackEval extends DefaultHandler {
private TPEStack rootStack;
int currentPre;
Stack<XMLNode> preOfOpenNodes;
List<Match> result;
public StackEval(TPEStack rootStack) {
this.rootStack = rootStack;
this.preOfOpenNodes = new Stack<>();
this.currentPre = 0;
this.result = new LinkedList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
List<Pair<String, String>> attributePairs = new ArrayList<>(attributes.getLength());
for(int i = 0 ; i < attributes.getLength() ; i++){
attributePairs.add(Pair.create(attributes.getQName(i), attributes.getValue(i)));
}
XMLNode currentNode = new XMLNode(currentPre, qName, attributePairs);
if(!preOfOpenNodes.isEmpty()) {
preOfOpenNodes.peek().addChild(currentNode);
}
preOfOpenNodes.push(currentNode);
for (TPEStack s : rootStack.getDescendantStacks()) {
if (s.isMatch(qName) && s.parentHasMatch()) {
s.createMatch(currentPre, qName);
}
}
for (int i = 0; i < attributes.getLength(); i++) {
for (TPEStack s : rootStack.getDescendantStacks()) {
if (s.isMatch(attributes.getQName(i)) && s.parentHasMatch() && (s instanceof TPEStackAttribute) && s.matcher.postMatch(attributes.getQName(i), attributes.getValue(i))) {
Match m = s.createMatch(currentPre, qName);
m.setContent(attributes.getValue(i));
}
}
}
currentPre++;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
XMLNode preOfLastOpen = preOfOpenNodes.pop();
for(TPEStack s : rootStack.getDescendantStacks()){
if (s.isMatch(qName) && s.hasOpenMatch(preOfLastOpen.getIndex())){
Match m = s.top();
m.setContent(preOfLastOpen.getText());
m.setXml(preOfLastOpen);
for (TPEStack pChild : s.getChildren()){
if(!m.getChildren().containsKey(pChild)) {
if(!pChild.isOptional()) {
if (m.getParent() != null) {
m.getParent().removeChild(s, m.getStart());
}
} else {
pChild.createMatch(MatcherOpt.MATCH_FAILED, ((MatcherOpt)pChild.getMatcher()).getInnerMatcher().toString());
pChild.pop();
}
}
}
if(!s.matcher.postMatch(m.getLabel(), preOfLastOpen.getText().trim())) {
if (s.getParent() != null) {
m.getParent().removeChild(s, m.getStart());
}
} else if (m.getParent() == null && m.getChildren().size() >= s.getChildren().size()) {
result.add(m);
}
m.close();
s.pop();
}
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException{
preOfOpenNodes.peek().appendText(new String(ch, start, length));
}
public List<Match> evaluate(ParseFunc func) throws IOException, SAXException{
func.apply(this);
List<Match> result = this.result;
this.result = new LinkedList<>();
return result;
}
@FunctionalInterface
public static interface ParseFunc{
void apply(DefaultHandler handler) throws SAXException, IOException;
}
}
|
C++
|
UTF-8
| 52,698
| 2.796875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include "stdafx.h"
#include "CppUnitTest.h"
#include <util/common/geom/polygon.h>
#include <array>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
template<> static std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString<geom::point2d_t> (const geom::point2d_t & p) { RETURN_WIDE_STRING(p); }
namespace geom
{
using arr4_t = std::array < point2d_t, 4 > ;
using vect_t = std::vector < point2d_t > ;
static const arr4_t points =
{
{ { 2, 2 }, { 3, 3 }, { 2, 4 }, { 1, 3 } }
};
TEST_CLASS(polygon_test)
{
public:
BEGIN_TEST_METHOD_ATTRIBUTE(_factory)
TEST_DESCRIPTION(L"factory and constructor works fine")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_factory)
{
auto p = make_polygon(points); // array
auto p2 = polygon < > (std::vector < point2d_t > (points.begin(), points.end())); // vector
Assert::AreEqual(points[0], p.points[0], L"p1[0]", LINE_INFO());
Assert::AreEqual(points[1], p.points[1], L"p1[1]", LINE_INFO());
Assert::AreEqual(points[2], p.points[2], L"p1[2]", LINE_INFO());
Assert::AreEqual(points[3], p.points[3], L"p1[3]", LINE_INFO());
Assert::AreEqual(points[0], p2.points[0], L"p2[0]", LINE_INFO());
Assert::AreEqual(points[1], p2.points[1], L"p2[1]", LINE_INFO());
Assert::AreEqual(points[2], p2.points[2], L"p2[2]", LINE_INFO());
Assert::AreEqual(points[3], p2.points[3], L"p2[3]", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_equality)
TEST_DESCRIPTION(L"equality checking works fine")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_equality)
{
auto p1 = make_polygon < arr4_t > ({ { { 2, 2 }, { 3, 3 }, { 2, 4 }, { 1, 3 } } });
auto p2 = make_polygon < arr4_t > ({ { { 2, 2 }, { 3, 3 }, { 2, 4 }, { 1, 3 } } });
auto p3 = make_polygon < arr4_t > ({ { { 1, 2 }, { 3, 3 }, { 2, 4 }, { 1, 3 } } });
auto p4 = make_polygon < arr4_t > ({ { { 2, 2 }, { 1, 3 }, { 2, 4 }, { 1, 3 } } });
auto p5 = make_polygon < arr4_t > ({ { { 2, 2 }, { 3, 3 }, { 1, 4 }, { 1, 3 } } });
auto p6 = make_polygon < arr4_t > ({ { { 2, 2 }, { 3, 3 }, { 2, 4 }, { 1, 1 } } });
Assert::IsTrue(p1 == p2, L"p1 == p2", LINE_INFO());
Assert::IsFalse(p1 != p2, L"p1 != p2", LINE_INFO());
Assert::IsTrue(p1 != p3, L"p1 != p3", LINE_INFO());
Assert::IsFalse(p1 == p3, L"p1 == p3", LINE_INFO());
Assert::IsTrue(p1 != p4, L"p1 != p4", LINE_INFO());
Assert::IsFalse(p1 == p4, L"p1 == p4", LINE_INFO());
Assert::IsTrue(p1 != p5, L"p1 != p5", LINE_INFO());
Assert::IsFalse(p1 == p5, L"p1 == p5", LINE_INFO());
Assert::IsTrue(p1 != p6, L"p1 != p6", LINE_INFO());
Assert::IsFalse(p1 == p6, L"p1 == p6", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_empty)
TEST_DESCRIPTION(L"empty check is correct")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_empty)
{
Assert::IsFalse(make_polygon(points).empty(),
L"non-empty", LINE_INFO());
Assert::IsFalse(make_polygon < arr4_t > ({}).empty(),
L"empty", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_intersection_with_line)
TEST_DESCRIPTION(L"intersection with line calculation is correct")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_intersection_with_line)
{
auto p1 = make_polygon < vect_t > ({ { { 2, 2 }, { 3, 3 }, { 2, 4 }, { 1, 3 } } });
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(make_line(1, 2, 3, 4)), L"p1 - l1", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(make_line(2, 3, 3, 4)), L"p1 - l2", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(make_line(4, 1, 5, 2)), L"p1 - l3", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(make_line(2, 0, 2, 1)), L"p1 - l4", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(make_line(3, 2, 3, 5)), L"p1 - l5", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(make_line(1, 2, 1, 5)), L"p1 - l6", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(make_line(2.999, 2, 2.999, 5)), L"p1 - l7", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(make_line(2, 1, 2, 5)), L"p1 - l8", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects) | status::polygon::edge_contains_point,
p1.intersects(make_line(2, 2, 2, 5)), L"p1 - l9", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(make_line(2, 3, 2, 5)), L"p1 - l10", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::touches_line) | status::polygon::edge_contains_point,
p1.intersects(make_line(2, 4, 2, 5)), L"p1 - l11", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line) | status::polygon::contains_line,
p1.intersects(make_line(1, 1, 4, 4)), L"p1 - l12", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line) | status::polygon::contains_line | status::polygon::edge_contains_point,
p1.intersects(make_line(2, 2, 4, 4)), L"p1 - l13", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line | status::polygon::touches_line) | status::polygon::edge_contains_point,
p1.intersects(make_line(3, 3, 4, 4)), L"p1 - l14", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_line) | status::polygon::edge_contains_point,
p1.intersects(make_line(2, 2, 2, 3)), L"p1 - l15", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_line | status::polygon::edge_contains_point),
p1.intersects(make_line(1.5, 2.5, 2, 3)), L"p1 - l16", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_line | status::polygon::edge_contains_both),
p1.intersects(make_line(1.5, 2.5, 2.5, 3.5)), L"p1 - l17", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::edge_contains_both | status::polygon::coincides_with_line) | status::polygon::contains_line,
p1.intersects(make_line(2.25, 2.25, 2.75, 2.75)), L"p1 - l18", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line) | status::polygon::edge_contains_both | status::polygon::contains_line,
p1.intersects(make_line(2, 2, 3, 3)), L"p1 - l19", LINE_INFO());
auto p2 = make_polygon < vect_t > ({ { { 2, 2 }, { 2.5, 2.5 }, { 3, 3 }, { 2.5, 3.5 }, { 2, 4 }, { 1.5, 3.5 }, { 1, 3 }, { 1.5, 2.5 } } });
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p2.intersects(make_line(1, 2, 3, 4)), L"p2 - l1", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p2.intersects(make_line(2, 3, 3, 4)), L"p2 - l2", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p2.intersects(make_line(4, 1, 5, 2)), L"p2 - l3", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p2.intersects(make_line(2, 0, 2, 1)), L"p2 - l4", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p2.intersects(make_line(3, 2, 3, 5)), L"p2 - l5", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p2.intersects(make_line(1, 2, 1, 5)), L"p2 - l6", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p2.intersects(make_line(2.999, 2, 2.999, 5)), L"p2 - l7", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p2.intersects(make_line(2, 1, 2, 5)), L"p2 - l8", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects) | status::polygon::edge_contains_point,
p2.intersects(make_line(2, 2, 2, 5)), L"p2 - l9", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p2.intersects(make_line(2, 3, 2, 5)), L"p2 - l10", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::touches_line) | status::polygon::edge_contains_point,
p2.intersects(make_line(2, 4, 2, 5)), L"p2 - l11", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line) | status::polygon::contains_line,
p2.intersects(make_line(1, 1, 4, 4)), L"p2 - l12", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line) | status::polygon::contains_line | status::polygon::edge_contains_point,
p2.intersects(make_line(2, 2, 4, 4)), L"p2 - l13", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line | status::polygon::touches_line) | status::polygon::edge_contains_point,
p2.intersects(make_line(3, 3, 4, 4)), L"p2 - l14", LINE_INFO());
auto p3 = make_polygon < vect_t > ({ { { 2, 2 }, { 2.25, 2.25 }, { 3, 2 }, { 2.75, 2.75 }, { 3, 3 }, { 2, 4 }, { 1, 3 } } });
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p3.intersects(make_line(1, 2, 3, 4)), L"p3 - l1", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p3.intersects(make_line(2, 3, 3, 4)), L"p3 - l2", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p3.intersects(make_line(4, 1, 5, 2)), L"p3 - l3", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p3.intersects(make_line(2, 0, 2, 1)), L"p3 - l4", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok) | status::polygon::edge_contains_point,
p3.intersects(make_line(3, 2, 3, 5)), L"p3 - l5", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p3.intersects(make_line(1, 2, 1, 5)), L"p3 - l6", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p3.intersects(make_line(2.999, 2, 2.999, 5)), L"p3 - l7", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p3.intersects(make_line(2, 1, 2, 5)), L"p3 - l8", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects) | status::polygon::edge_contains_point,
p3.intersects(make_line(2, 2, 2, 5)), L"p3 - l9", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p3.intersects(make_line(2, 3, 2, 5)), L"p3 - l10", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::touches_line) | status::polygon::edge_contains_point,
p3.intersects(make_line(2, 4, 2, 5)), L"p3 - l11", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p3.intersects(make_line(1, 1, 4, 4)), L"p3 - l12", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects) | status::polygon::edge_contains_point,
p3.intersects(make_line(2, 2, 4, 4)), L"p3 - l13", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line | status::polygon::touches_line) | status::polygon::edge_contains_point,
p3.intersects(make_line(3, 3, 4, 4)), L"p3 - l14", LINE_INFO());
auto p4 = make_polygon < vect_t > ({ { { 0, 0 }, { 7, 0 }, { 7, 3 }, { 0, 3 }, { 0, 2 }, { 6, 2 }, { 6, 1 }, { 0, 1 } } });
Assert::AreEqual(status::trusted(status::ok | status::polygon::touches_line | status::polygon::edge_contains_both),
p4.intersects(make_line(1, 2, 1, 1)), L"p4 - l1", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line | status::polygon::touches_line) | status::polygon::edge_contains_both,
p4.intersects(make_line(0, 2, 0, 1)), L"p4 - l2", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line) | status::polygon::contains_line | status::polygon::edge_contains_both,
p4.intersects(make_line(0, 3, 0, 0)), L"p4 - l3", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_intersection)
TEST_DESCRIPTION(L"intersection calculation is correct")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_intersection)
{
auto p1 = make_polygon < arr4_t > ({ { { 2, 2 }, { 3, 3 }, { 2, 4 }, { 1, 3 } } });
auto p2 = make_polygon < arr4_t > ({ { { 2, 1 }, { 3, 2 }, { 2, 3 }, { 1, 2 } } });
auto p3 = make_polygon < arr4_t > ({ { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } } });
auto p4 = make_polygon < arr4_t > ({ { { 3, 1 }, { 3, 3 }, { 1, 3 }, { 1, 1 } } });
auto p5 = make_polygon < arr4_t > ({ { { 1, 1 }, { 2, 2 }, { 1, 3 }, { 0, 2 } } });
auto p6 = make_polygon < vect_t > ({ { { 0, 0 }, { 7, 0 }, { 7, 3 }, { 0, 3 }, { 0, 2 }, { 6, 2 }, { 6, 1 }, { 0, 1 } } });
auto p7 = make_polygon < arr4_t > ({ { { 1, 1 }, { 2, 1 }, { 2, 2 }, { 1, 2 } } }); // move(p3, { 1, 1 });
auto p8 = make_polygon < arr4_t > ({ { { 0, 1 }, { 1, 1 }, { 1, 2 }, { 0, 2 } } }); // move(p3, { 0, 1 });
auto p9 = make_polygon < arr4_t > ({ { { 6, 0 }, { 7, 0 }, { 7, 1 }, { 6, 1 } } }); // move(p3, { 6, 1 });
auto p10 = make_polygon < arr4_t > ({ { { 6, 2 }, { 7, 2 }, { 7, 3 }, { 6, 3 } } }); // move(p3, { 6, 2 });
auto p11 = make_polygon < arr4_t > ({ { { 6.25, 2.25 }, { 6.75, 2.25 }, { 6.75, 2.75 }, { 6.25, 2.75 } } }); // scale(move(p3, { 6, 2 }), 0.5, { 6.5, 2.5 });
auto p12 = make_polygon < arr4_t > ({ { { 1.25, 1.25 }, { 1.75, 1.25 }, { 1.75, 1.75 }, { 1.25, 1.75 } } }); // scale(move(p3, { 1, 1 }), 0.5, { 1.5, 1.5 });
auto l1 = make_line(1, 2, 3, 4);
auto l2 = make_line(2, 3, 3, 4);
auto l3 = make_line(4, 1, 5, 2);
auto l4 = make_line(2, 0, 2, 1);
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(l1), L"p1 - l1 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(l2), L"p1 - l2 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(l3), L"p1 - l3 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(l4), L"p1 - l4 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(make_line(3, 2, 3, 5)), L"p1 - l5 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(make_line(1, 2, 1, 5)), L"p1 - l6 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(make_line(2.999, 2, 2.999, 5)), L"p1 - l7 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(make_line(2, 1, 2, 5)), L"p1 - l8 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects) | status::polygon::edge_contains_point,
p1.intersects(make_line(2, 2, 2, 5)), L"p1 - l9 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(make_line(2, 3, 2, 5)), L"p1 - l10 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::touches_line) | status::polygon::edge_contains_point,
p1.intersects(make_line(2, 4, 2, 5)), L"p1 - l11 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line) | status::polygon::contains_line,
p1.intersects(make_line(1, 1, 4, 4)), L"p1 - l11 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line) | status::polygon::contains_line | status::polygon::edge_contains_point,
p1.intersects(make_line(2, 2, 4, 4)), L"p1 - l12 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_line | status::polygon::touches_line) | status::polygon::edge_contains_point,
p1.intersects(make_line(3, 3, 4, 4)), L"p1 - l13 int", LINE_INFO());
auto i = p1.intersections(l1);
Assert::AreEqual(size_t(2), i.size(), L"p1 - l1", LINE_INFO());
// counterclockwise polygon side iteration
Assert::AreEqual(2.5, i[0].x, 1e-8, L"p1 - l1 x1", LINE_INFO());
Assert::AreEqual(3.5, i[0].y, 1e-8, L"p1 - l1 y1", LINE_INFO());
Assert::AreEqual(1.5, i[1].x, 1e-8, L"p1 - l1 x2", LINE_INFO());
Assert::AreEqual(2.5, i[1].y, 1e-8, L"p1 - l1 y2", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(l1), L"p1 - l1 int", LINE_INFO());
i = p1.intersections(l2);
Assert::AreEqual(size_t(1), i.size(), L"p1 - l2", LINE_INFO());
Assert::AreEqual(2.5, i[0].x, 1e-8, L"p1 - l2 x", LINE_INFO());
Assert::AreEqual(3.5, i[0].y, 1e-8, L"p1 - l2 y", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(l2), L"p1 - l2 int", LINE_INFO());
i = p1.intersections(l3);
Assert::AreEqual(size_t(0), i.size(), L"p1 - l3", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(l3), L"p1 - l3 int", LINE_INFO());
i = p1.intersections(l4);
Assert::AreEqual(size_t(0), i.size(), L"p1 - l4", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(l4), L"p1 - l4 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(p2), L"p1 - p2 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.intersects(p3), L"p1 - p3 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::intersects),
p1.intersects(p4), L"p1 - p4 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_polygon),
p1.intersects(p5), L"p1 - p5 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_polygon),
p1.intersects(p1), L"p1 - p1 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_polygon),
p6.intersects(p7), L"p6 - p7 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_polygon),
p6.intersects(p8), L"p6 - p8 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_polygon | status::polygon::contains_polygon),
p6.intersects(p9), L"p6 - p9 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_polygon | status::polygon::contains_polygon),
p6.intersects(p9), L"p6 - p9 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_polygon | status::polygon::contains_polygon),
p6.intersects(p10), L"p6 - p10 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::coincides_with_polygon | status::polygon::contains_polygon),
p6.intersects(p3), L"p6 - p3 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_polygon),
p6.intersects(p11), L"p6 - p11 int", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p6.intersects(p12), L"p6 - p12 int", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_convex)
TEST_DESCRIPTION(L"convexity calculation is correct")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_convex)
{
auto p0 = polygon < > ();
p0.points.emplace_back(2, 2);
p0.points.emplace_back(3, 3);
p0.points.emplace_back(2, 4);
auto p1 = polygon < > ();
p1.points.emplace_back(2, 2);
p1.points.emplace_back(3, 3);
p1.points.emplace_back(2, 4);
p1.points.emplace_back(1, 3);
auto p2 = polygon < > ();
p2.points.emplace_back(2.5, 2.5);
p2.points.emplace_back(3, 3);
p2.points.emplace_back(2, 4);
p2.points.emplace_back(1, 3);
p2.points.emplace_back(1.5, 2.5);
p2.points.emplace_back(2, 3);
auto p3 = p2;
p3.points.back() = { 2, 0 };
auto p4 = p1;
std::reverse(p4.points.begin(), p4.points.end());
auto p5 = p3;
std::reverse(p5.points.begin(), p5.points.end());
auto p6 = p0;
std::reverse(p6.points.begin(), p6.points.end());
Assert::IsTrue(p0.is_convex(), L"p0", LINE_INFO());
Assert::IsTrue(p0.convexity() == convex_type::counterclockwise, L"p0 c", LINE_INFO());
Assert::IsTrue(p1.is_convex(), L"p1", LINE_INFO());
Assert::IsTrue(p1.convexity() == convex_type::counterclockwise, L"p1 c", LINE_INFO());
Assert::IsFalse(p2.is_convex(), L"p2", LINE_INFO());
Assert::IsTrue(p2.convexity() == convex_type::no, L"p2 c", LINE_INFO());
Assert::IsFalse(p3.is_convex(), L"p3", LINE_INFO());
Assert::IsTrue(p3.convexity() == convex_type::no, L"p3 c", LINE_INFO());
Assert::IsTrue(p4.is_convex(), L"p4", LINE_INFO());
Assert::IsTrue(p4.convexity() == convex_type::clockwise, L"p4 c", LINE_INFO());
Assert::IsFalse(p5.is_convex(), L"p5", LINE_INFO());
Assert::IsTrue(p5.convexity() == convex_type::no, L"p5 c", LINE_INFO());
Assert::IsTrue(p6.is_convex(), L"p6", LINE_INFO());
Assert::IsTrue(p6.convexity() == convex_type::clockwise, L"p6 c", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_convex_special_cases)
TEST_DESCRIPTION(L"convexity calculation is correct - special cases")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_convex_special_cases)
{
auto p0 = polygon < > ();
Assert::IsFalse(p0.is_convex(), L"p0", LINE_INFO());
Assert::IsTrue(p0.convexity() == convex_type::degenerate, L"p0 c", LINE_INFO());
auto p1 = polygon < > ();
p1.points.emplace_back(2, 2);
p1.points.emplace_back(3, 3);
Assert::IsFalse(p1.is_convex(), L"p1", LINE_INFO());
Assert::IsTrue(p1.convexity() == convex_type::degenerate, L"p1 c", LINE_INFO());
auto p2 = p1;
p2.points.emplace_back(3, 3);
Assert::IsFalse(p2.is_convex(), L"p2", LINE_INFO());
Assert::IsTrue(p2.convexity() == convex_type::degenerate, L"p2 c", LINE_INFO());
auto p3 = p1;
p3.points.emplace_back(2.5, 2.5);
Assert::IsFalse(p3.is_convex(), L"p3", LINE_INFO());
Assert::IsTrue(p3.convexity() == convex_type::degenerate, L"p3 c", LINE_INFO());
auto p32 = polygon < > ();
p32.points.emplace_back(2, 2);
p32.points.emplace_back(2.5, 2.5);
p32.points.emplace_back(3, 3);
Assert::IsFalse(p32.is_convex(), L"p32", LINE_INFO());
Assert::IsTrue(p32.convexity() == convex_type::degenerate, L"p32 c", LINE_INFO());
auto p4 = p1;
p4.points.emplace_back(2.5, 2.5 + 1e-12);
Assert::IsFalse(p4.is_convex(), L"p4", LINE_INFO());
Assert::IsTrue(p4.convexity() == convex_type::degenerate, L"p4 c", LINE_INFO());
auto p5 = p1;
p5.points.emplace_back(2.5, 2.5 - 1e-12);
Assert::IsFalse(p5.is_convex(), L"p5", LINE_INFO());
Assert::IsTrue(p5.convexity() == convex_type::degenerate, L"p5 c", LINE_INFO());
auto p6 = polygon < > ();
p6.points.emplace_back(2, 2);
p6.points.emplace_back(2, 2);
p6.points.emplace_back(3, 3);
p6.points.emplace_back(3, 3);
p6.points.emplace_back(2, 4);
p6.points.emplace_back(2, 4);
p6.points.emplace_back(2, 4);
p6.points.emplace_back(2, 2);
Assert::IsTrue(p6.is_convex(), L"p6", LINE_INFO());
Assert::IsTrue(p6.convexity() == convex_type::counterclockwise, L"p6 c", LINE_INFO());
auto p7 = polygon < > ();
p7.points.emplace_back(2, 2);
p7.points.emplace_back(2, 2 + 1e-12);
p7.points.emplace_back(3 - 1e-12, 3);
p7.points.emplace_back(3, 3 + 1e-12);
p7.points.emplace_back(2, 4);
p7.points.emplace_back(2 + 1e-12, 4);
p7.points.emplace_back(2, 4 - 1e-12);
p7.points.emplace_back(2 - 1e-12, 2 + 1e-12);
Assert::IsTrue(p7.is_convex(), L"p7", LINE_INFO());
Assert::IsTrue(p7.convexity() == convex_type::counterclockwise, L"p7 c", LINE_INFO());
auto p8 = polygon < > ();
p8.points.emplace_back(2, 2);
p8.points.emplace_back(3, 3);
p8.points.emplace_back(2, 4);
p8.points.emplace_back(3, 3);
Assert::IsFalse(p8.is_convex(), L"p8", LINE_INFO());
Assert::IsTrue(p8.convexity() == convex_type::degenerate, L"p8 c", LINE_INFO());
auto p9 = polygon < > ();
p9.points.emplace_back(2, 2);
p9.points.emplace_back(2, 2);
p9.points.emplace_back(3, 3);
p9.points.emplace_back(3, 3);
p9.points.emplace_back(2, 4);
p9.points.emplace_back(2, 4);
p9.points.emplace_back(2, 4);
p9.points.emplace_back(2.5, 3);
Assert::IsFalse(p9.is_convex(), L"p9", LINE_INFO());
Assert::IsTrue(p9.convexity() == convex_type::no, L"p9 c", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_contains)
TEST_DESCRIPTION(L"containment calculation is correct")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_contains)
{
auto p = make_polygon < arr4_t > ({ { { 2, 2 }, { 3, 3 }, { 2, 4 }, { 1, 3 } } });
auto p2 = p;
std::reverse(p2.points.begin(), p2.points.end());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p.contains({ 2, 3 }), L"p1 (2,3)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p.contains({ 2, 2.1 }), L"p1 (2,2.1)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p.contains({ 2, 1.9 }), L"p1 (2,1.9)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 2, 3 }), L"p2 (2,3)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 2, 2.1 }), L"p2 (2,2.1)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p2.contains({ 2, 1.9 }), L"p2 (2,1.9)", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_contains_concave)
TEST_DESCRIPTION(L"containment calculation is correct - concave polygon")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_contains_concave)
{
auto p1 = polygon < > ();
p1.points.emplace_back(1, 2);
p1.points.emplace_back(2, 1);
p1.points.emplace_back(5, 1);
p1.points.emplace_back(4, 2);
p1.points.emplace_back(4, 3);
p1.points.emplace_back(5, 4);
p1.points.emplace_back(2, 4);
p1.points.emplace_back(1, 3);
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 0, 0 }), L"p1 (0,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 1, 0 }), L"p1 (1,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 2, 0 }), L"p1 (2,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 3, 0 }), L"p1 (3,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 4, 0 }), L"p1 (4,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 5, 0 }), L"p1 (5,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 6, 0 }), L"p1 (6,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 0, 5 }), L"p1 (0,5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 1, 5 }), L"p1 (1,5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 2, 5 }), L"p1 (2,5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 3, 5 }), L"p1 (3,5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 4, 5 }), L"p1 (4,5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 5, 5 }), L"p1 (5,5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 6, 5 }), L"p1 (6,5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 0, 1 }), L"p1 (0,1)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 0, 2 }), L"p1 (0,2)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 0, 3 }), L"p1 (0,3)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 0, 4 }), L"p1 (0,4)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 6, 1 }), L"p1 (6,1)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 6, 2 }), L"p1 (6,2)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 6, 3 }), L"p1 (6,3)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p1.contains({ 6, 4 }), L"p1 (6,4)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p1.contains({ 2, 2 }), L"p1 (2,2)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p1.contains({ 3, 3 }), L"p1 (3,3)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p1.contains({ 2, 3 }), L"p1 (2,3)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p1.contains({ 3, 2 }), L"p1 (3,2)", LINE_INFO());
auto p2 = polygon < > ();
p2.points.emplace_back(0, 0);
p2.points.emplace_back(7, 0);
p2.points.emplace_back(7, 3);
p2.points.emplace_back(1, 3);
p2.points.emplace_back(1, 4);
p2.points.emplace_back(7, 4);
p2.points.emplace_back(7, 7);
p2.points.emplace_back(0, 7);
p2.points.emplace_back(0, 6);
p2.points.emplace_back(6, 6);
p2.points.emplace_back(6, 5);
p2.points.emplace_back(0, 5);
p2.points.emplace_back(0, 2);
p2.points.emplace_back(6, 2);
p2.points.emplace_back(6, 1);
p2.points.emplace_back(0, 1);
for (size_t i = 0; i < 9; ++i)
{
auto info = L"p2 " + std::to_wstring(i) + L" left";
Assert::AreEqual(status::trusted(status::ok),
p2.contains({ -0.5, -0.5 + i }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" right";
Assert::AreEqual(status::trusted(status::ok),
p2.contains({ 7.5, -0.5 + i }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" top";
Assert::AreEqual(status::trusted(status::ok),
p2.contains({ -0.5 + i, 7.5 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" bottom";
Assert::AreEqual(status::trusted(status::ok),
p2.contains({ -0.5 + i, -0.5 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-bottom";
Assert::AreEqual(status::trusted(status::ok),
p2.contains({ -2.5 + i, 1.5 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-center";
Assert::AreEqual(status::trusted(status::ok),
p2.contains({ 2.5 + i, 3.5 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-top";
Assert::AreEqual(status::trusted(status::ok),
p2.contains({ -2.5 + i, 5.5 }), info.c_str(), LINE_INFO());
}
for (size_t i = 0; i < 7; ++i)
{
auto info = L"p2 " + std::to_wstring(i) + L" inside-bottom";
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 0.5 + i, 0.5 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inside-center-bottom";
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 0.5 + i, 2.5 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inside-center-top";
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 0.5 + i, 4.5 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inside-top";
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 0.5 + i, 6.5 }), info.c_str(), LINE_INFO());
}
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 6.5, 1.5 }), L"p2 spec1", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 0.5, 3.5 }), L"p2 spec2", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p2.contains({ 6.5, 5.5 }), L"p2 spec3", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_contains_concave_special_cases)
TEST_DESCRIPTION(L"containment calculation is correct - concave polygon - special cases")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_contains_concave_special_cases)
{
auto p1 = polygon < > ();
p1.points.emplace_back(1, 2);
p1.points.emplace_back(2, 1);
p1.points.emplace_back(5, 1);
p1.points.emplace_back(4, 2);
p1.points.emplace_back(4, 3);
p1.points.emplace_back(5, 4);
p1.points.emplace_back(2, 4);
p1.points.emplace_back(1, 3);
for (size_t i = 0; i < p1.points.size(); ++i)
{
auto info = L"p1 " + std::to_wstring(i);
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p1.contains(p1.points[i]), info.c_str(), LINE_INFO());
}
for (size_t i = 0; i < p1.points.size(); ++i)
{
auto info = L"p1 " + std::to_wstring(i) + L" +0";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p1.contains(p1.points[i] + point2d_t{ 1e-12, 1e-12 }), info.c_str(), LINE_INFO());
}
for (size_t i = 0; i < p1.points.size(); ++i)
{
auto info = L"p1 " + std::to_wstring(i) + L" -0";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p1.contains(p1.points[i] + point2d_t{ -1e-12, -1e-12 }), info.c_str(), LINE_INFO());
}
auto p2 = polygon < > ();
p2.points.emplace_back(0, 0);
p2.points.emplace_back(7, 0);
p2.points.emplace_back(7, 3);
p2.points.emplace_back(1, 3);
p2.points.emplace_back(1, 4);
p2.points.emplace_back(7, 4);
p2.points.emplace_back(7, 7);
p2.points.emplace_back(0, 7);
p2.points.emplace_back(0, 6);
p2.points.emplace_back(6, 6);
p2.points.emplace_back(6, 5);
p2.points.emplace_back(0, 5);
p2.points.emplace_back(0, 2);
p2.points.emplace_back(6, 2);
p2.points.emplace_back(6, 1);
p2.points.emplace_back(0, 1);
for (int i = 0; i <= 7; ++i)
{
auto info = L"p2 " + std::to_wstring(i) + L" left";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 3) || (i == 4)) ? status::trusted(status::polygon::edge_contains_point) : status::polygon::edge_contains_point),
p2.contains({ 0, i }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" right";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 1) || (i == 2) || (i == 5) || (i == 6)) ? status::trusted(status::polygon::edge_contains_point) : status::polygon::edge_contains_point),
p2.contains({ 7, i }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" top";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 0) || (i == 7)) ? status::polygon::edge_contains_point : status::trusted(status::polygon::edge_contains_point)),
p2.contains({ i, 7 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" bottom";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 0) || (i == 7)) ? status::polygon::edge_contains_point : status::trusted(status::polygon::edge_contains_point)),
p2.contains({ i, 0 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-bottom-1";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 0) || (i == 6)) ? status::polygon::edge_contains_point : status::trusted(status::polygon::edge_contains_point)),
p2.contains({ i, 1 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-bottom-2";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 0) || (i == 6)) ? status::polygon::edge_contains_point : status::trusted(status::polygon::edge_contains_point)),
p2.contains({ i, 2 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-center-1";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 1) || (i == 7)) ? status::polygon::edge_contains_point : status::trusted(status::polygon::edge_contains_point)),
p2.contains({ i, 3 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-center-2";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 1) || (i == 7)) ? status::polygon::edge_contains_point : status::trusted(status::polygon::edge_contains_point)),
p2.contains({ i, 4 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-top-1";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 0) || (i == 6)) ? status::polygon::edge_contains_point : status::trusted(status::polygon::edge_contains_point)),
p2.contains({ i, 5 }), info.c_str(), LINE_INFO());
info = L"p2 " + std::to_wstring(i) + L" inner-top-2";
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | (((i == 0) || (i == 6)) ? status::polygon::edge_contains_point : status::trusted(status::polygon::edge_contains_point)),
p2.contains({ i, 6 }), info.c_str(), LINE_INFO());
}
auto p3 = polygon < > ();
p3.points.emplace_back(-2, 0);
p3.points.emplace_back(0, 0);
p3.points.emplace_back(2, 0);
p3.points.emplace_back(0, 2);
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p3.contains({ -2, 0 }), L"p3 (-2,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p3.contains({ -3, 0 }), L"p3 (-3,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p3.contains({ 2, 0 }), L"p3 (2,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p3.contains({ 3, 0 }), L"p3 (3,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p3.contains({ 0, 2 }), L"p3 (0,2)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p3.contains({ 0, 3 }), L"p3 (0,3)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p3.contains({ 0, 1 }), L"p3 (0,1)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p3.contains({ 0, 1.5 }), L"p3 (0,1.5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p3.contains({ 0, 1.9 }), L"p3 (0,1.9)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p3.contains({ 0, 1.99 }), L"p3 (0,1.99)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p3.contains({ 0, 1.999 }), L"p3 (0,1.999)", LINE_INFO());
auto p4 = polygon < > ();
p4.points.emplace_back(-2, 0);
p4.points.emplace_back(-2, 0);
p4.points.emplace_back(0, 0);
p4.points.emplace_back(2, 0);
p4.points.emplace_back(2, 0);
p4.points.emplace_back(0, 2);
p4.points.emplace_back(0, 2);
p4.points.emplace_back(-2, 0);
p4.points.emplace_back(-2, 0);
p4.points.emplace_back(-2, 0);
p4.points.emplace_back(-2, 0);
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p4.contains({ -2, 0 }), L"p4 (-2,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p4.contains({ -3, 0 }), L"p4 (-3,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p4.contains({ 2, 0 }), L"p4 (2,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p4.contains({ 3, 0 }), L"p4 (3,0)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok) | status::polygon::contains_point | status::polygon::edge_contains_point,
p4.contains({ 0, 2 }), L"p4 (0,2)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok),
p4.contains({ 0, 3 }), L"p4 (0,3)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p4.contains({ 0, 1 }), L"p4 (0,1)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p4.contains({ 0, 1.5 }), L"p4 (0,1.5)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p4.contains({ 0, 1.9 }), L"p4 (0,1.9)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p4.contains({ 0, 1.99 }), L"p4 (0,1.99)", LINE_INFO());
Assert::AreEqual(status::trusted(status::ok | status::polygon::contains_point),
p4.contains({ 0, 1.999 }), L"p4 (0,1.999)", LINE_INFO());
}
BEGIN_TEST_METHOD_ATTRIBUTE(_clockwise_sort)
TEST_DESCRIPTION(L"clockwise sort calculation is correct")
END_TEST_METHOD_ATTRIBUTE()
TEST_METHOD(_clockwise_sort)
{
auto p1 = make_polygon < arr4_t > ({ { { 2, 2 }, { 3, 3 }, { 2, 4 }, { 1, 3 } } });
auto p2 = make_polygon < arr4_t > ({ { { 0, 0 }, { 2, 2 }, { 2, 1 }, { 0, 3 } } });
p1.sort();
p2.sort();
Assert::AreEqual(2, p1.points[0].x, 1e-8, L"p1[0].x ccw", LINE_INFO());
Assert::AreEqual(2, p1.points[0].y, 1e-8, L"p1[0].y ccw", LINE_INFO());
Assert::AreEqual(3, p1.points[1].x, 1e-8, L"p1[1].x ccw", LINE_INFO());
Assert::AreEqual(3, p1.points[1].y, 1e-8, L"p1[1].y ccw", LINE_INFO());
Assert::AreEqual(2, p1.points[2].x, 1e-8, L"p1[2].x ccw", LINE_INFO());
Assert::AreEqual(4, p1.points[2].y, 1e-8, L"p1[2].y ccw", LINE_INFO());
Assert::AreEqual(1, p1.points[3].x, 1e-8, L"p1[3].x ccw", LINE_INFO());
Assert::AreEqual(3, p1.points[3].y, 1e-8, L"p1[3].y ccw", LINE_INFO());
Assert::AreEqual(0, p2.points[0].x, 1e-8, L"p2[0].x ccw", LINE_INFO());
Assert::AreEqual(0, p2.points[0].y, 1e-8, L"p2[0].y ccw", LINE_INFO());
Assert::AreEqual(2, p2.points[1].x, 1e-8, L"p2[1].x ccw", LINE_INFO());
Assert::AreEqual(1, p2.points[1].y, 1e-8, L"p2[1].y ccw", LINE_INFO());
Assert::AreEqual(2, p2.points[2].x, 1e-8, L"p2[2].x ccw", LINE_INFO());
Assert::AreEqual(2, p2.points[2].y, 1e-8, L"p2[2].y ccw", LINE_INFO());
Assert::AreEqual(0, p2.points[3].x, 1e-8, L"p2[3].x ccw", LINE_INFO());
Assert::AreEqual(3, p2.points[3].y, 1e-8, L"p2[3].y ccw", LINE_INFO());
p1.sort(false);
p2.sort(false);
Assert::AreEqual(2, p1.points[0].x, 1e-8, L"p1[0].x cw", LINE_INFO());
Assert::AreEqual(2, p1.points[0].y, 1e-8, L"p1[0].y cw", LINE_INFO());
Assert::AreEqual(1, p1.points[1].x, 1e-8, L"p1[1].x cw", LINE_INFO());
Assert::AreEqual(3, p1.points[1].y, 1e-8, L"p1[1].y cw", LINE_INFO());
Assert::AreEqual(2, p1.points[2].x, 1e-8, L"p1[2].x cw", LINE_INFO());
Assert::AreEqual(4, p1.points[2].y, 1e-8, L"p1[2].y cw", LINE_INFO());
Assert::AreEqual(3, p1.points[3].x, 1e-8, L"p1[3].x cw", LINE_INFO());
Assert::AreEqual(3, p1.points[3].y, 1e-8, L"p1[3].y cw", LINE_INFO());
Assert::AreEqual(0, p2.points[0].x, 1e-8, L"p2[0].x cw", LINE_INFO());
Assert::AreEqual(0, p2.points[0].y, 1e-8, L"p2[0].y cw", LINE_INFO());
Assert::AreEqual(0, p2.points[1].x, 1e-8, L"p2[1].x cw", LINE_INFO());
Assert::AreEqual(3, p2.points[1].y, 1e-8, L"p2[1].y cw", LINE_INFO());
Assert::AreEqual(2, p2.points[2].x, 1e-8, L"p2[2].x cw", LINE_INFO());
Assert::AreEqual(2, p2.points[2].y, 1e-8, L"p2[2].y cw", LINE_INFO());
Assert::AreEqual(2, p2.points[3].x, 1e-8, L"p2[3].x cw", LINE_INFO());
Assert::AreEqual(1, p2.points[3].y, 1e-8, L"p2[3].y cw", LINE_INFO());
}
};
}
|
Java
|
UTF-8
| 4,124
| 2.265625
| 2
|
[] |
no_license
|
package com.lebien.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.lebien.dto.NewDTO;
import com.lebien.entity.CategoryEntity;
import com.lebien.entity.NewEntity;
import com.lebien.service.NewService;
@Controller
@RequestMapping("/admin")
public class AdminController {
@Autowired
private NewService nsv;
@GetMapping("/add")
public String add(ModelMap model) {
NewDTO newDTO = new NewDTO();
model.addAttribute("newStaff", newDTO);
return "admin/creatNew";
}
@PostMapping("/creat/new")
public String create(@ModelAttribute("newStaff")NewDTO newDTO,ModelMap model) {
NewEntity oldNew = nsv.findOneById(newDTO.getId());
String image = "Logo.png";
NewEntity newEntity = null;
Path path = Paths.get("src\\main\\resources\\static\\images");
if(oldNew != null) {
if(newDTO.getPhoto().isEmpty()) {
image = oldNew.getImage();
}else {
try {
InputStream inputStream = newDTO.getPhoto().getInputStream();
Files.copy(inputStream, path.resolve(newDTO.getPhoto().getOriginalFilename()),
StandardCopyOption.REPLACE_EXISTING);
image = newDTO.getPhoto().getOriginalFilename().toString();
}catch (Exception e) {
e.printStackTrace();
}
}
}else {
if(!newDTO.getPhoto().isEmpty()) {
try {
InputStream inputStream = newDTO.getPhoto().getInputStream();
Files.copy(inputStream, path.resolve(newDTO.getPhoto().getOriginalFilename()),
StandardCopyOption.REPLACE_EXISTING);
image = newDTO.getPhoto().getOriginalFilename().toString();
}catch (Exception e) {
e.printStackTrace();
}
}
}
//Long id, String title, String image, String shortdescription, String content,
newEntity = new NewEntity(newDTO.getId(),newDTO.getTitle(),
image,newDTO.getShortdescription(),newDTO.getContent(),new CategoryEntity(newDTO.getCategoryId(),""));
nsv.createNew(newEntity);
return "redirect:/admin/list";
}
@GetMapping("/edit/{id}")
public String edit(ModelMap model, @PathVariable(name = "id") Long id) {
NewEntity st = nsv.findOneById(id);
NewDTO dto = null;
if(st != null) {
File file = new File("src\\main\\resources\\static\\images/" + st.getImage());
FileInputStream input;
try {
input = new FileInputStream(file);
MultipartFile multiphoto =
new MockMultipartFile("file", file.getName(),"text/plain",
IOUtils.toByteArray(input));
dto = new NewDTO(st.getId(),st.getTitle(),st.getContent(),st.getDescription(),
multiphoto,st.getCategorys().getId());
model.addAttribute("newStaff", dto);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
}
return "admin/creatNew";
}
@GetMapping("/delete/{id}")
public String delete(ModelMap model, @PathVariable(name="id") Long id) {
nsv.delete(id);
List<NewEntity> list = nsv.findAll();
model.addAttribute("list", list);
return "redirect:/admin/list";
}
@GetMapping("/list")
public String list(ModelMap model) {
List<NewEntity> list = nsv.findAll();
model.addAttribute("list", list);
return "admin/newList";
}
@ModelAttribute(name = "listCategory")
public List<CategoryEntity> getCategory(){
return nsv.findAllCategory();
}
}
|
SQL
|
UTF-8
| 888
| 4.3125
| 4
|
[
"LicenseRef-scancode-public-domain",
"Unlicense"
] |
permissive
|
CREATE TABLE "Comment" (
"id" BIGINT NOT NULL UNIQUE,
"parentId" BIGINT,
"slug" TEXT NOT NULL,
"datePublished" NUMERIC NOT NULL,
"dateDeleted" NUMERIC,
"authorName" TEXT NOT NULL,
"authorEmail" TEXT,
"authorWebsite" TEXT,
"text" TEXT NOT NULL,
PRIMARY KEY("id" AUTOINCREMENT)
);
CREATE TABLE "Vote" (
"commentId" BIGINT NOT NULL,
"voterIp" VARCHAR(15) NOT NULL,
"vote" INTEGER NOT NULL,
PRIMARY KEY("commentId","voterIp")
);
CREATE VIEW "CommentWithScore" AS
SELECT
Comment.id,
Comment.parentId,
Comment.slug,
Comment.datePublished,
Comment.dateDeleted,
Comment.authorName,
Comment.authorEmail,
Comment.authorWebsite,
coalesce(sum(Vote.vote), 0) DIV 1 AS score,
Comment.text
FROM Comment
LEFT JOIN Vote ON Vote.commentId = Comment.id
GROUP BY Comment.id
ORDER BY Comment.datePublished ASC;
|
Rust
|
UTF-8
| 1,181
| 2.5625
| 3
|
[] |
no_license
|
use futures::Future;
use http::Uri;
use hyper::client::connect::Connect;
use hyper::client::connect::Connected;
use hyper::client::connect::Destination;
use std::io;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
/// A wrapper around `Proxy`s with a connector.
#[derive(Clone, Debug)]
pub struct ProxyConnector<C> {
proxy: Uri,
connector: C,
}
impl<C, T: 'static> Connect for ProxyConnector<C>
where
C: Connect<
Error = io::Error,
Transport = T,
Future = Box<Future<Item = (T, Connected), Error = io::Error> + Send>,
>,
T: AsyncWrite + Send + AsyncRead,
{
type Transport = T;
type Error = io::Error;
type Future = Box<Future<Item = (T, Connected), Error = io::Error> + Send>;
fn connect(&self, _dst: Destination) -> Self::Future {
Box::new(
self.connector
.connect(Destination::new(&self.proxy))
.map(move |(s, c)| (s, c.proxy(true))),
)
}
}
impl<C> ProxyConnector<C> {
pub fn new(connector: C, proxy: Uri) -> Result<Self, io::Error> {
Ok(ProxyConnector {
proxy: proxy,
connector: connector,
})
}
}
|
Markdown
|
UTF-8
| 2,045
| 3.5
| 4
|
[] |
no_license
|
# All devices setup
Since we are making websites designed for all devices, we want to setup our HTML and CSS to show it.
There are a couple `<meta>` tags and a little bit of CSS to make all devices recognize your website supports the device, whatever it is.
## HTML
```html
⋮
<head>
⋮
<meta name="handheldfriendly" content="true">
<meta name="mobileoptimized" content="240">
<meta name="viewport" content="width=device-width,initial-scale=1">
⋮
</head>
⋮
```
- **handheldfriendly** & **mobileoptimized** are for older devices
- The `240` states that our website is formatted for a minimum width of 240 pixels
- **viewport** is for newer smartphones. There are three arguments to specify:
- `width=device-width`—our website is formatted for the prime width of the device
- `initial-scale=1`—our website shouldn’t be zoomed in or out by default
## CSS
```css
@-moz-viewport { width: device-width; scale: 1; }
@-ms-viewport { width: device-width; scale: 1; }
@-o-viewport { width: device-width; scale: 1; }
@-webkit-viewport { width: device-width; scale: 1; }
@viewport { width: device-width; scale: 1; }
html {
-moz-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
⋮
```
The `@viewport` rule is a replacement for the viewport meta tag but is new and only supported by a few browsers.
Since we’re future thinking designers we want to put it in.
**It’s probably best to put this at the very top of your CSS file.**
Since we are optimizing our sites for small screens, we want to stop small-screen browsers from inflating our font-size in an attempt to make our sites more readable.
That’s what the `text-size-adjust` property does.
---
## Videos
1. [All devices setup](http://www.youtube.com/watch?v=nbqnFZFQxd0)
---
## Links
- https://developer.mozilla.org/en/Mobile/Viewport_meta_tag/
- http://dev.opera.com/articles/view/an-introduction-to-meta-viewport-and-viewport/
- http://learnthemobileweb.com/blog/2009/07/mobile-meta-tags/
|
Java
|
UTF-8
| 695
| 2.09375
| 2
|
[] |
no_license
|
package com.example.beckart.ViewModel;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;
import com.example.beckart.model.CartApiResponse;
import com.example.beckart.repository.CartRepository;
public class CartViewModel extends AndroidViewModel {
private CartRepository cartRepository;
public CartViewModel(@NonNull Application application) {
super(application);
cartRepository = new CartRepository(application);
}
public LiveData<CartApiResponse> getProductsInCart(int userId) {
return cartRepository.getProductsInCart(userId);
}
}
|
Java
|
UTF-8
| 1,047
| 3.734375
| 4
|
[] |
no_license
|
package Thejvm.MulitThreads;
/**
* Created by tangjialiang on 2018/1/23.
*/
public class DeadLock {
/**
* 用于对多线程死锁的测试,
* 线程的状态变化: blocked
* 某个线程占有对象a,
* 某个线程占有对象b
*/
static class SynAddRunalbe implements Runnable {
int a, b ;
public SynAddRunalbe(int a, int b) {
this.a = a ;
this.b = b ;
}
@Override
public void run() {
synchronized (Integer.valueOf(a)) { // Integer.valueof在[-128, 127]之间的数字会被缓存, 所以1和2对象是同一个。
synchronized (Integer.valueOf(b)) {
System.out.println(a + b);
}
}
}
}
public static void main(String[] args) {
for(int i=0; i<100; i++) {
// System.out.println("i: " + i) ;
new Thread(new SynAddRunalbe(1, 2)).start();
new Thread(new SynAddRunalbe(2, 1)).start();
}
}
}
|
Python
|
UTF-8
| 1,581
| 2.765625
| 3
|
[] |
no_license
|
import time
import RPi.GPIO as GPIO
import subprocess
import os
TRIG = 21 # Pin for ultrasonic sensor
ECHO = 22 # Pin for ultrasonic sensor
LED = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED,GPIO.OUT) #setup
GPIO.setup(23,GPIO.OUT) #setup
GPIO.setup(TRIG,GPIO.OUT) #setup
GPIO.setup(ECHO,GPIO.IN) #setup
def main(): # function
start_motor() # motor will start
img="click.jpg" # captured image through webcam
temp_img="template.jpg" # sample template image
while True:
x=read_from_sensor() #continuously sence by sensor
if x!=-1: #if detected
time.sleep(0.4)
stop_motor() #then motor stop
os.system('fswebcam '+str(img)) # command for capturing image
os.system('python im.py '+str(img)+' '+str(temp_img)+'>diff.txt') #compare 2 images
output=open('diff.txt').read().strip()
print output
x=float(output)
print x
print "output is" +str(x)
if x>45: # threshold
blink_led()
start_motor()
time.sleep(1.5)
def blink_led(): #code for LED blink
GPIO.output(LED,True)
time.sleep(3)
GPIO.output(LED,False)
time.sleep(3)
def start_motor(): # code for motor starting
GPIO.output(23,True)
def read_from_sensor(): # read sensor input data
print "Waiting For Sensor To Settle"
pulse_start = 0
GPIO.output(TRIG,True)
time.sleep(0.00001)
GPIO.output(TRIG,False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance,2)
if distance < 13 :
return 1
else:
return -1
def stop_motor():
GPIO.output(23,False)
if __name__ == "__main__":
main()
|
Markdown
|
UTF-8
| 597
| 2.703125
| 3
|
[] |
no_license
|
# Frontend
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
### Prerequisites
- Node.JS
- yarn
### Installing
1. Clone this repository.
2. Navigate to the right directory.
3. <b>First, run the backend server!</b> Type "yarn run dev" in your command prompt/terminal.
4. App should start.
## Tech/framework used
<b>Built with</b>
- [next.js](https://nextjs.org/)
- [apollo](https://www.apollographql.com/docs/)
- [material-ui](https://material-ui.com/)
- [i18next](https://www.i18next.com/)
|
PHP
|
UTF-8
| 2,865
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace SimoTod\OmnipaySetefi\Message;
use Omnipay\Common\Message\AbstractRequest;
class Request extends AbstractRequest
{
protected $testEndpoint = 'https://test.monetaonline.it/monetaweb/payment/2/xml';
protected $liveEndpoint = 'https://www.monetaonline.it/monetaweb/payment/2/xml';
const OP_TYPE_INIT = 'initialize';
public function getData()
{
$this->validate('id', 'password', 'amount', 'transactionId');
return $this->getParameters();
}
public function setId($id)
{
return $this->setParameter('id', $id);
}
public function setPassword($password)
{
return $this->setParameter('password', $password);
}
public function setLanguage($language)
{
return $this->setParameter('language', $language);
}
public function sendData($data)
{
$newData = array();
$redirectUrl = null;
try {
$tokenRequest = $this->httpClient
->post($this->getEndpoint())
->setPostField('id', $this->getParameter('id'))
->setPostField('password', $this->getParameter('password'))
->setPostField('operationType', self::OP_TYPE_INIT)
->setPostField('amount', $this->getParameter('amount'))
->setPostField('currencycode', $this->getParameter('currency'))
->setPostField('language', $this->getParameter('language'))
->setPostField('responseToMerchantUrl', $this->getParameter('returnUrl'))
->setPostField('recoveryUrl', $this->getParameter('cancelUrl'))
->setPostField('merchantOrderId', $this->getParameter('transactionId'))
->setPostField('description', $this->getParameter('description'));
$tokenResponse = $tokenRequest->send();
$xml = simplexml_load_string($tokenResponse->getBody()->__toString());
if ($xml->errorcode) {
$newData["reference"] = null;
$newData['message'] = "Failure: ".$xml->errormessage->__toString();
} else {
$newData["reference"] = [
'securitytoken' => $xml->securitytoken->__toString(),
'paymentid' => $xml->paymentid->__toString(),
];
$newData['message'] = "Success";
$redirectUrl = ($xml->hostedpageurl->__toString()).'?paymentId='.($xml->paymentid->__toString());
}
} catch (Exception $e) {
$newData["reference"] = null;
$newData['message'] = "Failure: ".$e->getMessage();
}
return $this->response = new Response($this, $newData, $redirectUrl);
}
public function getEndpoint()
{
return $this->getTestMode() ? $this->testEndpoint : $this->liveEndpoint;
}
}
|
JavaScript
|
UTF-8
| 2,033
| 2.53125
| 3
|
[] |
no_license
|
import React, { Component } from 'react'
import axios from "axios"
import Card from "../../components/Card/Card"
//引入swiper组件
import Swiper from "../../components/Swiper/Swiper"
// 引入购物车组件
import ShoppingCar from "../../components/ShoppingCar/ShoppingCar"
// 引入dealFn高阶方法
import { dealFn } from '../../store';
// 处理购物车
let DealShoppingCar = dealFn(ShoppingCar);
export default class Home extends Component {
constructor(props){
super(props)
this.state={
data:[]
}
}
componentDidMount(){
// 发送请求
this.getData()
}
getData(){
// 发送请求
axios
.get(this.getUrl())
// 监听数据返回
// .then(({ data }) => this.setState({ data: data.data }))
// 简写
.then(({ data }) => this.setState(data))
}
getUrl(){
//根据当前的页面进行判断
let {match} = this.props;
//判断match
if(match.url.indexOf('/search/')===0){
//返回搜索页面请求地址
return '/data/lesson/search?id=' + match.params.word;
}else{
return '/data/lesson/home'
}
}
// 组件更新完成
componentDidUpdate(oldProps){
// 如果url发生了改变,发送请求
if (this.props.match.url !== oldProps.match.url) {
// 发送请求
this.getData()
}
}
// 创建课程卡片
createList() {
return this.state.data&&this.state.data.map(item => <Card key={item._id} data={item}></Card>)
}
render() {
console.log(this.state)
return (
<div>
<Swiper height="200px" urls={[
'static/img/banner/01.jpg',
'static/img/banner/02.jpg',
'static/img/banner/03.jpg',
'static/img/banner/04.jpg',
'static/img/banner/05.jpg'
]}></Swiper>
{ this.createList()}
<DealShoppingCar/>
</div>
)
}
}
|
JavaScript
|
UTF-8
| 1,478
| 4.25
| 4
|
[] |
no_license
|
//1.
/*
var warmup = new Promise(function (resolve, reject){
resolve('hello promise, yay i resolved')
reject('oops i did it again you got rejected')
})
warmup.then(function(result){
setTimeout(function(){
console.log(result)
}, 1000),
function(err) {
console.log(err)
}
})
*/
//2.
var delay = function(milliseconds) {
var promise = new Promise(function (resolve, reject) {
setTimeout(function(){
resolve(milliseconds)
console.log(promise)
}, milliseconds)
})
console.log(promise)
return promise
}
var countDown = function(resolveFromDelay) {
if (resolveFromDelay > 1) {
console.log(resolveFromDelay)
var promise = new Promise(function(resolve,reject){
setTimeout(function(){
resolve(resolveFromDelay - 100)
}, 500)
})
} else if(resolveFromDelay === 0) {
console.log('done!')
}
return promise
}
//delay(1000).then(countDown).then(countDown).then(countDown).then(countDown).then(countDown).then(countDown).then(countDown).then(countDown).then(countDown).then(countDown).then(countDown)
// 3.
var squaring = function(num){
var promise = new Promise(function(resolve,reject){
if (typeof(num) === "number" ) {
resolve(num * num)
} else {
reject("sorry thats not a number")
}
})
return promise
}
var num = [1,2,3,4,5,6,7,8,9]
num = num.map(function(i) {
return squaring(i)
})
Promise.all(num)
.then(function(results) {
console.log(results);
});
|
Python
|
UTF-8
| 1,939
| 2.59375
| 3
|
[] |
no_license
|
import numpy as np
from matplotlib import pyplot as plt
import scipy.io.wavfile
from scipy import signal
import analysis as ana
import synthesis as syn
rate, unnorm_input = scipy.io.wavfile.read('s5.wav')
input = unnorm_input/64000
signal_length = len(input)
samples_per_frame = int(25/1000*rate)
samples_per_skip = int(10/1000*rate)
fft_length = 1024
### analyze signal
pitch_frames = ana.extract_frame(input,rate,samples_per_frame,samples_per_skip)
fft_frames = ana.fft_frame(pitch_frames, fft_length)
pitch_estimates = ana.estimate_pitch(pitch_frames,samples_per_frame,np.arange(20,91))
Ams, all_choices, error_sum =ana.estimate_amplitude(fft_frames,samples_per_frame,pitch_estimates,fft_length)
refined_Am,refined_all_choices,refined_error_sum,refined_periods = ana.estimate_refined_pitch(fft_frames,samples_per_frame,pitch_estimates,fft_length)
###synthesize signal
sv_n = syn.voiced_signal(refined_Am, refined_all_choices, refined_periods,samples_per_skip,signal_length)
suv_n = syn.unvoiced_signal(fft_frames,samples_per_frame,refined_all_choices,refined_periods,fft_length,signal_length,samples_per_skip)
output = np.real(sv_n+suv_n)
scipy.io.wavfile.write("s5_synthesized.wav",rate,output)
# uncomment the following code if you need to see the plots and spectrograms
# plt.plot(np.arange(298), refined_periods)
# plt.title('Pitch Estimates vs. Frame Index')
# plt.ylabel('Pitch Estimates')
# plt.xlabel('Frame [i]')
# plt.show()
# plt.plot(np.arange(298), refined_error_sum)
# plt.title('Error vs. Frame Index')
# plt.ylabel('Error')
# plt.xlabel('Frame [i]')
# plt.show()
# f, t, Sxx = signal.spectrogram(input, rate)
# plt.pcolormesh(t, f, Sxx)
# plt.title('Original Signal')
# plt.ylabel('Frequency [Hz]')
# plt.xlabel('Time [sec]')
# plt.show()
# f, t, Sxx = signal.spectrogram(output, rate)
# plt.pcolormesh(t, f, Sxx)
# plt.title('Synthesized Signal')
# plt.ylabel('Frequency [Hz]')
# plt.xlabel('Time [sec]')
# plt.show()
|
Ruby
|
UTF-8
| 1,613
| 3.4375
| 3
|
[] |
no_license
|
class Slots
def initialize(player)
puts '
/$$$$$$ /$$ /$$
/$$__ $$| $$ | $$
| $$ \__/| $$ /$$$$$$ /$$$$$$ /$$$$$$$
| $$$$$$ | $$ /$$__ $$|_ $$_/ /$$_____/
\____ $$| $$| $$ \ $$ | $$ | $$$$$$
/$$ \ $$| $$| $$ | $$ | $$ /$$\____ $$
| $$$$$$/| $$| $$$$$$/ | $$$$//$$$$$$$/
\______/ |__/ \______/ \___/ |_______/ '.colorize(:yellow)
puts "Welcome to slots #{player.name}!"
puts "You have #{player.wallet.amount}"
slots(player)
end
def slots(player)
slot1 = ["Cherries", "777", "Bell"]
slot2 = ["Cherries", "777", "Bell"]
slot3 = ["Cherries", "777", "Bell"]
puts "How much would you like to bet?"
betting_amount = gets.to_f
if betting_amount > player.wallet.amount || betting_amount < 1
puts "You don't have enough cash!"
slots(player)
end
puts "Type 'Spin' to pull the handle or type 'Menu' to return to the main menu"
case gets.strip.downcase
when "spin"
slot_roll_one = slot1.sample
slot_roll_two = slot2.sample
slot_roll_three = slot3.sample
puts slot_roll_one.colorize(:yellow)
puts slot_roll_two.colorize(:green)
puts slot_roll_three.colorize(:cyan)
if slot_roll_one == slot_roll_two && slot_roll_two == slot_roll_three
player.wallet.amount += betting_amount
puts "You win! Current balance #{player.wallet.amount}".colorize(:green)
else
player.wallet.amount -= betting_amount
puts "You lose! Current balance #{player.wallet.amount}".colorize(:red)
end
when "menu"
end
end
end
|
PHP
|
UTF-8
| 4,044
| 2.84375
| 3
|
[] |
no_license
|
<?php
/**
* DataGateway for SQL Db wraps up Zend_Db_Table
*
* PHP version 5.3
*
* @category ZendApp
* @package DataGateway
* @author Francisco Marcos <fmarcos83@gmail.com>
* @license GNU http://www.gnu.org/licenses/lgpl.txt
* @link ZendApp\Data\DataGateway
* @see Zend_Db_Adapter_Abstract
* @see DataGatewayInterface
* @see Mapper
**/
declare(encoding='UTF-8');
namespace ZendApp\Data\DataGateway;
use ZendApp\Data\DataGateway\DataGatewayInterface as DataGatewayInterface;
/**
* DbDataGateway class
*
* Uses Zend_Db_Table to abstract persistence layer
*
* @category ZendApp
* @package DataGateway
* @author Francisco Marcos <fmarcos83@gmail.com>
* @license GNU http://www.gnu.org/licenses/lgpl.txt
* @link ZendApp\Data\DataGateway
* @see Zend_Db_Adapter_Abstract
* @see DataGatewayInterface
* @see Mapper
**/
class DbDataGateway implements DataGatewayInterface
{
private $_tableGateway = null;
/**
* instantiates a Zend_Db_Table if $tableName is set
*
* @param (String) $tableName OPTIONAL sets Zend_Db_Table name if present
*
* @return null
* @author Francisco Marcos <fmarcos83@gmail.com>
**/
public function __construct($tableName = null)
{
//intended especially for testing porpouses so it can be easily mocked
(!isset($tableName))||$this->setTableGateway(new \Zend_Db_Table($tableName));
}
/**
* sets an instance of \Zend_Db_Table this method is mainly
* used for testing porpouses on Zend_Db_Table mocks dependency injection
*
* @param (\Zend_Db_Table) $_tableGateway an instance of Zend_Db_Table
*
* @return null
* @author Francisco Marcos <fmarcos83@gmail.com>
**/
public function setTableGateway(\Zend_Db_Table $_tableGateway)
{
$this->_tableGateway = $_tableGateway;
}
/**
* inserts a new row in the database
*
* @param (array) $data dictionary where keys are column names and
* values column value
*
* @return (int) last id
* @author Francisco Marcos <fmarcos83@gmail.com>
**/
public function insert(array $data)
{
return $this->_tableGateway->insert($data);
}
/**
* update rows in the db
*
* @param (array) $data dictionary where keys match db table columns
* and values the values to be inserted in db
* @param (array) $where dictionary where keys are where clauses with
* question mark (?) placeholders and value will
* the value to substitute the placeholder with
*
* @return (int) the number of afected rows
* @author Francisco Marcos <fmarcos83@gmail.com>
**/
public function update(array $data, array $where)
{
return $this->_tableGateway->update($data, $where);
}
/**
* forwards to Zend_Db_Table fetchAll method
*
* @param string|array|Zend_Db_Table_Select $where OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
* @param string|array $order OPTIONAL An SQL ORDER clause.
* @param int $count OPTIONAL An SQL LIMIT count.
* @param int $offset OPTIONAL An SQL LIMIT offset.
*
* @return array rowset converted to array
* @author Francisco Marcos <fmarcos83@gmail.com>
**/
public function find(array $where=array())
{
$result = call_user_func_array(
array($this->_tableGateway, 'fetchAll'),
func_get_args()
);
return $result->toArray();
}
/**
* deletes rows in the db
*
* @param (array) $where dictionary where keys are where clauses with
* question mark (?) placeholders and value will
* the value to substitute the placeholder with
*
* @return (int) number of deleted rows
* @author Francisco Marcos <fmarcos83@gmail.com>
**/
public function delete(array $where)
{
return $this->_tableGateway->delete($where);
}
}
|
Java
|
UTF-8
| 397
| 2.859375
| 3
|
[] |
no_license
|
import java.util.*;
public class Prep1 {
/*
public static void main(String[] args) {
int i =20;
if(i==20)
{
int n= 34;
}
else
{
System.out.println(n);
}
}
}
*/
// public class Main {
public static void main(String[] args) {
for(int i = 0; i < 3; i++) {
System.out.print(i + " ");
System.out.print(i + " ");
}
}
}
|
JavaScript
|
UTF-8
| 196
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
module.exports = function reverse (n) {
// let Array = [];
//newArray = Array.map(n);
//console.log(newArray);
return Number(Math.abs(n).toString().split('').reverse().join(''));
}
|
C++
|
UTF-8
| 478
| 2.59375
| 3
|
[] |
no_license
|
#ifndef TIMER_H
#define TIMER_H
#include <QObject>
#include <QTimer>
class Timer:public QTimer
{
Q_OBJECT
Q_PROPERTY(int second READ second WRITE setSecond NOTIFY secondChanged)
public:
Timer(QObject *parent=nullptr);
Q_INVOKABLE void startTimer();
Q_INVOKABLE void stopTimer();
int second() const;
void setSecond(int second);
signals:
void callChangeImage(int num);
void secondChanged();
private:
int m_second;
};
#endif // TIMER_H
|
Python
|
UTF-8
| 4,299
| 2.8125
| 3
|
[] |
no_license
|
#!/usr/bin/python
import re,os,sys
#This file contains the useful functions for interacting with the config files
class ConfigFile:
def __init__(self, FileName="config.dat"):
self.FileName=FileName
self.Parameters={}
self.infile=open(self.FileName,"r")
self.LoadConfigFile()
def GetParameters(self, name):
if name in self.Parameters:
return self.Parameters[name]
else:
return False
def GetParameter(self, name, i):
if name in self.Parameters:
return self.Parameters[name][i]
else:
return False
def GetnParameter(self):
return len(self.Parameters)
def GetnVals(self, name):
if name in self.Parameters:
return len(self.Parameters[name])
else:
return False
def LoadConfigFile(self):
print "Loading "+self.FileName
while 1:
line = self.infile.readline()
if not line:
break
if ("#" in line) or (line in ('\n', '\r\n')):
continue
else:
line=line.rstrip()
line=re.sub(r'\s+','',line)
lineparts=re.split(':',line);
parName= lineparts[0]
self.Parameters[parName]=re.split(',',lineparts[1])
print "Loaded",parName+" -->",self.Parameters[parName]
def Configure(self):
print"\n\n Starting Configuration \n\n"
self.infile.seek(0)
while 1:
line = self.infile.readline()
if not line:
print "Finally done!"
break
if ("#" in line) or (line in ('\n', '\r\n')):
pass
else:
line=line.rstrip()
line=re.sub(r'\s+','',line)
lineparts=re.split(':',line);
parName= lineparts[0]
if(self.GetnVals(parName)<1):
print "Error, missing parameters from original Config"
sys.exit(0)
else:
parVals=raw_input("Enter values (comma separated) for "+parName+", default = "+str(self.Parameters[parName])+" : ")
if not parVals:
pass
else:
self.Parameters[parName]=[]
parVals.strip();
parVals=re.sub(r'\s+','',parVals)
self.Parameters[parName]=re.split(',',parVals)
def SaveConfigFile(self,FileName):
if(os.path.isfile(FileName)):
overwrite=raw_input("File "+FileName+" already exists, overwrite (y/n)? default=n :")
if(not overwrite or overwrite =="n"):
FileName=""
while(not FileName or os.path.isfile(FileName)):
FileName=raw_input("Enter a new filename: ")
self.FileName=FileName
outfile = open(self.FileName,"w")
#copy all the contents of the input file (comments) except for the paramers
self.infile.seek(0)
while 1:
line = self.infile.readline()
if not line:
break
if ("#" in line):
outfile.write(line)
elif (line in ('\n', '\r\n')):
outfile.write("\n")
else:
line=line.rstrip()
line=re.sub(r'\s+','',line)
lineparts=re.split(':',line);
parName= lineparts[0]
if(self.GetnVals(parName)<1):
print "Error, missing parameters from original Config"
sys.exit(0)
else:
newline = parName+" : "
count=0
for par in self.Parameters[parName]:
newline=newline+par;
count=count+1
if count<len(self.Parameters[parName]):
newline=newline+","
outfile.write(newline+"\n")
self.infile.close()
|
C++
|
UTF-8
| 1,394
| 2.96875
| 3
|
[] |
no_license
|
#ifndef PARSER_H
#define PARSER_H
#include<string>
#include<iterator>
#include<algorithm>
using std::string;
typedef string::iterator strIter;
// a section has the format:
// \section{sectionName}{sectionContent}
class Section
{
public:
Section();
const strIter & begin();
const strIter & end();
const strIter & cont_beg();
const strIter & cont_end();
virtual string getName();
//this method may be override,
// since the return type may be different
string getContent();
void markName(strIter begin, strIter end);
void markContent(strIter begin, strIter end);
void markAll(strIter begin, strIter end);
protected:
strIter _beg,
_end,
_name_beg,
_name_end,
_cont_beg,
_cont_end;
};
typedef Section EqlSection;
// The parser class
class Parser
{
public:
// init, tell the parser where to begin and end
void init(strIter begin, strIter end);
// usage, use nextSection() first, then use currentSection() to
// get
bool virtual nextSection();
Section virtual currentSection();
bool isEnd();
protected:
strIter _begin,
_end,
_current;
Section _section;
};
class EqlParser: public Parser
{
public:
bool virtual nextSection();
protected:
//none
};
bool decode(const strIter begin,
const strIter end,
string & result);
bool encode(const strIter begin,
const strIter end,
string & result);
#endif
|
Python
|
UTF-8
| 223
| 3.046875
| 3
|
[] |
no_license
|
import sys
import time
if len(sys.argv)>1:
filename = sys.argv[1]
file = open(filename, 'w')
temp=0
while(temp<=100):
text = file.write('a')
time.sleep(0.1)
temp+=1
file.close()
|
Python
|
UTF-8
| 4,149
| 2.8125
| 3
|
[] |
no_license
|
import copy
import numpy as np
import math
from common.game import Board
import random
class Edge():
def __init__(self, move, parentNode):
self.parentNode = parentNode
self.move = move
self.N = 0
self.W = 0
self.Q = 0
self.P = 0
class Node():
def __init__(self, board, parentEdge):
self.board = board
self.parentEdge = parentEdge
self.childEdgeNode = []
def expand(self, network):
moves = self.board.generateMoves()
for m in moves:
child_board = copy.deepcopy(self.board)
child_board.applyMove(m)
child_edge = Edge(m, self)
childNode = Node(child_board, child_edge)
self.childEdgeNode.append((child_edge,childNode))
q = network.predict(np.array([self.board.toNetworkInput()]))
prob_sum = 0.
for (edge,_) in self.childEdgeNode:
m_idx = self.board.getNetworkOutputIndex(edge.move)
edge.P = q[0][0][m_idx]
prob_sum += edge.P
for edge,_ in self.childEdgeNode:
edge.P /= prob_sum
v = q[1][0][0]
return v
def isLeaf(self):
return self.childEdgeNode == []
class MCTS():
def __init__(self, network):
self.network = network
self.rootNode = None
self.tau = 1.0
self.c_puct = 1.0
def uctValue(self, edge, parentN):
return self.c_puct * edge.P * (math.sqrt(parentN) / (1+edge.N))
def select(self, node):
if(node.isLeaf()):
return node
else:
maxUctChild = None
maxUctValue = -100000000.
for edge, child_node in node.childEdgeNode:
uctVal = self.uctValue(edge, edge.parentNode.parentEdge.N)
val = edge.Q
if(edge.parentNode.board.turn == Board.BLACK):
val = -edge.Q
uctValChild = val + uctVal
if(uctValChild > maxUctValue):
maxUctChild = child_node
maxUctValue = uctValChild
allBestChilds = []
for edge, child_node in node.childEdgeNode:
uctVal = self.uctValue(edge, edge.parentNode.parentEdge.N)
val = edge.Q
if(edge.parentNode.board.turn == Board.BLACK):
val = -edge.Q
uctValChild = val + uctVal
if(uctValChild == maxUctValue):
allBestChilds.append(child_node)
if(maxUctChild == None):
raise ValueError("could not identify child with best uct value")
else:
if(len(allBestChilds) > 1):
idx = random.randint(0, len(allBestChilds)-1)
return self.select(allBestChilds[idx])
else:
return self.select(maxUctChild)
def expandAndEvaluate(self, node):
terminal, winner = node.board.isTerminal()
if(terminal == True):
v = 0.0
if(winner == Board.WHITE):
v = 1.0
if(winner == Board.BLACK):
v = -1.0
self.backup(v, node.parentEdge)
return
v = node.expand(self.network)
self.backup(v, node.parentEdge)
def backup(self, v, edge):
edge.N += 1
edge.W = edge.W + v
edge.Q = edge.W / edge.N
if(edge.parentNode != None):
if(edge.parentNode.parentEdge != None):
self.backup(v, edge.parentNode.parentEdge)
def search(self, rootNode):
self.rootNode = rootNode
_ = self.rootNode.expand(self.network)
for i in range(0,100):
selected_node = self.select(rootNode)
self.expandAndEvaluate(selected_node)
N_sum = 0
moveProbs = []
for edge, _ in rootNode.childEdgeNode:
N_sum += edge.N
for (edge, node) in rootNode.childEdgeNode:
prob = (edge.N ** (1 / self.tau)) / ((N_sum) ** (1/self.tau))
moveProbs.append((edge.move, prob, edge.N, edge.Q))
return moveProbs
|
Markdown
|
UTF-8
| 1,039
| 2.828125
| 3
|
[] |
no_license
|
# Article L233-1
Le contrat conclu par un éditeur de services de télévision pour l'acquisition de droits relatifs à la diffusion d'une œuvre
cinématographique prévoit le délai au terme duquel cette diffusion peut intervenir.
Lorsqu'il existe un accord professionnel portant sur le délai applicable au mode d'exploitation des œuvres cinématographiques
par les services de télévision, le délai prévu par cet accord s'impose aux éditeurs de services et aux membres des
organisations professionnelles signataires. Cet accord peut porter sur une ou plusieurs catégories de services. Il peut être
rendu obligatoire pour l'ensemble des intéressés des secteurs d'activité et des éditeurs de services concernés dans les
conditions prévues à l'article L. 234-1.
**Liens relatifs à cet article**
_Créé par_:
- Ordonnance n°2009-901 du 24 juillet 2009 - art.
_Anciens textes_:
- Code de l'industrie cinématographique - art. 30-6 (Ab)
_Cité par_:
- Code du cinéma et de l'image animée - art. L234-1 (V)
|
C#
|
UTF-8
| 1,017
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KancolleBgmChenger
{
/// <summary>
/// KanColleViewerからもらうエンドポイントからのセッション通信を管理するクラス
/// </summary>
public class EndPointPath
{
private uint id; //ID
private string endPointPath; //受信待ちするエンドポイントのパス
private AnalysisEndPoint callBackClass;
public uint ID { get { return id; } }
public string EventPath { get { return endPointPath; } }
public AnalysisEndPoint CallbackClass { get { return callBackClass; } }
public EndPointPath(
uint _id,
string _endPointPath,
AnalysisEndPoint _callBackClass)
{
//ID
id = _id;
endPointPath = _endPointPath;
callBackClass = _callBackClass;
}
}
}
|
JavaScript
|
UTF-8
| 663
| 3.5
| 4
|
[] |
no_license
|
/*
AM Warm Up Assignment (11/8/19):
1.) create new file secondServer.js
2.) write, line by line, a new Express server
3.) use port 3000 & console.log() the port
4.) no routes required
*/
// require Express:
const express = require("express");
// instantiate an application via the express() method:
const app = express();
// require http package & create a new object of the Server class:
const http = require("http").Server(app);
// set port number:
const port = 3000;
// tell http which port web server should use:
http.listen(port);
// console.log() which port server is using:
console.log(`Congrats! Your web server is active and using port ${port}.`);
|
Go
|
UTF-8
| 3,510
| 2.796875
| 3
|
[] |
no_license
|
package site
import (
"dna"
"dna/hdv"
"dna/sqlpg"
"time"
)
// UpdateHDViet gets lastest items from hdviet.com.
//
// The update process goes through 8 steps and 2 parts:
//
// PART I: FINDING AND UPDATING NEW EPS OF MOVIES IN DB
// Step 1: Initalizing db connection, loading site config and state handler.
// Step 2: Finding all movies possibly having new episodes in DB
// Step 3: Finding all movies found in Step 2 actually having new episodes available from source website.
// Step 4: Checking consitency of movies' new found episodes from the source.
// Step 5: Getting new episode data from the source, save them to DB and update current_eps field of movies having new eps.
//
// PART II: GETTING NEW MOVIES FROM HDVIET SITE.
// Step 6: Find newest movies from the source.
// Step 7: Updating newest episodes from newest found movies in Step 6.
// Step 8: Recovering failed sql statements.
func UpdateHDViet() {
var mvTable = dna.String("hdvmovies")
db, err := sqlpg.Connect(sqlpg.NewSQLConfig(SqlConfigPath))
dna.PanicError(err)
siteConf, err := LoadSiteConfig("hdv", SiteConfigPath)
dna.PanicError(err)
TIMEOUT_SECS = 100
// PART 1: UPDATING NEW EPISODES OF MOVIES IN DB
// STEP 2: Finding all movies possibly having new episodes in DB.
movieCurrentEps, err := hdv.GetMoviesCurrentEps(db, mvTable)
dna.PanicError(err)
newEpisodeKeys := dna.IntArray{}
for movieid, currentEps := range movieCurrentEps {
newEpisodeKeys.Push(hdv.ToEpisodeKey(movieid, currentEps))
}
newEpisodeKeys.Sort()
// STEP 3: Checking and getting new episodes if available from source website.
state := NewStateHandlerWithExtSlice(new(hdv.EpUpdater), &newEpisodeKeys, siteConf, db)
Update(state)
// STEP 4:Checking consitency of new found episodes of movies from the source.
movieIdList := dna.IntArray{}
for _, epKey := range hdv.LastestEpisodeKeyList {
mvid, _ := hdv.ToMovieIdAndEpisodeId(epKey)
movieIdList.Push(mvid)
}
movieIdList = movieIdList.Unique()
dna.Log("\nNumber of movies: ", movieIdList.Length(), "having new episodes:", hdv.LastestEpisodeKeyList.Length())
if movieIdList.Length() != dna.Int(len(hdv.LastestMovieCurrentEps)) {
dna.Log("LastestEpisodeKeyList & LastestMovieCurrentEps do not match! GOT:", movieIdList.Length(), len(hdv.LastestMovieCurrentEps))
}
// STEP 5: Getting new episode data from the source, save them to DB and update current_eps field of movies having new eps.
if hdv.LastestEpisodeKeyList.Length() > 0 {
state = NewStateHandlerWithExtSlice(new(hdv.Episode), &hdv.LastestEpisodeKeyList, siteConf, db)
Update(state)
RecoverErrorQueries(SqlErrorLogPath, db)
// dna.Log(hdv.LastestEpisodeKeyList)
hdv.SaveLastestMovieCurrentEps(db, mvTable, SQLERROR)
RecoverErrorQueries(SqlErrorLogPath, db)
} else {
dna.Log("No new episodes found. Update operation has been aborted!")
}
// PART 2: UPDATING NEW MOVIES FROM hdv site.
// STEP 6: Find newest movies from sources.
db.Ping()
state = NewStateHandler(new(hdv.Movie), siteConf, db)
Update(state)
// STEP 7: Updating newest episodes from newest found movies in Step 6.
hdv.EpisodeKeyList = hdv.EpisodeKeyList.Unique()
if hdv.EpisodeKeyList.Length() > 0 {
state = NewStateHandlerWithExtSlice(new(hdv.Episode), &hdv.EpisodeKeyList, siteConf, db)
Update(state)
} else {
dna.Log("No new movies found")
}
// STEP 8: Recovering failed sql statements.
RecoverErrorQueries(SqlErrorLogPath, db)
CountDown(3*time.Second, QuittingMessage, EndingMessage)
db.Close()
}
|
TypeScript
|
UTF-8
| 991
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import { workspace } from "vscode";
import ConfigurationError from "./ConfigurationError";
type Content = string[];
type Commands = string[];
const extractCommands = (filePath: string): Promise<Commands> =>
getFileContent(filePath).then(buildCommands);
export default extractCommands;
const getFileContent = async (filePath: string): Promise<Content> => {
let document;
try {
document = await workspace.openTextDocument(filePath);
} catch (e) {
throw new ConfigurationError(
'Makefile cannot be read. Check the configuration and update the makefilePath'
);
}
const content = document.getText().split("\n");
return content;
};
const buildCommands = (content: Content) => {
const commands = [];
for (let i = 0; i < content.length; i++) {
const line = content[i];
const separator = ": ##";
if (line.indexOf(": ##") !== -1) {
const command = line.split(separator)[0];
commands.push(command);
}
}
return commands;
};
|
C#
|
UTF-8
| 1,111
| 3.90625
| 4
|
[] |
no_license
|
using System;
namespace FibonacciNumbers
{
class FibonacciNumbers
{
static void Main(string[] args)
{
Console.Write("Какой член ряда Фибоначчи Вы хотите увидеть?: ");
int number = Convert.ToInt32(Console.ReadLine());
if (number > 48)
{
Console.WriteLine("Программа считает только до 48 члена ряда Фибоначчи");
}
else if (number < 0)
{
Console.WriteLine("В ряде Фибоначчи нет такого элемента.");
}
else
{
int first = 0;
int second = 1;
int i = 1;
while (i <= number)
{
int sum = first + second;
first = second;
second = sum;
i++;
}
Console.WriteLine("Число Фибоначчи = " + first);
}
}
}
}
|
Python
|
UTF-8
| 204
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
from __future__ import print_function
import fileinput, hashlib
h = hashlib.sha256()
for line in fileinput.input(mode='rb'):
h.update(line)
print(h.hexdigest()[:4], line.decode('utf-8'), end='')
|
Java
|
UTF-8
| 26,495
| 2.1875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.vaadin.tests.components;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import com.vaadin.event.FieldEvents.BlurEvent;
import com.vaadin.event.FieldEvents.BlurListener;
import com.vaadin.event.FieldEvents.BlurNotifier;
import com.vaadin.event.FieldEvents.FocusEvent;
import com.vaadin.event.FieldEvents.FocusListener;
import com.vaadin.event.FieldEvents.FocusNotifier;
import com.vaadin.server.DefaultErrorHandler;
import com.vaadin.server.Resource;
import com.vaadin.server.ThemeResource;
import com.vaadin.tests.util.Log;
import com.vaadin.tests.util.LoremIpsum;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.Component.Focusable;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.themes.BaseTheme;
public abstract class AbstractComponentTest<T extends AbstractComponent>
extends AbstractComponentTestCase<T> implements FocusListener,
BlurListener {
protected static final String TEXT_SHORT = "Short";
protected static final String TEXT_MEDIUM = "This is a semi-long text that might wrap.";
protected static final String TEXT_LONG = "This is a long text. "
+ LoremIpsum.get(500);
protected static final String TEXT_VERY_LONG = "This is a very, very long text. "
+ LoremIpsum.get(5000);
private static final Resource SELECTED_ICON = new ThemeResource(
"../runo/icons/16/ok.png");
private static final LinkedHashMap<String, String> sizeOptions = new LinkedHashMap<String, String>();
static {
sizeOptions.put("auto", null);
sizeOptions.put("50%", "50%");
sizeOptions.put("100%", "100%");
for (int w = 200; w < 1000; w += 100) {
sizeOptions.put(w + "px", w + "px");
}
}
// Menu related
private MenuItem mainMenu;
private MenuBar menu;
private MenuItem settingsMenu;
private T component;
// Used to determine if a menuItem should be selected and the other
// unselected on click
private Set<MenuItem> parentOfSelectableMenuItem = new HashSet<MenuItem>();
/**
* Maps the category name to a menu item
*/
private Map<String, MenuItem> categoryToMenuItem = new HashMap<String, MenuItem>();
private Map<MenuItem, String> menuItemToCategory = new HashMap<MenuItem, String>();
// Logging
private Log log;
protected static final String CATEGORY_STATE = "State";
protected static final String CATEGORY_SIZE = "Size";
protected static final String CATEGORY_SELECTION = "Selection";
protected static final String CATEGORY_LISTENERS = "Listeners";
protected static final String CATEGORY_FEATURES = "Features";
protected static final String CATEGORY_ACTIONS = "Actions";
protected static final String CATEGORY_DECORATIONS = "Decorations";
@Override
protected final void setup() {
setTheme("tests-components");
// Create menu here so it appears before the components
addComponent(createMainMenu());
getLayout().setSizeFull();
createLog();
super.setup();
// Create menu actions and trigger default actions
createActions();
// Clear initialization log messages
log.clear();
}
private MenuBar createMainMenu() {
menu = new MenuBar();
menu.setId("menu");
mainMenu = menu.addItem("Component", null);
settingsMenu = menu.addItem("Settings", null);
populateSettingsMenu(settingsMenu);
return menu;
}
/**
* Override to add items to the "settings" menu.
*
* NOTE, Call super class first to preserve current order. If you override
* this in a class and another class overrides it you might break tests
* because the wrong items will be selected.
*
* @param settingsMenu
*/
protected void populateSettingsMenu(MenuItem settingsMenu) {
MenuItem showEventLog = settingsMenu.addItem("Show event log",
new MenuBar.Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
boolean selected = !isSelected(selectedItem);
setLogVisible(selected);
setSelected(selectedItem, selected);
}
});
setSelected(showEventLog, true);
settingsMenu.addItem("Clear log", new MenuBar.Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
log.clear();
}
});
MenuItem layoutSize = settingsMenu.addItem("Parent layout size", null);
MenuItem layoutWidth = layoutSize.addItem("Width", null);
MenuItem layoutHeight = layoutSize.addItem("Height", null);
for (final String name : sizeOptions.keySet()) {
layoutWidth.addItem(name, new MenuBar.Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
getTestComponents().get(0).getParent()
.setWidth(sizeOptions.get(name));
log("Parent layout width set to " + name);
}
});
layoutHeight.addItem(name, new MenuBar.Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
getTestComponents().get(0).getParent()
.setHeight(sizeOptions.get(name));
log("Parent layout height set to " + name);
}
});
}
}
protected void setLogVisible(boolean visible) {
// This is only to be screenshot-compatible with Vaadin 6, where
// invisible components cause spacing
if (visible) {
log.removeStyleName("displaynone");
log.setCaption((String) log.getData());
} else {
log.addStyleName("displaynone");
log.setCaption(null);
}
}
private void createLog() {
log = new Log(5).setNumberLogRows(true);
log.setData(log.getCaption());
log.setStyleName(BaseTheme.CLIP);
getLayout().addComponent(log, 1);
}
/**
* By default initializes just one instance of {@link #getTestClass()} using
* {@link #constructComponent()}.
*/
@Override
protected void initializeComponents() {
component = constructComponent();
component.setId("testComponent");
addTestComponent(component);
}
public T getComponent() {
return component;
}
@Override
protected void addTestComponent(T c) {
super.addTestComponent(c);
getLayout().setExpandRatio(c, 1);
}
/**
* Construct the component that is to be tested. This method uses a no-arg
* constructor by default. Override to customize.
*
* @return Instance of the component that is to be tested.
* @throws IllegalAccessException
* @throws InstantiationException
*/
protected T constructComponent() {
try {
return getTestClass().newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to instantiate "
+ getTestClass(), e);
}
}
/**
* Create actions for the component. Remember to call super.createActions()
* when overriding.
*/
protected void createActions() {
createBooleanAction("Immediate", CATEGORY_STATE, true, immediateCommand);
createBooleanAction("Enabled", CATEGORY_STATE, true, enabledCommand);
createBooleanAction("Readonly", CATEGORY_STATE, false, readonlyCommand);
createBooleanAction("Visible", CATEGORY_STATE, true, visibleCommand);
createBooleanAction("Error indicator", CATEGORY_STATE, false,
errorIndicatorCommand);
createLocaleSelect(CATEGORY_STATE);
createErrorMessageSelect(CATEGORY_DECORATIONS);
createDescriptionSelect(CATEGORY_DECORATIONS);
createCaptionSelect(CATEGORY_DECORATIONS);
createIconSelect(CATEGORY_DECORATIONS);
createWidthAndHeightActions(CATEGORY_SIZE);
createStyleNameSelect(CATEGORY_DECORATIONS);
createFocusActions();
}
protected Command<T, Boolean> focusListenerCommand = new Command<T, Boolean>() {
@Override
public void execute(T c, Boolean value, Object data) {
FocusNotifier fn = (FocusNotifier) c;
if (value) {
fn.addFocusListener(AbstractComponentTest.this);
} else {
fn.removeFocusListener(AbstractComponentTest.this);
}
}
};
protected Command<T, Boolean> blurListenerCommand = new Command<T, Boolean>() {
@Override
public void execute(T c, Boolean value, Object data) {
BlurNotifier bn = (BlurNotifier) c;
if (value) {
bn.addBlurListener(AbstractComponentTest.this);
} else {
bn.removeBlurListener(AbstractComponentTest.this);
}
}
};
protected void createFocusListener(String category) {
createBooleanAction("Focus listener", category, false,
focusListenerCommand);
}
protected void createBlurListener(String category) {
createBooleanAction("Blur listener", category, false,
blurListenerCommand);
}
private void createFocusActions() {
if (FocusNotifier.class.isAssignableFrom(getTestClass())) {
createFocusListener(CATEGORY_LISTENERS);
}
if (BlurNotifier.class.isAssignableFrom(getTestClass())) {
createBlurListener(CATEGORY_LISTENERS);
}
if (Focusable.class.isAssignableFrom(getTestClass())) {
LinkedHashMap<String, Integer> tabIndexes = new LinkedHashMap<String, Integer>();
tabIndexes.put("0", 0);
tabIndexes.put("-1", -1);
tabIndexes.put("10", 10);
createSelectAction("Tab index", "State", tabIndexes, "0",
new Command<T, Integer>() {
@Override
public void execute(T c, Integer tabIndex, Object data) {
((Focusable) c).setTabIndex(tabIndex);
}
});
createClickAction("Set focus", "State", new Command<T, Void>() {
@Override
public void execute(T c, Void value, Object data) {
((Focusable) c).focus();
}
}, null);
}
}
private void createStyleNameSelect(String category) {
LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
options.put("-", null);
options.put("Light blue background (background-lightblue)",
"background-lightblue");
options.put("1px red border (border-red-1px)", "border-red-1px");
options.put("2px blue border (border-blue-2px)", "border-blue-2px");
createComponentStyleNames(options);
createSelectAction("Style name", category, options, "-",
styleNameCommand);
}
protected void createComponentStyleNames(
LinkedHashMap<String, String> options) {
}
private void createErrorMessageSelect(String category) {
LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
options.put("-", null);
options.put(TEXT_SHORT, TEXT_SHORT);
options.put("Medium", TEXT_MEDIUM);
options.put("Long", TEXT_LONG);
options.put("Very long", TEXT_VERY_LONG);
createSelectAction("Error message", category, options, "-",
errorMessageCommand);
}
private void createDescriptionSelect(String category) {
LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
options.put("-", null);
options.put(TEXT_SHORT, TEXT_SHORT);
options.put("Medium", TEXT_MEDIUM);
options.put("Long", TEXT_LONG);
options.put("Very long", TEXT_VERY_LONG);
createSelectAction("Description / tooltip", category, options, "-",
descriptionCommand);
}
private void createCaptionSelect(String category) {
createSelectAction("Caption", category, createCaptionOptions(),
"Short", captionCommand);
}
protected LinkedHashMap<String, String> createCaptionOptions() {
LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
options.put("-", null);
options.put("Short", TEXT_SHORT);
options.put("Medium", TEXT_MEDIUM);
options.put("Long", TEXT_LONG);
options.put("Very long", TEXT_VERY_LONG);
return options;
}
private void createWidthAndHeightActions(String category) {
String widthCategory = "Width";
String heightCategory = "Height";
createCategory(widthCategory, category);
createCategory(heightCategory, category);
for (String name : sizeOptions.keySet()) {
createClickAction(name, widthCategory, widthCommand,
sizeOptions.get(name));
createClickAction(name, heightCategory, heightCommand,
sizeOptions.get(name));
}
// Default to undefined size
for (T c : getTestComponents()) {
c.setWidth(null);
c.setHeight(null);
}
}
private void createIconSelect(String category) {
LinkedHashMap<String, Resource> options = new LinkedHashMap<String, Resource>();
options.put("-", null);
options.put("16x16", ICON_16_USER_PNG_CACHEABLE);
options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE);
options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE);
createSelectAction("Icon", category, options, "-", iconCommand, null);
}
private void createLocaleSelect(String category) {
LinkedHashMap<String, Locale> options = new LinkedHashMap<String, Locale>();
options.put("-", null);
options.put("fi_FI", new Locale("fi", "FI"));
options.put("en_US", Locale.US);
options.put("zh_CN", Locale.SIMPLIFIED_CHINESE);
options.put("fr_FR", Locale.FRANCE);
createSelectAction("Locale", category, options, "en_US", localeCommand,
null);
}
protected void createBooleanAction(String caption, String category,
boolean initialState, final Command<T, Boolean> command) {
createBooleanAction(caption, category, initialState, command, null);
}
protected <DATATYPE> void createBooleanAction(String caption,
String category, boolean initialState,
final Command<T, Boolean> command, Object data) {
MenuItem categoryItem = getCategoryMenuItem(category);
MenuItem item = categoryItem.addItem(caption,
menuBooleanCommand(command, data));
setSelected(item, initialState);
doCommand(caption, command, initialState, data);
}
protected <DATATYPE> void createClickAction(String caption,
String category, final Command<T, DATATYPE> command, DATATYPE value) {
createClickAction(caption, category, command, value, null);
}
protected <DATATYPE> void createClickAction(String caption,
String category, final Command<T, DATATYPE> command,
DATATYPE value, Object data) {
MenuItem categoryItem = getCategoryMenuItem(category);
categoryItem.addItem(caption, menuClickCommand(command, value, data));
}
private MenuItem getCategoryMenuItem(String category) {
if (category == null) {
return getCategoryMenuItem("Misc");
}
MenuItem item = categoryToMenuItem.get(category);
if (item != null) {
return item;
}
return createCategory(category, null);
}
/**
* Creates category named "category" with id "categoryId" in parent category
* "parentCategory". Each categoryId must be globally unique.
*
* @param category
* @param categoryId
* @param parentCategory
* @return
*/
protected MenuItem createCategory(String category, String parentCategory) {
if (hasCategory(category)) {
return categoryToMenuItem.get(category);
}
MenuItem item;
if (parentCategory == null) {
item = mainMenu.addItem(category, null);
} else {
item = getCategoryMenuItem(parentCategory).addItem(category, null);
}
categoryToMenuItem.put(category, item);
menuItemToCategory.put(item, category);
return item;
}
protected boolean hasCategory(String categoryId) {
return categoryToMenuItem.containsKey(categoryId);
}
protected void removeCategory(String categoryId) {
if (!hasCategory(categoryId)) {
throw new IllegalArgumentException("Category '" + categoryId
+ "' does not exist");
}
MenuItem item = getCategoryMenuItem(categoryId);
Object[] children = item.getChildren().toArray();
for (Object child : children) {
if (menuItemToCategory.containsKey(child)) {
removeCategory(menuItemToCategory.get(child));
}
}
// Detach from parent
item.getParent().removeChild(item);
// Clean mappings
categoryToMenuItem.remove(categoryId);
menuItemToCategory.remove(item);
}
private MenuBar.Command menuBooleanCommand(
final com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> booleanCommand,
final Object data) {
return new MenuBar.Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
boolean selected = !isSelected(selectedItem);
doCommand(getText(selectedItem), booleanCommand, selected, data);
setSelected(selectedItem, selected);
}
};
}
private <DATATYPE> MenuBar.Command menuClickCommand(
final com.vaadin.tests.components.ComponentTestCase.Command<T, DATATYPE> command,
final DATATYPE value, final Object data) {
return new MenuBar.Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
doCommand(getText(selectedItem), command, value, data);
}
};
}
protected void setSelected(MenuItem item, boolean selected) {
if (selected) {
item.setIcon(SELECTED_ICON);
} else {
item.setIcon(null);
}
}
protected boolean isSelected(MenuItem item) {
return (item.getIcon() != null);
}
private <VALUETYPE> MenuBar.Command singleSelectMenuCommand(
final com.vaadin.tests.components.ComponentTestCase.Command<T, VALUETYPE> cmd,
final VALUETYPE object, final Object data) {
return new MenuBar.Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
doCommand(getText(selectedItem), cmd, object, data);
if (parentOfSelectableMenuItem.contains(selectedItem
.getParent())) {
unselectChildren(selectedItem.getParent());
setSelected(selectedItem, true);
}
}
};
}
/**
* Unselect all child menu items
*
* @param parent
*/
protected void unselectChildren(MenuItem parent) {
List<MenuItem> children = parent.getChildren();
if (children == null) {
return;
}
for (MenuItem child : children) {
setSelected(child, false);
}
}
protected String getText(MenuItem item) {
String path = "";
MenuItem parent = item.getParent();
while (!isCategory(parent)) {
path = parent.getText() + "/" + path;
parent = parent.getParent();
}
return path + "/" + item.getText();
}
private boolean isCategory(MenuItem item) {
return item.getParent() == mainMenu;
}
protected <TYPE> void createSelectAction(
String caption,
String category,
LinkedHashMap<String, TYPE> options,
String initialValue,
com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command) {
createSelectAction(caption, category, options, initialValue, command,
null);
}
protected <TYPE> void createMultiClickAction(
String caption,
String category,
LinkedHashMap<String, TYPE> options,
com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command,
Object data) {
MenuItem categoryItem = getCategoryMenuItem(category);
MenuItem mainItem = categoryItem.addItem(caption, null);
for (String option : options.keySet()) {
MenuBar.Command cmd = menuClickCommand(command,
options.get(option), data);
mainItem.addItem(option, cmd);
}
}
protected <TYPE> void createMultiToggleAction(
String caption,
String category,
LinkedHashMap<String, TYPE> options,
com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> command,
boolean defaultValue) {
LinkedHashMap<String, Boolean> defaultValues = new LinkedHashMap<String, Boolean>();
for (String option : options.keySet()) {
defaultValues.put(option, defaultValue);
}
createMultiToggleAction(caption, category, options, command,
defaultValues);
}
protected <TYPE> void createMultiToggleAction(
String caption,
String category,
LinkedHashMap<String, TYPE> options,
com.vaadin.tests.components.ComponentTestCase.Command<T, Boolean> command,
LinkedHashMap<String, Boolean> defaultValues) {
createCategory(caption, category);
for (String option : options.keySet()) {
createBooleanAction(option, caption, defaultValues.get(option),
command, options.get(option));
}
}
protected <TYPE> void createSelectAction(
String caption,
String category,
LinkedHashMap<String, TYPE> options,
String initialValue,
com.vaadin.tests.components.ComponentTestCase.Command<T, TYPE> command,
Object data) {
MenuItem parentItem = getCategoryMenuItem(category);
MenuItem mainItem = parentItem.addItem(caption, null);
parentOfSelectableMenuItem.add(mainItem);
for (String option : options.keySet()) {
MenuBar.Command cmd = singleSelectMenuCommand(command,
options.get(option), data);
MenuItem item = mainItem.addItem(option, cmd);
if (option.equals(initialValue)) {
cmd.menuSelected(item);
}
}
}
protected LinkedHashMap<String, Integer> createIntegerOptions(int max) {
LinkedHashMap<String, Integer> options = new LinkedHashMap<String, Integer>();
for (int i = 0; i <= 9 && i <= max; i++) {
options.put(String.valueOf(i), i);
}
for (int i = 10; i <= max; i *= 10) {
options.put(String.valueOf(i), i);
if (2 * i <= max) {
options.put(String.valueOf(2 * i), 2 * i);
}
if (5 * i <= max) {
options.put(String.valueOf(5 * i), 5 * i);
}
}
return options;
}
protected LinkedHashMap<String, Double> createDoubleOptions(double max) {
LinkedHashMap<String, Double> options = new LinkedHashMap<String, Double>();
for (double d = 0; d <= max && d < 10; d += 0.5) {
options.put(String.valueOf(d), d);
}
for (double d = 10; d <= max; d *= 10) {
options.put(String.valueOf(d), d);
if (2.5 * d <= max) {
options.put(String.valueOf(2 * d), 2 * d);
}
if (5 * d <= max) {
options.put(String.valueOf(5 * d), 5 * d);
}
}
return options;
}
protected LinkedHashMap<String, Resource> createIconOptions(
boolean cacheable) {
LinkedHashMap<String, Resource> options = new LinkedHashMap<String, Resource>();
options.put("-", null);
if (cacheable) {
options.put("16x16", ICON_16_USER_PNG_CACHEABLE);
options.put("32x32", ICON_32_ATTENTION_PNG_CACHEABLE);
options.put("64x64", ICON_64_EMAIL_REPLY_PNG_CACHEABLE);
} else {
options.put("16x16", ICON_16_USER_PNG_UNCACHEABLE);
options.put("32x32", ICON_32_ATTENTION_PNG_UNCACHEABLE);
options.put("64x64", ICON_64_EMAIL_REPLY_PNG_UNCACHEABLE);
}
return options;
}
protected void log(String msg) {
log.log(msg);
}
protected boolean hasLog() {
return log != null;
}
@Override
protected <VALUET> void doCommand(String commandName,
AbstractComponentTestCase.Command<T, VALUET> command, VALUET value,
Object data) {
if (hasLog()) {
log("Command: " + commandName + "(" + value + ")");
}
super.doCommand(commandName, command, value, data);
}
@Override
public void error(com.vaadin.server.ErrorEvent event) {
final Throwable throwable = DefaultErrorHandler
.findRelevantThrowable(event.getThrowable());
log.log("Exception occured, " + throwable.getClass().getName() + ": "
+ throwable.getMessage());
throwable.printStackTrace();
}
@Override
public void focus(FocusEvent event) {
log(event.getClass().getSimpleName());
}
@Override
public void blur(BlurEvent event) {
log(event.getClass().getSimpleName());
}
}
|
C
|
UTF-8
| 873
| 3.09375
| 3
|
[] |
no_license
|
#include <stdio.h>
int main()
{
int id;
char name[100];
float unit,cost,unitfee,surchage;
scanf("%d",&id);
fflush(stdin);
gets(name);
scanf("%f",&unit);
if(unit<=199)
{
cost=unit*1.20;
unitfee=1.20;
}
else if(unit>=200&&unit<400)
{
cost=unit*1.50;
unitfee=1.50;
}
else if(unit>=400&&unit<600)
{
cost=unit*1.80;
unitfee=1.80;
}
else
{
cost=unit*2.00;
unitfee=2.00;
}
printf("customer IDNO: %d\n",id);
printf("customer Name: %s\n",name);
printf("amount charge@Rs.%.2f per unit: %.2f taka\n",unitfee,cost);
if(cost>=400)
{ surchage=cost*0.15;
if(surchage<100)
surchage=100;
}
printf("surchage ammount: %.2f\n",surchage);
printf("net amount paid by customer: %.2f\n",cost+surchage);
}
|
Markdown
|
UTF-8
| 8,887
| 3.21875
| 3
|
[] |
no_license
|
# HW 2: Grapheme-to-phoneme conversion
In this assignment you will use [FairSeq](https://github.com/pytorch/fairseq), a
neural network sequence-to-sequence learning tool, to build an [encoder-decoder
LSTM](https://fairseq.readthedocs.io/en/latest/models.html#module-fairseq.models.lstm)
grapheme-to-phoneme engine for Icelandic.
Icelandic is written in a Roman script but the mapping from spelling to
pronunciation regular but rather complex.
This repository contains three data files:
- training data: [`ice_train.tsv`](ice_train.tsv) is a two-column TSV file in
which the first column is a Icelandic word in UTF-8, and the second column
gives that word's space-delimited IPA transcription in UTF-8. There are 800
training examples in all. For instance, the row
auga ø yː ɣ a
indicates that *auga* 'eye' is pronounced \[øyːɣa\].
- development data: [`ice_dev.tsv`](ice_dev.tsv) is a two-column, 100-row TSV
file in the same format as the previous file.
- test data: [`ice_test.tsv`](ice_test.tsv) is a two-column, 100-row TSV file
in the same format as the previous two files.
## Part 1: environment preparation
First, set up your environment.
### What to do
Install FairSeq:
pip install fairseq==0.10.2
### What to turn in
Nothing for this part of the assignment.
### Hints
If the above command fails with an error message reading:
Sorry, Python >= 3.6 is required for fairseq.
Then you are using an (ancient) system Python instead of Conda. Please just use
Conda instead.
## Part 2: preprocessing
FairSeq requires you to "preprocess" the data into binary files that it can read
into memory rapidly during training, development, and testing. Preprocessing is
performed by the
[`fairseq-preprocess`](https://fairseq.readthedocs.io/en/latest/command_line_tools.html#fairseq-preprocess)
command-line tool. This tool takes a series of arguments specifying the location
of the data and how it to be "tokenized" into graphemes and phones. Because this
tool makes certain assumptions about the format of your data, you will have to
first convert the aforementioned TSV and text files as follows:
1. Write the first column of [`ice_train.tsv`](ice_train.tsv) to a file called
`train.ice.g`. You must also place a space between each UTF-8 character.
Thus, the row
auga ø yː ɣ a
would appear in `train.ice.g` as
a u g a
2. Write the second column of [`ice_train.tsv`](ice_train.tsv) to a file called
`train.ice.p`. The data has already been segmented with spaces *so do not
add additional spaces*. Thus the aforementioned row would appear in
`train.ice.p` as
ø yː ɣ a
3. Write the first column of [`ice_dev.tsv`](ice_dev.tsv) to a file called
`dev.ice.g` using the same style as you did in step 1.
4. Write the second column of [`ice_dev.tsv`](ice_dev.tsv) to a file called
`dev.ice.p` using the same style as you did in step 2.
5. Write the first column of [`ice_test.tsv`](ice_test.tsv) to a file called
`test.ice.g` using the same style as you did in steps 1 and 3.
6. Write the second column of [`ice_test.tsv`](ice_test.tsv) to a file called
`test.ice.p` using the same style as you did in steps 2 and 4.
Then, call `fairseq-preprocess` as follows:
fairseq-preprocess \
--source-lang ice.g \
--target-lang ice.p \
--trainpref train \
--validpref dev \
--testpref test \
--tokenizer space \
--thresholdsrc 2 \
--thresholdtgt 2
### What to turn in
1. All Python code you used to prepare the data.
2. The logging output from `fairseq-preprocess`.
### Hints
- The `\` character used at the end of a lines above is a "continuation": it
indicates that the current command continues on the next line. You yourself
do not need to type it in at the command line.
- You need to name the files exactly what I say: `fairseq-preprocess` is
finicky like that.
- Visually inspect all six `.g` and `.p` files before attempting to call
`fairseq-preprocess`; confirm there are no blank lines and that there are
spaces between grapheme and phone symbols.
- Read the [the
docs](https://fairseq.readthedocs.io/en/latest/command_line_tools.html#fairseq-preprocess)
for `fairseq-preprocess`.
- If you call `fairseq-preprocess` multiple times it may crash with a
`FileExistsError`. If you see this error, simply remove the `data-bin`
directory and try again.
## Part 3: training
Model training is performed by the
[`fairseq-train`](https://fairseq.readthedocs.io/en/latest/command_line_tools.html#fairseq-train)
command-line tool.
#### What to do
Using `fairseq-train`, train the model. You should use the following parameters:
- random seed: pick some random number
- architecture: LSTM
- bidirectional encoder
- dropout probability .2
- encoder embedding dimensionality: 128
- decoder embedding dimensionality: 128
- decoder output embedding dimensionality: 128
- encoder hidden layer size: 512
- decoder hidden layer size: 512
- criterion: label-smoothed cross-entropy
- label smoothing coefficient: .1
- optimizer: Adam
- learning rate: .001
- norm clipping coefficient: 1
- batch size: 50
- maximum number of updates: 800
- don't store epoch checkpoints
If successful, this will produce two large model files in a `checkpoints`
directory.
### What to turn in
The `fairseq-train` command you ran.
#### Hints
- You do not need to write any Python for this step; your goal here is to read
the documentation carefully and figure out how to get `fairseq-train` to do
what you want.
- The command will begin as follows:
fairseq-train \
data-bin \
--source-lang ice.g \
--target-lang ice.p \
...
but many more flags are required (roughly, one for each bullet point).
- Read [the
docs](https://fairseq.readthedocs.io/en/latest/command_line_tools.html#fairseq-train)
for `fairseq-train`.
### Part 4: evaluation
Grapheme-to-phoneme conversion engines are traditionally evaluated using word
error rate (WER), which is simply the percentage of incorrectly predicted word
pronuniciations in the test set. Unfortunately, FairSeq does not provide any
tool to compute word error rate. Instead, the
[`fairseq-generate`](https://fairseq.readthedocs.io/en/latest/command_line_tools.html#fairseq-generate)
command-line tool is used for inference/prediction, and this program's output
can then be processed to compute WER.
#### What to do
Run the following command to write the one-best prediction for each test example
to a file called `predictions.txt`.
fairseq-generate \
data-bin \
--source-lang ice.g \
--target-lang ice.p \
--path checkpoints/checkpoint_best.pt \
--gen-subset test \
--beam 8 \
> predictions.txt
Then, automatically process `predictions.txt`, a verbose (but human-readable)
text file, to compute test set WER.
#### What to turn in
1. A Python script for computing WER from the `predictions.txt` file.
2. Your word error rate, rounded to an appropriate number of digits given the
number of test examples.
#### Hints
- I obtained a WER of 23, but your mileage may vary somewhat.
- Since there are only 100 examples, multiply WER by 100 and round to the
nearest integer. Thus WER should be some number between 0 and 100, the
smaller the better.
- In this file, the gold ("target") pronunciation is indicated by line-initial
`T-` and the predicted ("hypothesis") pronunciation is indicated by
line-initial `H-`.
- Don't forget to turn in your WER.
- Read [the
docs](https://fairseq.readthedocs.io/en/latest/command_line_tools.html#fairseq-generate)
for `fairseq-generate`.
## Part 5: reflection
Please provide a brief (roughly one page) reflection on this assignment.
### What to turn in
A brief description of the challenges and problems you ran into during this
assignment.
## Stretch goals
- Run the above experiment on a GPU, such as available in the computational
linguistics lab (7400.13). Using `time` to keep track of "wall clock" time
(i.e., human time), report the runtime of the CPU and GPU versions.
- Tune at least two of the hyperparameters to minimize word error rate on the
development set.
- Perform an error analysis along the lines proposed in section 8 of [Ashby et
al. 2021](https://aclanthology.org/2021.sigmorphon-1.13/).
- Try an alternative sequence-to-sequence model supported by FairSeq, such as
the
[transformer](https://fairseq.readthedocs.io/en/latest/models.html#module-fairseq.models.transformer),
using hyperparameters such as those proposed by [Wu et
al. 2021](https://aclanthology.org/2021.eacl-main.163/).
|
PHP
|
UTF-8
| 1,603
| 2.875
| 3
|
[] |
no_license
|
<?php
require_once("model/Manager.php");
class PostManager extends Manager{
// Join between commentaires and utilisateurs to solely grab and then display the amount of comments in a given entry
function callPosts(){
$bdd = $this->databaseConnect();
$req = $bdd->query('SELECT billets.id,billets.title,billets.content,DATE_FORMAT(billets.entry_date, \'%d/%m/%Y à %Hh%imin%ss\') AS date_creation, COUNT(commentaires.id_billet) nombreComm
FROM commentaires
RIGHT JOIN billets on commentaires.id_billet=billets.id
GROUP BY billets.id
ORDER BY billets.id DESC');
return $req;
}
function callPost($postId){
$bdd = $this->databaseConnect();
$req = $bdd->prepare('SELECT id,title,content,DATE_FORMAT(entry_date, \'%d/%m/%Y à %Hh%imin%ss\') AS date_creation FROM billets WHERE id = :id');
$req->execute(array('id' =>$postId));
$singlePost = $req->fetch();
return $singlePost;
}
function postEntry(){
$bdd = $this->databaseConnect();
$req = $bdd->prepare('INSERT INTO billets(title,content,entry_date) VALUES (:title,:content,NOW())');
$req->execute(array(
'title'=>$_POST['entryTitle'],
'content'=>$_POST['entryContent']));
}
function editedEntry($postId){
$bdd = $this->databaseConnect();
$req = $bdd->prepare('UPDATE billets SET title = :title, content = :content WHERE id = :id');
$req->execute(array(
'title'=>$_POST['entryTitle'],
'content'=>$_POST['entryContent'],
'id'=>$postId));
}
function deleteEntry($postId){
$bdd = $this->databaseConnect();
$req = $bdd->prepare('DELETE FROM billets WHERE id = :id');
$req->execute(array('id'=>$postId));
}
}
|
Markdown
|
UTF-8
| 202
| 2.578125
| 3
|
[] |
no_license
|
# Keith Taylor Links
Here are a few links from my Markdown Portfolio to other pages about me:
- [Keith Taylor's Personal Blog](https://keith.1drous.me/)
- [Keith Taylor on Twitter](https://twitter.com/KeithTaylor)
|
Python
|
UTF-8
| 537
| 2.765625
| 3
|
[] |
no_license
|
from persistencia import MySqlConnector
def crearUsuario(email, nombre, apellido, password):
usuarios = MySqlConnector.correr_sql(f"INSERT INTO usuarios VALUES ('{email}','{nombre}','{apellido}','{password}')")
return obtenerUsuario(email, password)
def obtenerUsuario(email, password):
usuarios = MySqlConnector.correr_sql(f"SELECT IdUsuario, Nombre, Apellido FROM usuarios WHERE IdUsuario = '{email}' AND password = '{password}'")
if usuarios.__len__() == 1:
return usuarios[0]
else:
return None
|
Shell
|
UTF-8
| 2,020
| 2.734375
| 3
|
[] |
no_license
|
#!/bin/sh
# the files from which this script was run are kept (at the time of
# writing) in //oryx/external/codecmaps/.
p4 edit *.inc
# DOS code pages
for a in CP???.TXT ; do tr '[a-f]' '[A-F]' < $a | tr -s ' ' | awk '/^0x[0123456789ABCDEF]/{ print $1, $2 }' | sort | sed -e 's/#UNDEF.*$/0xFFFD/' | cut -c6- | paste '-d ' - - - - - - - - | sed -e 's/ /, /g' -e 's/$/,/' -e 's/^/ /' -e '$ s/,$//' > `basename $a .TXT | tr 'A-Z' 'a-z'`.inc ; done
# windows code pages, except 874, which is above
for a in CP12??.TXT ; do ( awk '/^0x[0123456789ABCDEF]/{ print $1, $2 }' < $a ) | sort | sed -e 's/#UNDEF.*$/0xFFFD/' | cut -c6- | paste '-d ' - - - - - - - - | sed -e 's/ /, /g' -e 's/$/,/' -e 's/^/ /' -e '$ s/,$//' > `basename $a .TXT | tr 'A-Z' 'a-z'`.inc ; done
# 8859-*
for A in 0 1 2 3 4 5 6 7 8 9 A B C D E F ; do for B in 0 1 2 3 4 5 6 7 8 9 A B C D E F ; do echo 0xFFFD 0x${A}${B} ; done ; done > /tmp/digits
for a in 8859-*.TXT ; do ( awk '/^0x[0123456789ABCDEF]/{ print $2, $1 }' < $a ; cat /tmp/digits ) | sort +1 | uniq -s7 | awk '{print $2, $1}' | cut -c6- | paste '-d ' - - - - - - - - | sed -e 's/ /, /g' -e 's/$/,/' -e 's/^/ /' -e '$ s/,$//' > `basename $a .TXT`.inc ; done
# mac codecs
for a in ROMAN.TXT ; do ( awk '/^0x[0123456789ABCDEF]/{ print $1, $2 }' < $a ; for hi in 0 1 2 3 4 5 6 7 8 9 A B C D E F ; do for lo in 0 1 2 3 4 5 6 7 8 9 A B C D E F ; do echo 0x$hi$lo 0xFFFD ; done ; done ) | sort | uniq -w4 | sed -e 's/#UNDEF.*$/0xFFFD/' | cut -c6- | paste '-d ' - - - - - - - - | sed -e 's/ /, /g' -e 's/$/,/' -e 's/^/ /' -e '$ s/,$//' > mac-`basename $a .TXT | tr 'A-Z' 'a-z'`.inc ; done
# hp
( awk '/^0x[0123456789ABCDEF]/{ print $1, $2 }' < hproman8.txt ; for hi in 0 1 2 3 4 5 6 7 8 9 A B C D E F ; do for lo in 0 1 2 3 4 5 6 7 8 9 A B C D E F ; do echo 0x$hi$lo 0xFFFD ; done ; done ) | sort | uniq -w4 | sed -e 's/#UNDEF.*$/0xFFFD/' | cut -c6- | paste '-d ' - - - - - - - - | sed -e 's/ /, /g' -e 's/$/,/' -e 's/^/ /' -e '$ s/,$//' > hproman8.inc
p4 revert -a ...
|
PHP
|
UTF-8
| 5,349
| 2.984375
| 3
|
[] |
no_license
|
<?php
/**
*
* Stick Object class to make CRUD operations on table.
*
* @author Hamza Waqas
* @since 1st Feb, 2013
* @version v1.0
*/
class Stick {
private $_table = "table_name";
private $_data = array();
private $_isNew;
private $_dataSource;
private $_fetchAs = PDO::FETCH_ASSOC;
protected static $_classDataSource = null;
protected static $_name;
private $_config = null;
private static $static_config = null;
private $_isLoaded = false;
private $_isSaved = false;
public function __construct($table_name,$data = array()) {
$this->_table = $table_name;
$this->_data = $data;
$this->_isNew = true;
$this->_config = StickConfig::getInstance();
static::$static_config = $this->_config;
$this->_dataSource = $this->_config->datasource;
}
public function save() {
$this->_validateModifiable();
if ($this->_isNew) {
$this->_dataSource->add($this->_getName(), $this->_data);
$this->_isSaved = true;
} else {
$this->_dataSource->update($this->_getName(), $this->_data);
$this->_isSaved = true;
}
}
function _auto_get($id, $table_name = null) {
if (!is_null($table_name) && !isset($this->_table))
$this->_table = $table_name;
$record = static::getDataSource()->scanAndGet($this->_getName(), $id);
if (!empty ($record)) {
foreach ($record as $column => $value) {
$this->_data[$column] = $value;
}
$this->_isLoaded = true;
$this->_isNew = false;
}
return $this;
}
public function isLoaded() {
return $this->_isLoaded;
}
public function isSaved() {
return $this->_isSaved;
}
public function delete() {
$this->_dataSource->remove($this->_getName(), $this->_data);
}
public function _setNew($bool) {
$this->_isNew = $bool;
}
private function _makeStick($data) {
if ( !empty ($data)) {
$stick = Stick::newStick($this->_getName());
foreach ($data as $column => $value) {
$stick->$column = $value;
}
return $stick;
}
return Stick::newStick($this->_getName());
}
public function get($criteria = array(), $order = null, $limit = null, $offset = 0) {
try {
$result = static::getDataSource()->get($this->_getName(), $criteria, $order, $limit, $offset);
$object = new stdClass();
if ( !empty($result)) {
$object = Stick::newStick($this->_getName());
$object->_setNew(false);
foreach ($result as $column => $value) {
$object->$column = $value;
}
}
} catch (Exception $ex) {
echo "<pre>"; print_r($ex); exit;
}
return $object;
}
private function _validateModifiable()
{
if (!($this->getDataSource() instanceof Modifiable)) {
throw new Exception("Object is read-only.");
}
}
public function __unset($column)
{
$this->_validateModifiable();
$this->_data[$column] = null;
}
public function get_all($object, array $criteria = array(), $order = null, $limit = null, $offset = 0) {
try {
$result = static::getDataSource()->get_all($this->_getName(), $criteria, $order, $limit, $offset);
$objects = array();
if ( !empty($result) && count($result) > 0) {
foreach ($result as $data) {
$object = Stick::newStick($this->_getName());
$object->_setNew(false);
foreach ($data as $column => $value) {
$object->$column = $value;
}
$objects[] = $object;
}
}
} catch (Exception $ex) {
echo "<pre>"; print_r($ex); exit;
}
return $objects;
}
public function count($criteria = array()) {
return static::getDataSource()->count($this->_getName(),$criteria);
}
public function __set($column, $value) {
$this->_data[$column] = $value;
}
public function __get($column) {
return $this->_data[$column];
}
public function getScope($type = null) {
if ( $type == 'object')
return (object) $this->_data;
return $this->_data;
}
public function fetchAs($type = PDO::FETCH_OBJ) {
$this->_fetchAs = $type;
static::getDataSource()->setFetchMode($this->_fetchAs);
return $this;
}
public static function getDataSource() {
return static::$static_config->datasource;
}
public static function setDataSource(DataSource $datasource) {
static::$_classDataSource = $datasource;
}
public function _getName() {
if ( !isset ($this->_table)) {
throw new Exception("Table name not found in ".get_called_class());
}
return $this->_table;
}
public function hasProperty($key) {
if ( array_key_exists($key, $this->_data))
return true;
return false;
}
}
|
JavaScript
|
UTF-8
| 147
| 3.484375
| 3
|
[] |
no_license
|
const numeros = [1, 2, 3, 4, 5, 6]
for (numero of numeros)
console.log(numero)
numeros.forEach((numero, indice) => {console.log(numero, indice)})
|
Swift
|
UTF-8
| 21,291
| 2.578125
| 3
|
[] |
no_license
|
//
// GameScene.swift
// FlappyBird
//
// Created by 濱田龍輝 on 2019/09/09.
// Copyright © 2019 Ryuuki.hamada. All rights reserved.
//
import SpriteKit
import AVFoundation
class GameScene: SKScene , SKPhysicsContactDelegate{
var scrollNode:SKNode!
var wallNode:SKNode!
var pointUpItemNode:SKNode!
var bird:SKSpriteNode!
var effectSoundPlayer:AVAudioPlayer?
var bgmPlayer: AVAudioPlayer?
// 衝突判定カテゴリー
let birdCategory: UInt32 = 1 << 0 // 0...00001
let groundCategory: UInt32 = 1 << 1 // 0...00010
let wallCategory: UInt32 = 1 << 2 // 0...00100
let scoreCategory: UInt32 = 1 << 3 // 0...01000
let pointUpItemCategory: UInt32 = 1 << 4 // 0...10000
// スコア用
var score = 0
var pointUpItem_score = 0
var scoreLabelNode:SKLabelNode!
var bestScoreLabelNode:SKLabelNode!
var restartLabelNode:SKLabelNode!
var hintLabelNode:SKLabelNode!
var pointUpItemLabelNode:SKLabelNode!
let userDefaults:UserDefaults = UserDefaults.standard
var hint_array = ["error"]
var hint_array_number = 0
/*
zPosition
Cloud -100
wall -50
pointUpItem -40
scoreLabel 100
bestscoreLabel 100
restartLabel 100
hintLabel 100
pointUpItemLabel 100
*/
// SKView上にシーンが表示されたときに呼ばれるメソッド
override func didMove(to view: SKView) {
// 重力を設定
physicsWorld.gravity = CGVector(dx: 0, dy: -4)
physicsWorld.contactDelegate = self
backgroundColor = UIColor(red: 0.15, green: 0.75, blue: 0.90, alpha: 1)// 背景色を設定
// スクロールするスプライトの親ノード
scrollNode = SKNode()
addChild(scrollNode)
// 壁用のノード
wallNode = SKNode()
pointUpItemNode = SKNode()
scrollNode.addChild(wallNode)
scrollNode.addChild(pointUpItemNode)
// 各種スプライトを生成する処理をメソッドに分割
setupGround()
setupCloud()
setupWall()
setupBird()
setupScoreLabel()
setupPointUpItem()
load_audio()
setup_effectSoundPlayer()
setup_hint_array()
}
// 画面をタップした時に呼ばれる
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if scrollNode.speed > 0 {
bird.physicsBody?.velocity = CGVector.zero// 鳥の速度をゼロにする
bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 15))// 鳥に縦方向の力を与える
} else if bird.speed == 0 {
restart()
}
}
// SKPhysicsContactDelegateのメソッド。衝突したときに呼ばれる
func didBegin(_ contact: SKPhysicsContact) {
// ゲームオーバーのときは何もしない
if scrollNode.speed <= 0 {
return //ここでdidBegin処理終了 壁接触後の床の処理をさせないため
}
//ポイントアップ要素同時処理対応
var flug_contact_score = 0
if (contact.bodyA.categoryBitMask & pointUpItemCategory) == pointUpItemCategory || (contact.bodyB.categoryBitMask & pointUpItemCategory) == pointUpItemCategory {
score += 3
pointUpItem_score += 1
pointUpItemLabelNode.text = "Item Count:\(pointUpItem_score)"
upDateScore()
effectSoundPlayer?.play()
flug_contact_score = 1
pointUpItemNode.removeAllChildren()
}
if (contact.bodyA.categoryBitMask & scoreCategory) == scoreCategory || (contact.bodyB.categoryBitMask & scoreCategory) == scoreCategory {
score += 1
upDateScore()
} else if (flug_contact_score == 0) {
scrollNode.speed = 0
bird.physicsBody?.collisionBitMask = groundCategory
let roll = SKAction.rotate(byAngle: CGFloat(Double.pi) * CGFloat(bird.position.y) * 0.01, duration:1)
bird.run(roll, completion:{
self.bird.speed = 0
})
restartLabelNode.text = "GAME OVER"
hintLabelNode.text = "\(hint_array[hint_array_number])"
}
}
func upDateScore(){
scoreLabelNode.text = "Score:\(score)"
var bestScore = userDefaults.integer(forKey: "BEST")
if score > bestScore {
bestScore = score
userDefaults.set(bestScore, forKey: "BEST")
userDefaults.synchronize()
bestScoreLabelNode.text = "Best Score:\(bestScore)"
}
}
func restart() {
score = 0
pointUpItem_score = 0
scoreLabelNode.text = "Score:\(score)"
pointUpItemLabelNode.text = "Item Count:\(pointUpItem_score)"
restartLabelNode.text = ""
hintLabelNode.text = ""
hint_array_number = Int.random(in: 0..<hint_array.count)
//print("count: \(hint_array.count)")
//print("number: \(hint_array_number)")
bird.position = CGPoint(x: self.frame.size.width * 0.2, y:self.frame.size.height * 0.7)
bird.physicsBody?.velocity = CGVector.zero
bird.physicsBody?.collisionBitMask = groundCategory | wallCategory
bird.zRotation = 0
wallNode.removeAllChildren()
pointUpItemNode.removeAllChildren()
bird.speed = 1
scrollNode.speed = 1
}
func setupGround() {
// 地面の画像を読み込む
let groundTexture = SKTexture(imageNamed: "ground")
groundTexture.filteringMode = .nearest
// 必要な枚数を計算
let needNumber = Int(self.frame.size.width / groundTexture.size().width) + 2
// スクロールするアクションを作成
// 左方向に画像一枚分スクロールさせるアクション
let moveGround = SKAction.moveBy(x: -groundTexture.size().width , y: 0, duration: 5)
// 元の位置に戻すアクション
let resetGround = SKAction.moveBy(x: groundTexture.size().width, y: 0, duration: 0)
// 左にスクロール->元の位置->左にスクロールと無限に繰り返すアクション
let repeatScrollGround = SKAction.repeatForever(SKAction.sequence([moveGround, resetGround]))
// groundのスプライトを配置する
for i in 0..<needNumber {
let sprite = SKSpriteNode(texture: groundTexture)
// スプライトの表示する位置を指定する
sprite.position = CGPoint(
x: groundTexture.size().width / 2 + groundTexture.size().width * CGFloat(i),
y: groundTexture.size().height / 2
)
// スプライトにアクションを設定する
sprite.run(repeatScrollGround)
// スプライトに物理演算を設定する
sprite.physicsBody = SKPhysicsBody(rectangleOf: groundTexture.size()) // ←追加
// 衝突のカテゴリー設定
sprite.physicsBody?.categoryBitMask = groundCategory // ←追加
// 衝突の時に動かないように設定する
sprite.physicsBody?.isDynamic = false // ←追加
scrollNode.addChild(sprite)// スプライトを追加する
}
}
func setupCloud() {
// 雲の画像を読み込む
let cloudTexture = SKTexture(imageNamed: "cloud")
cloudTexture.filteringMode = .nearest
// 必要な枚数を計算
let needCloudNumber = Int(self.frame.size.width / cloudTexture.size().width) + 2
// スクロールするアクションを作成
// 左方向に画像一枚分スクロールさせるアクション
let moveCloud = SKAction.moveBy(x: -cloudTexture.size().width , y: 0, duration: 20)
// 元の位置に戻すアクション
let resetCloud = SKAction.moveBy(x: cloudTexture.size().width, y: 0, duration: 0)
// 左にスクロール->元の位置->左にスクロールと無限に繰り返すアクション
let repeatScrollCloud = SKAction.repeatForever(SKAction.sequence([moveCloud, resetCloud]))
// スプライトを配置する
for i in 0..<needCloudNumber {
let sprite = SKSpriteNode(texture: cloudTexture)
sprite.zPosition = -100 // 一番後ろになるようにする
// スプライトの表示する位置を指定する
sprite.position = CGPoint(
x: cloudTexture.size().width / 2 + cloudTexture.size().width * CGFloat(i),
y: self.size.height - cloudTexture.size().height / 2
)
// スプライトにアニメーションを設定する
sprite.run(repeatScrollCloud)
// スプライトを追加する
scrollNode.addChild(sprite)
}
}
func setupWall() {
// 壁の画像を読み込む
let wallTexture = SKTexture(imageNamed: "wall")
wallTexture.filteringMode = .linear
// 移動する距離を計算
let movingDistance = CGFloat(self.frame.size.width + wallTexture.size().width)
// 画面外まで移動するアクションを作成
let moveWall = SKAction.moveBy(x: -movingDistance, y: 0, duration:4)
// 自身を取り除くアクションを作成
let removeWall = SKAction.removeFromParent()
// 2つのアニメーションを順に実行するアクションを作成
let wallAnimation = SKAction.sequence([moveWall, removeWall])
// 鳥の画像サイズを取得
let birdSize = SKTexture(imageNamed: "bird_a").size()
// 鳥が通り抜ける隙間の長さを鳥のサイズの3倍とする
let slit_length = birdSize.height * 3
// 隙間位置の上下の振れ幅を鳥のサイズの3倍とする
let random_y_range = birdSize.height * 3
// 下の壁のY軸下限位置(中央位置から下方向の最大振れ幅で下の壁を表示する位置)を計算
let groundSize = SKTexture(imageNamed: "ground").size()
let center_y = groundSize.height + (self.frame.size.height - groundSize.height) / 2
let under_wall_lowest_y = center_y - slit_length / 2 - wallTexture.size().height / 2 - random_y_range / 2
// 壁を生成するアクションを作成
let createWallAnimation = SKAction.run({
// 壁関連のノードを乗せるノードを作成
let wall = SKNode()
wall.position = CGPoint(x: self.frame.size.width + wallTexture.size().width / 2, y: 0)
wall.zPosition = -50 // 雲より手前、地面より奥
let random_y = CGFloat.random(in: 0..<random_y_range)// 0〜random_y_rangeまでのランダム値を生成
let under_wall_y = under_wall_lowest_y + random_y// Y軸の下限にランダムな値を足して、下の壁のY座標を決定
// 下側の壁を作成
let under = SKSpriteNode(texture: wallTexture)
under.position = CGPoint(x: 0, y: under_wall_y)
// スプライトに物理演算を設定する
under.physicsBody = SKPhysicsBody(rectangleOf: wallTexture.size())
under.physicsBody?.categoryBitMask = self.wallCategory
under.physicsBody?.isDynamic = false // 衝突の時に動かないように設定する
wall.addChild(under)
// 上側の壁を作成
let upper = SKSpriteNode(texture: wallTexture)
upper.position = CGPoint(x: 0, y: under_wall_y + wallTexture.size().height + slit_length)
// スプライトに物理演算を設定する
upper.physicsBody = SKPhysicsBody(rectangleOf: wallTexture.size())
upper.physicsBody?.categoryBitMask = self.wallCategory
upper.physicsBody?.isDynamic = false // 衝突の時に動かないように設定する
wall.addChild(upper)
// スコアアップ用のノード
let scoreNode = SKNode()
scoreNode.position = CGPoint(x: upper.size.width + birdSize.width / 2, y: self.frame.height / 2)
scoreNode.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: upper.size.width, height: self.frame.size.height))
scoreNode.physicsBody?.isDynamic = false
scoreNode.physicsBody?.categoryBitMask = self.scoreCategory
scoreNode.physicsBody?.contactTestBitMask = self.birdCategory
wall.addChild(scoreNode)
wall.run(wallAnimation)
self.wallNode.addChild(wall)
})
// 次の壁作成までの時間待ちのアクションを作成
let waitAnimation = SKAction.wait(forDuration: 2)
// 壁を作成->時間待ち->壁を作成を無限に繰り返すアクションを作成
let repeatForeverAnimation = SKAction.repeatForever(SKAction.sequence([createWallAnimation, waitAnimation]))
wallNode.run(repeatForeverAnimation)
}
func setupBird() {
// 鳥の画像を2種類読み込む
let birdTextureA = SKTexture(imageNamed: "bird_a")
birdTextureA.filteringMode = .linear
let birdTextureB = SKTexture(imageNamed: "bird_b")
birdTextureB.filteringMode = .linear
// 2種類のテクスチャを交互に変更するアニメーションを作成
let texuresAnimation = SKAction.animate(with: [birdTextureA, birdTextureB], timePerFrame: 0.2)
let flap = SKAction.repeatForever(texuresAnimation)
// スプライトを作成
bird = SKSpriteNode(texture: birdTextureA)
bird.position = CGPoint(x: self.frame.size.width * 0.2, y:self.frame.size.height * 0.7)
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height / 2.2) // 物理演算を設定
bird.physicsBody?.allowsRotation = false // 衝突した時に回転させない
// 衝突のカテゴリー設定
bird.physicsBody?.categoryBitMask = birdCategory
bird.physicsBody?.collisionBitMask = groundCategory | wallCategory
bird.physicsBody?.contactTestBitMask = groundCategory | wallCategory | pointUpItemCategory
bird.run(flap) // アニメーションを設定
addChild(bird) // スプライトを追加する
}
func setupScoreLabel() {
score = 0
scoreLabelNode = SKLabelNode()
scoreLabelNode.fontColor = UIColor.black
scoreLabelNode.position = CGPoint(x: 10, y: self.frame.size.height - 60)
scoreLabelNode.zPosition = 100
scoreLabelNode.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left
scoreLabelNode.text = "Score:\(score)"
self.addChild(scoreLabelNode)
bestScoreLabelNode = SKLabelNode()
bestScoreLabelNode.fontColor = UIColor.black
bestScoreLabelNode.position = CGPoint(x: 10, y: self.frame.size.height - 90)
bestScoreLabelNode.zPosition = 100
bestScoreLabelNode.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left
let bestScore = userDefaults.integer(forKey: "BEST")
bestScoreLabelNode.text = "Best Score:\(bestScore)"
self.addChild(bestScoreLabelNode)
pointUpItemLabelNode = SKLabelNode()
pointUpItemLabelNode.fontColor = UIColor.black
pointUpItemLabelNode.position = CGPoint(x: 10, y: self.frame.size.height - 120)
pointUpItemLabelNode.zPosition = 100
pointUpItemLabelNode.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.left
pointUpItemLabelNode.text = "Item Count:\(pointUpItem_score)"
self.addChild(pointUpItemLabelNode)
restartLabelNode = SKLabelNode()
restartLabelNode.fontColor = UIColor.black
restartLabelNode.fontName = "Thonburi-Bold"
restartLabelNode.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
restartLabelNode.zPosition = 100
restartLabelNode.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center
restartLabelNode.text = ""
self.addChild(restartLabelNode)
hintLabelNode = SKLabelNode()
hintLabelNode.fontColor = UIColor.black
hintLabelNode.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2 - 50)
hintLabelNode.zPosition = 100
hintLabelNode.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center
hintLabelNode.text = ""
self.addChild(hintLabelNode)
}
func setupPointUpItem() {
let pointUpItemTexture = SKTexture(imageNamed: "pan")
pointUpItemTexture.filteringMode = .nearest
// 移動する距離を計算
let pointUpItemMovingDistance = CGFloat(self.frame.size.width + pointUpItemTexture.size().width)
// 画面外まで移動するアクションを作成
let movePointUpItem = SKAction.moveBy(x: -pointUpItemMovingDistance, y: 0, duration:4)
// 自身を取り除くアクションを作成
let removePointUpItem = SKAction.removeFromParent()
// 2つのアニメーションを順に実行するアクションを作成
let pointUpItemAnimation = SKAction.sequence([movePointUpItem, removePointUpItem])
let birdSize = SKTexture(imageNamed: "bird_a").size()
let random_y_MaxRange = birdSize.height * 3.5
let groundSize = SKTexture(imageNamed: "ground").size()
let center_y = groundSize.height + (self.frame.size.height - groundSize.height) / 2
// ポイントアップを生成するアクションを作成
let createPointUpItemAnimation = SKAction.run({
// 削除管理用ノード
let pointUpItem_basenode = SKNode()
pointUpItem_basenode.position = CGPoint(x: 0, y: 0)
pointUpItem_basenode.zPosition = 0
//random_y_MinRange~random_y_MaxRangeの間
let random_y = CGFloat.random(in: -random_y_MaxRange...random_y_MaxRange)
let random_x = CGFloat.random(in: -random_y_MaxRange...0)
let pointUpItem_y = center_y + random_y
let pointUpItem = SKSpriteNode(texture: pointUpItemTexture)
pointUpItem.position = CGPoint(x: random_x + self.frame.size.width + pointUpItemTexture.size().width / 2, y: pointUpItem_y)
pointUpItem.zPosition = -40
pointUpItem.physicsBody = SKPhysicsBody(rectangleOf: pointUpItemTexture.size())
pointUpItem.physicsBody?.categoryBitMask = self.pointUpItemCategory
pointUpItem.physicsBody?.isDynamic = false
pointUpItem_basenode.addChild(pointUpItem)
pointUpItem_basenode.run(pointUpItemAnimation)
self.pointUpItemNode.addChild(pointUpItem_basenode)
})
let waitAnimation = SKAction.wait(forDuration: 5.2)
// 壁を作成->時間待ち->壁を作成を無限に繰り返すアクションを作成
let repeatForeverAnimation = SKAction.repeatForever(SKAction.sequence([createPointUpItemAnimation, waitAnimation]))
pointUpItemNode.run(repeatForeverAnimation)
}
func load_audio(){
let path = Bundle.main.path(forResource: "background" , ofType: "mp3")!
let url = URL(fileURLWithPath: path)
do {
bgmPlayer = try AVAudioPlayer(contentsOf: url)
bgmPlayer?.numberOfLoops = -1
bgmPlayer?.volume = 0.9
bgmPlayer?.play()
} catch {
print("bgmPlayer ERROR")
}
}
func setup_effectSoundPlayer(){
let path = Bundle.main.path(forResource: "chun" , ofType: "mp3")!
let url = URL(fileURLWithPath: path)
do {
effectSoundPlayer = try AVAudioPlayer(contentsOf: url)
effectSoundPlayer?.numberOfLoops = 0
effectSoundPlayer?.volume = 1.0
effectSoundPlayer?.prepareToPlay()
} catch {
print("effectSoundPlayer ERROR")
}
}
func setup_hint_array(){
//10文字まで
hint_array[0] = "タップでリスタート!"
hint_array.append("無理は禁物!")
hint_array.append("リズムを大事に!")
hint_array.append("パンは3ポイント!")
hint_array.append("頑張れ!")
}
}
|
Java
|
UTF-8
| 545
| 2.9375
| 3
|
[] |
no_license
|
package operacija;
public class BasicOperacija extends Operacija {
public enum BasicOperacije
{
Addition,
Subtraction,
InverseSubtraction,
Multiplication,
Division,
InverseDivision,
Power,
Logarithm,
Abs,
Min,
Max,
Invert,
Grayscale,
BlackAndWhite,
Median
}
public enum BasicOperacijeBezKonstante
{
Abs,
Invert,
Grayscale,
BlackAndWhite,
Median
}
public BasicOperacija(BasicOperacije ime, int cnst)
{
this.name = ime.toString();
this.cnst = cnst;
this.listaOperacija = null;
}
}
|
Python
|
UTF-8
| 1,233
| 3.625
| 4
|
[] |
no_license
|
# intersection for sorted arrays
class Solution:
# O(n + m)
def intersection(self, nums1, nums2):
if nums1 is None or 0 == len(nums1) or nums2 is None or 0 == len(nums2):
return []
result, idx1, idx2 = [], 0, 0
while idx1 < len(nums1) and idx2 < len(nums2):
if nums1[idx1] == nums2[idx2]:
result.append(nums1[idx1])
idx1 += 1
idx2 += 1
elif nums1[idx1] < nums2[idx2]:
idx1 += 1
else:
idx2 += 1
# To remove duplications
prevIdx1 = idx1 - 1
while 0 < idx1 < len(nums1) - 1 and nums1[prevIdx1] == nums1[idx1]:
idx1 += 1
prevIdx2 = idx2 - 1
while 0 < idx2 < len(nums2) - 1 and nums2[prevIdx2] == nums2[idx2]:
idx2 += 1
return result
s = Solution()
data = [([], [2, 2], []),
([1, 3, 4, 7, 11, 19], [2, 3, 11, 17], [3, 11]),
([1, 3, 3, 4, 7, 11, 19], [2, 3, 11, 17], [3, 11])
]
for nums1, nums2, expected in data:
real = s.intersection(nums1, nums2)
print(f'{nums1}, {nums2}, expected {expected}, real {real}, result {expected == real}')
|
PHP
|
UTF-8
| 501
| 2.921875
| 3
|
[] |
no_license
|
<?php
class Empresa{
private $nome;
private $empresa;
private $cenario;
public function getNome(){
return $this ->nome;
}
public function setNome($nome){
$this->nome = $nome;
}
public function getEmpresa(){
return $this ->empresa;
}
public function setEmpresa($empresa){
$this->empresa = $empresa;
}
public function getCenario(){
return $this -> cenario;
}
public function setCenario($cenario){
$this->cenario =$cenario;
}
}
|
C++
|
UTF-8
| 567
| 2.71875
| 3
|
[] |
no_license
|
/*
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
typedef long long ll;
class mCmp{
public:
bool operator()(const int a, const int b) const{
return a > b;
}
};
int main()
{
int N;
scanf("%d", &N);
char ch[10];
int num;
set<int, mCmp> temp;
for (int i = 0; i < N;i++){
scanf("%s", ch);
if ( !strcmp(ch, "A") ){
scanf("%d", &num);
temp.insert(num);
}else{
num = (*temp.begin());
temp.erase(temp.begin());
printf("%d\n", num);
}
}
return 0;
}*/
|
Markdown
|
UTF-8
| 2,956
| 3.71875
| 4
|
[] |
no_license
|
## 嵌套类应用
**嵌套类**
**• 嵌套类:Nested classes**
**–静态嵌套类:Static nested classes,即类前面有class修饰符**
**–非静态嵌套类:Non-static nested classes, 又名内部类,Inner classes**
**• 普通内部类(又翻译为:成员内部类)**
**• 局部内部类(Local classes)**
**• 匿名内部类(Anonymous classes)**
**– https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html**
**匿名内部类**
**• 匿名内部类**
**–无需类名,用过即焚,使用广泛**
**–该类的对象只要一个,且方法只有一个,代码短**
**• Android中常用匿名内部类**
**局部内部类(1)**
**• 局部内部类**
**–定义在方法体内,只能在当前方法内使用,代码短**
**–使用较少**
**–介于匿名内部类和普通内部类之间**
**• 只用一次,就用匿名内部类,简便**
**• 使用多次,那就上升到普通内部类,整个类都可以使用**
**局部内部类(2)**
**• 局部内部类**
**–继承某一个类或接口,重新定义方法,并当作返回值在外部使用**
**–如java.util.regex.Pattern的splitAsStream方法的局部内部类**
**普通内部类**
**• 普通内部类**
**–广泛使用在具有母子结构的类,内部类对象和外围类保持联系**
**–如Map和Map.Entry,ZipFile和ZipFile.ZipEntryIterator等**
**静态嵌套类**
**• 静态嵌套类**
**–和普通类一致,只是“碰巧”声明在一个外围类的内部**
**–和外围类没有太多的联系,可以脱离外围类对象存在,也可以访问外围类的静态成员**
**–如果不需要访问外围类的非静态成员,尽量将普通内部类变更为静态嵌套类**
**• 节省普通内部类和外围类的联系开销**
**• 使得外围类对象更容易被垃圾回收器回收**
**Java的rt.jar分析**
**• Java 8中的rt.jar所包含的嵌套类数据**
**• 所有类:19730个**
**• 嵌套类:7115**
**–匿名内部类:2295个**
**–局部内部类:46个**
**–普通内部类:3618个**
**–静态嵌套类:1156个**
**• 注:此数据是基于Oracle JDK 1.8.0_45 64位Windows版本统计得出的。对于不同版本的JDK,可能略有差别。**
**嵌套类**
**• 嵌套类的作用(官方文档)**
**–https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html**
**–逻辑上,是一种对类分组的好办法,限定某类只能在一个地方使用。**
**It is a way of logically grouping classes that are only used in one place.**
**–增加了封装。 It increases encapsulation.**
**–使得代码更加容易阅读和维护。 It can lead to more readable and**
**maintainable code.**
**总结**
**• 了解4种嵌套类使用原则和应用场景**
**• 总结4种嵌套类的作用**
|
Shell
|
UTF-8
| 1,414
| 2.609375
| 3
|
[] |
no_license
|
# Based on Ubuntu-16.04
# update
sudo apt-get update
# install vim
sudo apt-get install vim
# install ipython
sudo apt-get install ipython
# install pwntools
sudo apt-get install python2.7 python-pip python-dev git libssl-dev libffi-dev build-essential
sudo pip install --upgrade pip
sudo pip install --upgrade pwntools
# install zsh
sudo apt-get install zsh
sudo apt-get install git
sudo wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | sh
chsh -s /usr/bin/zsh
# install x86 environment
sudo apt-get install gcc-multilib
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libstdc++6:i386 open-vm-tools open-vm-tools-desktop
# install tmux
sudo apt-get install tmux
# install peda
git clone https://github.com/scwuaptx/peda.git ~/peda
echo "source ~/peda/peda.py" >> ~/.gdbinit
# install Pwngdb
git clone https://github.com/scwuaptx/Pwngdb.git ~/Pwngdb
cp ~/Pwngdb/.gdbinit ~/
# install zsh plugins
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
git clone git://github.com/zsh-users/zsh-autosuggestions $ZSH_CUSTOM/plugins/zsh-autosuggestions
# install LibcSearcher
git clone https://github.com/lieanu/libc.git
cd libc
git submodule update --init --recursive
sudo python setup.py develop
# install one_gadget
sudo apt install ruby
sudo gem install one_gadget
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.