language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 496
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
# Project
Continue last week's project, feel free to add any feature that you like!
Here are some ideas if you don't have any:
- Create a server and a database and connect them to your React app.
- Add more pages related to your app.
- Use an external API.
> Quick tip: in case you actually want to build a server for you frontend, make sure you create it in a new repository.
Make sure to explore packages from React and Express and practice subjects that you are not fully confident with.
|
TypeScript
|
UTF-8
| 2,857
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
import ts from 'typescript';
import minimatch from 'minimatch';
import {existsSync} from 'fs';
import {dirname, join, normalize, relative, resolve} from 'path';
import * as Lint from 'tslint';
const BUILD_BAZEL_FILE = 'BUILD.bazel';
/**
* Rule that enforces that imports or exports with relative paths do not resolve to
* source files outside of the current Bazel package. This enforcement is necessary
* because relative cross entry-point imports/exports can cause code being inlined
* unintentionally and could break module resolution since the folder structure
* changes in the Angular Package release output.
*/
export class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, checkSourceFile, this.getOptions().ruleArguments);
}
}
/**
* Rule walker function that checks the source file for imports/exports
* with relative cross entry-point references.
*/
function checkSourceFile(ctx: Lint.WalkContext<string[]>) {
const filePath = ctx.sourceFile.fileName;
const relativeFilePath = relative(process.cwd(), filePath);
if (!ctx.options.every(o => minimatch(relativeFilePath, o))) {
return;
}
(function visitNode(node: ts.Node) {
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
if (
!node.moduleSpecifier ||
!ts.isStringLiteralLike(node.moduleSpecifier) ||
!node.moduleSpecifier.text.startsWith('.')
) {
return;
}
const modulePath = node.moduleSpecifier.text;
const basePath = dirname(filePath);
const currentPackage = findClosestBazelPackage(basePath);
const resolvedPackage = findClosestBazelPackage(resolve(basePath, modulePath));
if (
currentPackage &&
resolvedPackage &&
normalize(currentPackage) !== normalize(resolvedPackage)
) {
const humanizedType = ts.isImportDeclaration(node) ? 'Import' : 'Export';
ctx.addFailureAtNode(
node,
`${humanizedType} resolves to a different Bazel build package through a relative ` +
`path. This is not allowed and can be fixed by using the actual module import.`,
);
}
return;
}
ts.forEachChild(node, visitNode);
})(ctx.sourceFile);
}
/** Finds the closest Bazel build package for the given path. */
function findClosestBazelPackage(startPath: string): string | null {
let currentPath = startPath;
while (!hasBuildFile(currentPath)) {
const parentPath = dirname(currentPath);
if (parentPath === currentPath) {
return null;
}
currentPath = parentPath;
}
return currentPath;
}
/** Checks whether the given directory has a Bazel build file. */
function hasBuildFile(dirPath: string): boolean {
return existsSync(join(dirPath, BUILD_BAZEL_FILE));
}
|
Java
|
UTF-8
| 234
| 1.773438
| 2
|
[] |
no_license
|
package Selektions_Chp_03_Exercises;
import static Selektions_Chp_03_Exercises.Exercise_3_2_Calculations.AdditionQuiz;
public class Exercise_3_2_Main {
public static void main(String[] args) {
AdditionQuiz();
}
}
|
Python
|
UTF-8
| 253
| 2.796875
| 3
|
[] |
no_license
|
# vim: set fenc=utf8 ts=4 sw=4 et :
from master.drill import Drill
class LengthDrill(Drill):
"""
Mines length
@author Ente
"""
def get_headers(self):
return ["Length"]
def drill(self, line):
return [len(line)]
|
Markdown
|
UTF-8
| 5,379
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
# Расширение Авторазиации
Данное расширение являеться новым для фреймворка MyUCP,
и совместимо только с версией 5.7 и выше. Работает при помощи
новой системы расширений которая была введена в новой версии.
## Установка
Расширение идет предустановленым в базовой сборке фреймворка.
Если у вас его нет то, для установки расширения вам нужно загрузить архив последней
версии и загрузить файлы с заменой.
**Важное примечание:** если у вас уже есть модель с названием Model,
вы можете оставить свою.
После загрузки файлов вам нужно указать алиас расширения в `configs/main.php`:
```php
'extensions' => [
...
// Список расширений которые будут инициализированы при запуске приложения
// Обязательно должны реализовывать класс BootExtensionable
'boot' => [
...
"Auth" => \Extensions\Auth\Auth::class,
],
],
```
После нужно указать путь для автозагрузки главного класса в `configs/autoload_classess.php`:
```php
\Extensions\Auth\Auth::class => EXTENSIONS_DIR . 'Auth/Auth.php',
```
Так же для работы расширения нужно еще одно расширение **Validate**, которое так же предустановлено
в базовой сборке фреймворка.
После загрузки всех файлов и указания путей, нужно настроить
конфигурационный файл расширения `configs/auth.php`
### Конфигурационный файл
В данном поле вы указываете название таблицы, где храняться ваши пользователи:
```php
"table" => "users",
```
В массиве `rows` указаны названия полей необходимые для работы расширения, вы так же можете заменить их на те которые указаны у вас в таблице:
```php
"rows" => [
"id" => "user_id",
"password" => "user_password",
"email" => "user_email",
],
```
В поле `redirect` вы указываете адрес куда будет совершенна переадрессация после успешной авторизации пользователем
```php
"redirect" => "/",
```
## Доступные методы
Вы так же можете использовать некоторые методы расширения для получения некоторых данных или совершения действий авторизации или регистрации.
`login($email, $password)` - данный метод позволяет проводить авторизацию пользователя.
`register($email, $password, $password_repeat)` - данный метод позволяет проводить регистраци пользователя.
`auth()` - данный метод позволяет получить данные авторизированного пользователя, если пользователь не авторизирован будет возвращен `false`
`::user()` - данный метод является статическим и полной копией метода `auth()`
`::check()` - данный метод является статическим и позволяет узнать статус пользователя, возвращает `true` в случае если пользователь авторизирован и `false` если не прошел авторизации.
## Виды (шаблоны)
В качестве форм авторизации и регистрации используются Zara шаблоны, которые предзагружены при инициализации расширения
вы так же можете перезаписать их, просто создав в директории `resources/views/` свои, с аналогичными названиями, они будут загружены вместо шаблонов расширения.
`auth.common` - шаблон каркас, который имеет в себе подключаемые стили и скрипты и основную разметку страниц.
`auth.login` - шаблон с формой авторизации, расширяем шаблоном `auth.common`
`auth.register` - шаблон с формой регистрации, расширяем шаблоном `auth.common`
## Лицензия
Расширение **Auth** является программных обеспечением с открытым исходным кодом, под [лицензией MIT](https://opensource.org/licenses/MIT).
|
Markdown
|
UTF-8
| 1,950
| 3.078125
| 3
|
[] |
no_license
|
---
title: Drives - Map a Network Drive
description:
Map a network drive using Files in Pop!_OS.
keywords:
- network drive
- drive
- mount
- network
facebookImage: /_social/article
twitterImage: /_social/article
hidden: false
section: community
tableOfContents: true
---
If you have a storage location on a network drive, you can easily map the location using Files in Pop!\_OS.
## Navigate to Other Locations
Open Files and click on "Other Locations" on the left side overview. It should open a window similar to the one below:

## Connect to server
Enter the address of the server into the box which says "Enter server address..." with one of the following prefixes appended to the beginning of the address.
| Available Protocols | Prefix |
| :------------- | :------------- |
| AppleTalk | afp:// |
| File Transfer Protocol | ftp:// or ftps:// |
| Network File System | nfs:// |
| Samba | smb:// |
| SSH File Transfter Protocol | sftp:// or ssh:// |
| WebDAV | dav:// or davs:// |
The image below shows a Samba connection to the server storage.wpi.edu:

## Enter your username, domain, and password
On the dialog that pops up, enter your account information for the server, then select how it will be remembered by Files. The window looks similar to the one below:

Once this is done, hit "Connect" in the top right and you can access the files on the network drive.
You can also navigate to your newly mounted drive using the Terminal:
```bash
cd /run/user/1000/gvfs/
```
To open your mount in a new Terminal session, right-click the folder and select `Open in Terminal`.
---
This article was contributed by [kylecorry31](https://github.com/kylecorry31).
|
Markdown
|
UTF-8
| 2,037
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
# Fiber Sveltekit Embed App

This application is a full-stack project built using Sveltekit, Tailwind CSS, Fiber. It showcases the construction of a monolithic architecture for a full-stack application.
## Run the Project
To run the project, follow these steps:
1. Execute the following command to run all the necessary commands for building and running the application:
```bash
make all
```
2. Once the build process is complete, you can start the application by running:
```bash
./app
```
## Available Commands
The following commands are available to manage the project:
| Command | Description |
| --- | --- |
| `info` | Info command. Displays the available commands and the purpose of the application. |
| `go-build` | Builds the Golang project and creates an `app` file. |
| `svelte-build` | Builds the SvelteKit project. It first installs the dependencies and then performs the project build. |
| `all` | Runs both `svelte-build` and `go-build` commands sequentially. |
## Usage
To use this application, run the following command:
```bash
make <command>
```
API Routes
----------
The Go Fiber application provides the following API routes:
| Route | Description |
| --- | --- |
| `/*` | Serves static files from the specified directory (`template.Dist()`). If a file is not found, it serves `index.html`. |
Go Dependencies
---------------
- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects.
- **Fiber:** A fast and minimalist web framework for Golang.
Npm Dependencies
----------------
- **SvelteKit:** A JavaScript framework used to build modern web applications.
- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects.
- **Skeleton UI:** This is a fully featured UI Toolkit for building reactive interfaces quickly using Svelte and Tailwind.
----------------
Author: [@ugurkorkmaz](https://github.com/ugurkorkmaz)
|
Java
|
UTF-8
| 265
| 1.773438
| 2
|
[] |
no_license
|
package CoronaVirusTracker.CoronaVirusTracker.domain;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
@ToString
@Builder
@Getter
public class OverseasStats {
private String country;
private String total;
private String dead;
}
|
Markdown
|
UTF-8
| 2,602
| 2.96875
| 3
|
[] |
no_license
|
---
title: 最近遇到的Linux文件系统只读问题
date: 2016-05-20 11:40:20
categories:
- Linux
tags:
- Linux
---
最近两次遇到Linux系统中磁盘出现问题而导致不能写入和更改磁盘数据。
## 问题的出现
- 问题一: 某天早上导师说实验室网站挂掉了,让我去看看。从YII输出的错误信息看应该是后端MySQL连接不上,只好登录服务去查看MySQL进程是否存在。
- 问题二: 今天由于实验室自己的Linux主机ubuntu出现问题,通过另外一块盘备份的时候出现不能写入,在该盘挂载的目录下执行命令都会提示Input/Output error。ubuntu forums上的相关问题
## 问题的解决
- 对于第一个问题登录主机之后发现MySQL进程存在。然后试着通过从shell登录MySQL,结果提示Can’t connect to local MySQL server through socket /xx/xx.sock不能创建,网上说是需要修改这儿sock的权限+R即可,但是修改之后依旧不可以,ls之后发现已经是rwx了。这就让我非常纳闷了。后面发觉整个Linux文件系统不能写入东西了,然后more /proc/mounts之后发现分区的确变成ro只读状态了。由于之前备份过数据,只好冒着一定的危险,选择万能的重启策略了。最好,重启之后手动开启了Apache和Mysql服务就完成了问题的解决。
- 由于有了之前的经验,今天遇到这个问题网上查了资料说是可能是磁盘损坏导致。通过dmesg命令发现,这一条log:
[ 139.666511] EXT4-fs (sdb5): mounting ext3 file system using the ext4 subsystem
[ 139.724006] EXT4-fs (sdb5): warning: mounting unchecked fs, running e2fsck is recommended
[ 139.725427] EXT4-fs (sdb5): mounted filesystem with ordered data mode. Opts: (null)
[ 200.126359] EXT4-fs error (device sdb5): ext4_lookup:1441: inode #110643744: comm rm: deleted inode referenced: 110668315
既然如此提示,那就通过e2fsck来修复sdb5这个分区,但是修复的时候没选-a自动修复参数,默然是-y交互方式,导致修复的时候一直按y按了好长时间 囧。
## 小记
当磁盘出现问题的时候一般会发出信号,使得文件系统变成只读模式,此时不能修改和写入数据。这个时候比较快的策略应该是dmesg查看kernel的log,然后通过mount或者/proc/mounts看已经挂载分区的状态。如果是重要数据那么选择备份之后,卸载文件系统尝试通过e2fsck/fsck命令修复分区。
涉及命令:mount/umount/df/fdisk/lsof(这个命令很强大,非常有用)/fsck/e2fsck(-a自动修复,-y交互模式)
|
Java
|
UTF-8
| 1,504
| 2.40625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
*
*/
package net.community.chest.dom.impl;
import org.w3c.dom.DOMException;
import org.w3c.dom.ProcessingInstruction;
/**
* <P>Copyright 2009 as per GPLv2</P>
*
* @author Lyor G.
* @since Aug 26, 2009 9:47:57 AM
*/
public class StandaloneProcessingInstructionImpl
extends BaseNodeImpl<StandaloneProcessingInstructionImpl>
implements ProcessingInstruction {
public StandaloneProcessingInstructionImpl (String tgtName, String tgtData)
{
super(StandaloneProcessingInstructionImpl.class, tgtName, tgtData);
}
public StandaloneProcessingInstructionImpl (String tgtName)
{
this(tgtName, null);
}
public StandaloneProcessingInstructionImpl ()
{
this(null);
}
/*
* @see org.w3c.dom.Node#getNodeType()
*/
@Override
public final short getNodeType ()
{
return PROCESSING_INSTRUCTION_NODE;
}
/*
* @see org.w3c.dom.ProcessingInstruction#getTarget()
*/
@Override
public String getTarget ()
{
return getNodeName();
}
public void setTarget (String tgt)
{
setNodeName(tgt);
}
/*
* @see org.w3c.dom.ProcessingInstruction#getData()
*/
@Override
public String getData ()
{
return getNodeValue();
}
/*
* @see org.w3c.dom.ProcessingInstruction#setData(java.lang.String)
*/
@Override
public void setData (String data) throws DOMException
{
setNodeValue(data);
}
}
|
Go
|
UTF-8
| 2,857
| 2.984375
| 3
|
[
"LicenseRef-scancode-google-patent-license-golang",
"BSD-3-Clause",
"MIT"
] |
permissive
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"go/build"
"log"
"os"
"path"
"path/filepath"
"strings"
)
// Dirs is a structure for scanning the directory tree.
// Its Next method returns the next Go source directory it finds.
// Although it can be used to scan the tree multiple times, it
// only walks the tree once, caching the data it finds.
type Dirs struct {
scan chan string // directories generated by walk.
paths []string // Cache of known paths.
offset int // Counter for Next.
}
var dirs Dirs
func init() {
dirs.paths = make([]string, 0, 1000)
dirs.scan = make(chan string)
go dirs.walk()
}
// Reset puts the scan back at the beginning.
func (d *Dirs) Reset() {
d.offset = 0
}
// Next returns the next directory in the scan. The boolean
// is false when the scan is done.
func (d *Dirs) Next() (string, bool) {
if d.offset < len(d.paths) {
path := d.paths[d.offset]
d.offset++
return path, true
}
path, ok := <-d.scan
if !ok {
return "", false
}
d.paths = append(d.paths, path)
d.offset++
return path, ok
}
// walk walks the trees in GOROOT and GOPATH.
func (d *Dirs) walk() {
d.bfsWalkRoot(build.Default.GOROOT)
for _, root := range splitGopath() {
d.bfsWalkRoot(root)
}
close(d.scan)
}
// bfsWalkRoot walks a single directory hierarchy in breadth-first lexical order.
// Each Go source directory it finds is delivered on d.scan.
func (d *Dirs) bfsWalkRoot(root string) {
root = path.Join(root, "src")
// this is the queue of directories to examine in this pass.
this := []string{}
// next is the queue of directories to examine in the next pass.
next := []string{root}
for len(next) > 0 {
this, next = next, this[0:0]
for _, dir := range this {
fd, err := os.Open(dir)
if err != nil {
log.Printf("error opening %s: %v", dir, err)
return // TODO? There may be entry before the error.
}
entries, err := fd.Readdir(0)
fd.Close()
if err != nil {
log.Printf("error reading %s: %v", dir, err)
return // TODO? There may be entry before the error.
}
hasGoFiles := false
for _, entry := range entries {
name := entry.Name()
// For plain files, remember if this directory contains any .go
// source files, but ignore them otherwise.
if !entry.IsDir() {
if !hasGoFiles && strings.HasSuffix(name, ".go") {
hasGoFiles = true
}
continue
}
// Entry is a directory.
// No .git or other dot nonsense please.
if strings.HasPrefix(name, ".") {
continue
}
// Remember this (fully qualified) directory for the next pass.
next = append(next, filepath.Join(dir, name))
}
if hasGoFiles {
// It's a candidate.
d.scan <- dir
}
}
}
}
|
C++
|
GB18030
| 1,627
| 2.984375
| 3
|
[] |
no_license
|
// leetcode-462-ƽ.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string.h>
#include <math.h>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <stack>
#include<iomanip>
#include <ctype.h>
#include <algorithm>
using namespace std;
class Solution {
public:
void swap(vector<int>& nums, int i, int j)
{
int t = nums[j];
nums[j] = nums[i];
nums[i] = t;
}
int partion(vector<int>& nums, int st, int ed)
{
int key = nums[st];
int i = st;
int j = ed;
while (i <= j)
{
while (i <= j&&nums[i] <= key)
i++;
while (i <= j&&nums[j] >= key)
j--;
if (i<=ed&&j>=st&&i<=j)
swap(nums, i, j);
}
swap(nums,st,j);
return j;
}
int find_median(vector<int>& nums, int st, int ed, int k)
{
if (k > ed - st + 1)
return -1;
int pos = partion(nums,st,ed);
if (pos - st < k - 1)
return find_median(nums, pos + 1, ed, k - (pos-st+1));
else if (pos - st == k - 1)
return nums[pos];
else
return find_median(nums,st,pos-1,k);
}
int minMoves2(vector<int>& nums) {
int n = nums.size();
if (n == 0 || n == 1)
return 0;
sort(nums.begin(),nums.end());
if (n == 2 || n == 3)
return abs(nums[n - 1] - nums[0]);
long long sum = 0;
int mid = INT_MIN;
mid = find_median(nums,0,n-1,n/2+1);
for (int i = 0; i < n; i++)
{
if (nums[i] != mid)
sum += abs(nums[i]-mid);
}
return sum;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> ve;
ve = { 1,0,0,8,6};
Solution s;
s.minMoves2(ve);
return 0;
}
|
JavaScript
|
UTF-8
| 2,323
| 4.375
| 4
|
[] |
no_license
|
/**
* Function to find common elements in 3 arrays
* @Author me
*/
function FindCommonElements(arr, arr1,arr2){
var arr4 =[];
var arrS;
var arrSS;
var arrSSS;
//here we want to find an array with a shortest length, to give it as a first in for loop
if (arr.length <= arr1.length && arr.length <= arr2.length) {
arrS = arr;
arrSS = arr1;
arrSSS = arr2;
} else if (arr1.length <= arr.length && arr1.length <= arr2.length) {
arrS = arr1;
arrSS = arr;
arrSSS = arr2;
} else {
arrS = arr2;
arrSS = arr;
arrSSS = arr1;
}
let arrcopy=NoDuplicates(arrS);
// loop to find the same values in the given 3 arrays
for(var i=0; i<arrcopy.length;i++) {
for (var j = 0; j < arrSS.length; j++) {
if (arrcopy[i] === arrSS[j]) {
for (var t = 0; t < arrSSS.length; t++) {
if (arrcopy[i] === arrSSS[t]) {
arr4.push(arrcopy[i]);
break; // to avoid duplicates in the 3d array
}
}
break; // to avoid duplicates from 2nd array
}
}
}
/*
This is a help function makes a copy of array that doesn't have a duplicates
*/
function NoDuplicates(arrS){
let arrcopy= Array.from(arrS);
for(let c=0;c<arrcopy.length;c++){
for(let cc=c+1;cc<arrcopy.length;cc++){
if(arrcopy[c] === arrcopy[cc]){
arrcopy.splice(cc,1);
cc--; // added this line, each time when we delete a number from array we have to decrement index, cuz instead of
// for condition with cc++, in this fall we have cc+2
}
}
}
return arrcopy;
}
// if statement to print the right answer
if(arr4.length>1) {
console.log(arr4 + ' Are common elements of these 3 arrays');}
else if(arr4.length===1){console.log(arr4+ ' Is a common element of these 3 arrays');}
else {console.log('There are no common elements in these 3 arrays');}
}
FindCommonElements([1,2,5,2,3,1,1,1,1,4,2,5,6,3], [2,3,2,2,1,1,10], [3,4,5,6,7,8,2,2,2,2,2,3,1,1,1,1,1]);
//=> output => 2,3,1 Are common elements of these 3 arrays
|
JavaScript
|
UTF-8
| 1,355
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
// @flow
import {compose, divide} from 'ramda'
import keypress from 'keypress'
import {cursorTo, eraseScreen, cursorHide, cursorShow} from 'ansi-escapes'
import {Field, Tile, FieldLayer} from './field'
import {Player} from './creature'
import {Dungeon} from './generate-field'
keypress(process.stdin)
const divideInteger = compose(Math.round, divide)
// @flow-ignore
const screenWidth = process.stdout.columns
// @flow-ignore
const screenHeight = process.stdout.rows
const width = divideInteger(screenWidth, 5 / 4)
const height = divideInteger(screenHeight, 5 / 4)
const field:Dungeon = new Dungeon(width, height)
process.stdout.write(eraseScreen + cursorHide)
process.on('exit', () => {
process.stdout.write(eraseScreen + cursorShow)
})
// @flow-ignore
process.stdin.setRawMode(true)
field.layers[0].setWall()
field.generate()
const player = new Player(field.stairPosition[0], field.stairPosition[1], field)
process.stdin.on('keypress', (ch, key) => {
if (key) {
if (key.ctrl && key.name === 'c') {
process.exit(0)
}
if (key.name === 'h') {
player.moveNear(-1, 0)
}
if (key.name === 'j') {
player.moveNear(0, 1)
}
if (key.name === 'k') {
player.moveNear(0, -1)
}
if (key.name === 'l') {
player.moveNear(1, 0)
}
field.render()
}
})
process.stdin.resume()
field.render()
|
Markdown
|
UTF-8
| 11,725
| 3.203125
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: "Handling and Raising Events"
description: Learn to handle and raise .NET events, which are based on the delegate model. This model lets subscribers register with or receive notifications from providers.
ms.date: "07/22/2022"
ms.custom: devdivchpfy22
dev_langs:
- "csharp"
- "vb"
helpviewer_keywords:
- "delegate model for events"
- "application development [.NET], events"
- "application development [.NET], events"
- "application development [.NET Core], events"
- "events [.NET]"
- "events [.NET Core]"
- "events [.NET]"
ms.assetid: b6f65241-e0ad-4590-a99f-200ce741bb1f
---
# Handle and raise events
Events in .NET are based on the delegate model. The delegate model follows the [observer design pattern](observer-design-pattern.md), which enables a subscriber to register with and receive notifications from a provider. An event sender pushes a notification that an event has happened, and an event receiver receives that notification and defines a response to it. This article describes the major components of the delegate model, how to consume events in applications, and how to implement events in your code.
## Events
An event is a message sent by an object to signal the occurrence of an action. The action can be caused by user interaction, such as a button click, or it can result from some other program logic, such as changing a property's value. The object that raises the event is called the *event sender*. The event sender doesn't know which object or method will receive (handle) the events it raises. The event is typically a member of the event sender; for example, the <xref:System.Web.UI.WebControls.Button.Click> event is a member of the <xref:System.Web.UI.WebControls.Button> class, and the <xref:System.ComponentModel.INotifyPropertyChanged.PropertyChanged> event is a member of the class that implements the <xref:System.ComponentModel.INotifyPropertyChanged> interface.
To define an event, you use the C# [`event`](../../csharp/language-reference/keywords/event.md) or the Visual Basic [`Event`](../../visual-basic/language-reference/statements/event-statement.md) keyword in the signature of your event class, and specify the type of delegate for the event. Delegates are described in the next section.
Typically, to raise an event, you add a method that is marked as `protected` and `virtual` (in C#) or `Protected` and `Overridable` (in Visual Basic). Name this method `On`*EventName*; for example, `OnDataReceived`. The method should take one parameter that specifies an event data object, which is an object of type <xref:System.EventArgs> or a derived type. You provide this method to enable derived classes to override the logic for raising the event. A derived class should always call the `On`*EventName* method of the base class to ensure that registered delegates receive the event.
The following example shows how to declare an event named `ThresholdReached`. The event is associated with the <xref:System.EventHandler> delegate and raised in a method named `OnThresholdReached`.
[!code-csharp[EventsOverview#1](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#1)]
[!code-vb[EventsOverview#1](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#1)]
## Delegates
A delegate is a type that holds a reference to a method. A delegate is declared with a signature that shows the return type and parameters for the methods it references, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. A delegate declaration is sufficient to define a delegate class.
Delegates have many uses in .NET. In the context of events, a delegate is an intermediary (or pointer-like mechanism) between the event source and the code that handles the event. You associate a delegate with an event by including the delegate type in the event declaration, as shown in the example in the previous section. For more information about delegates, see the <xref:System.Delegate> class.
.NET provides the <xref:System.EventHandler> and <xref:System.EventHandler%601> delegates to support most event scenarios. Use the <xref:System.EventHandler> delegate for all events that don't include event data. Use the <xref:System.EventHandler%601> delegate for events that include data about the event. These delegates have no return type value and take two parameters (an object for the source of the event and an object for event data).
Delegates are [multicast](xref:System.MulticastDelegate), which means that they can hold references to more than one event-handling method. For more information, see the <xref:System.Delegate> reference page. Delegates provide flexibility and fine-grained control in event handling. A delegate acts as an event dispatcher for the class that raises the event by maintaining a list of registered event handlers for the event.
For scenarios where the <xref:System.EventHandler> and <xref:System.EventHandler%601> delegates don't work, you can define a delegate. Scenarios that require you to define a delegate are rare, such as when you must work with code that doesn't recognize generics. You mark a delegate with the C# [`delegate`](../../csharp/language-reference/builtin-types/reference-types.md#the-delegate-type) and Visual Basic [`Delegate`](../../visual-basic/language-reference/statements/delegate-statement.md) keyword in the declaration. The following example shows how to declare a delegate named `ThresholdReachedEventHandler`:
[!code-csharp[EventsOverview#4](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#4)]
[!code-vb[EventsOverview#4](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#4)]
## Event data
Data that is associated with an event can be provided through an event data class. .NET provides many event data classes that you can use in your applications. For example, the <xref:System.IO.Ports.SerialDataReceivedEventArgs> class is the event data class for the <xref:System.IO.Ports.SerialPort.DataReceived?displayProperty=nameWithType> event. .NET follows a naming pattern of ending all event data classes with `EventArgs`. You determine which event data class is associated with an event by looking at the delegate for the event. For example, the <xref:System.IO.Ports.SerialDataReceivedEventHandler> delegate includes the <xref:System.IO.Ports.SerialDataReceivedEventArgs> class as one of its parameters.
The <xref:System.EventArgs> class is the base type for all event data classes. <xref:System.EventArgs> is also the class you use when an event doesn't have any data associated with it. When you create an event that is only meant to notify other classes that something happened and doesn't need to pass any data, include the <xref:System.EventArgs> class as the second parameter in the delegate. You can pass the <xref:System.EventArgs.Empty?displayProperty=nameWithType> value when no data is provided. The <xref:System.EventHandler> delegate includes the <xref:System.EventArgs> class as a parameter.
When you want to create a customized event data class, create a class that derives from <xref:System.EventArgs>, and then provide any members needed to pass data that is related to the event. Typically, you should use the same naming pattern as .NET and end your event data class name with `EventArgs`.
The following example shows an event data class named `ThresholdReachedEventArgs`. It contains properties that are specific to the event being raised:
[!code-csharp[EventsOverview#3](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#3)]
[!code-vb[EventsOverview#3](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#3)]
## Event handlers
To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you're handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button. To receive notifications when the event occurs, your event handler method must subscribe to the event.
The following example shows an event handler method named `c_ThresholdReached` that matches the signature for the <xref:System.EventHandler> delegate. The method subscribes to the `ThresholdReached` event.
[!code-csharp[EventsOverview#2](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#2)]
[!code-vb[EventsOverview#2](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#2)]
## Static and dynamic event handlers
.NET allows subscribers to register for event notifications either statically or dynamically. Static event handlers are in effect for the entire life of the class whose events they handle. Dynamic event handlers are explicitly activated and deactivated during program execution, usually in response to some conditional program logic. For example, they can be used if event notifications are needed only under certain conditions or if an application provides multiple event handlers and run-time conditions define the appropriate one to use. The example in the previous section shows how to dynamically add an event handler. For more information, see [Events](../../visual-basic/programming-guide/language-features/events/index.md) (in Visual Basic) and [Events](../../csharp/programming-guide/events/index.md) (in C#).
## Raising multiple events
If your class raises multiple events, the compiler generates one field per event delegate instance. If the number of events is large, the storage cost of one field per delegate might not be acceptable. For those situations, .NET provides event properties that you can use with another data structure of your choice to store event delegates.
Event properties consist of event declarations accompanied by event accessors. Event accessors are methods that you define to add or remove event delegate instances from the storage data structure.
> [!NOTE]
> The event properties are slower than the event fields because each event delegate must be retrieved before it can be invoked.
The trade-off is between memory and speed. If your class defines many events that are infrequently raised, you'll want to implement event properties. For more information, see [How to: Handle Multiple Events Using Event Properties](how-to-handle-multiple-events-using-event-properties.md).
## Related articles
|Title|Description|
|-----------|-----------------|
|[How to: Raise and Consume Events](how-to-raise-and-consume-events.md)|Contains examples of raising and consuming events.|
|[How to: Handle Multiple Events Using Event Properties](how-to-handle-multiple-events-using-event-properties.md)|Shows how to use event properties to handle multiple events.|
|[Observer Design Pattern](observer-design-pattern.md)|Describes the design pattern that enables a subscriber to register with and receive notifications from a provider.|
## See also
- <xref:System.EventHandler>
- <xref:System.EventHandler%601>
- <xref:System.EventArgs>
- <xref:System.Delegate>
- [Events (Visual Basic)](../../visual-basic/programming-guide/language-features/events/index.md)
- [Events (C# Programming Guide)](../../csharp/programming-guide/events/index.md)
- [Events and routed events overview (UWP apps)](/windows/uwp/xaml-platform/events-and-routed-events-overview)
- [Events in Windows Store 8.x apps](/previous-versions/windows/apps/hh758286(v=win.10))
|
Java
|
UTF-8
| 896
| 2.0625
| 2
|
[] |
no_license
|
package com.erx.microservice.patientmanagement.service.wardmaster.createwardmaster;
/*
* created by Brighty on 17-11-2017
* */
import com.erx.microservice.patientmanagement.service.CommonServiceResponse;
public class CreateWardMasterServiceResponse extends CommonServiceResponse {
private long wardMasterId;
private String wardCode;
public CreateWardMasterServiceResponse() {
}
public CreateWardMasterServiceResponse(long wardMasterId, String wardCode) {
this.wardMasterId = wardMasterId;
this.wardCode = wardCode;
}
public long getWardMasterId() {
return wardMasterId;
}
public void setWardMasterId(long wardMasterId) {
this.wardMasterId = wardMasterId;
}
public String getWardCode() {
return wardCode;
}
public void setWardCode(String wardCode) {
this.wardCode = wardCode;
}
}
|
C
|
UTF-8
| 3,586
| 3.046875
| 3
|
[] |
no_license
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
int sock;
struct sockaddr_in addr;
int a = 3;
int b = 4;
int sumRes,sqrtRes;
int mul_port =48660;
int sum_port = 48661;
int sqrt_port=48662;
int main()
{
printf("Клиент для расчёта гипотенузы запущен в работу!\n");
printf("Введите катеты: \n");
scanf("%d", &a);
scanf("%d", &b);
system("gnome-terminal -- ./mulServer");
system("gnome-terminal -- ./sumServer");
system("gnome-terminal -- ./sqrtServer");
printf("--- Возведение катетов в квадрат---\n");
sendOnServer1(mul_port,a,b);
printf("--- Сложение катетов ---\n");
sumRes = sendOnServer2(sum_port,a,b);
printf("--- Извлечение квадратного корня ---\n");
sqrtRes = sendOnServer3(sqrt_port,sumRes);
printf("Сервера посчитали результат!\n");
printf("Ответ: %d \n",sqrtRes);
return EXIT_SUCCESS;
}
void sendOnServer1(int port, int value,int value2){
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
perror("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int c = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
perror("connect");
int s = send(sock, &value, sizeof(value), 0);
perror("send");
printf("Отправил число: %d \n",value);
int r = recv(sock, &value, sizeof(value), 0);
perror("recv");
printf("Пришло число: %d \n",value);
a = value;
//-----------------------------------------------------------
s = send(sock, &value2, sizeof(value2), 0);
perror("send");
printf("Отправил число: %d \n",value2);
r = recv(sock, &value2, sizeof(value2), 0);
perror("recv");
printf("Пришло число: %d \n",value2);
b = value2;
close(sock);
perror("close");
}
int sendOnServer2(int port, int value,int value2){
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
perror("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int c = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
perror("connect");
int s = send(sock, &value, sizeof(value), 0);
perror("send");
printf("Отправил число: %d \n",value);
int r = recv(sock, &value, sizeof(value), 0);
perror("recv");
//-----------------------------------------------------------
s = send(sock, &value2, sizeof(value2), 0);
perror("send");
printf("Отправил число: %d \n",value2);
r = recv(sock, &value2, sizeof(value2), 0);
perror("recv");
printf("Пришло число: %d \n",value2);
close(sock);
perror("close");
return value2;
}
int sendOnServer3(int port, int value){
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
perror("socket");
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int c = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
perror("connect");
int s = send(sock, &value, sizeof(value), 0);
perror("send");
printf("Отправил число: %d \n",value);
int r = recv(sock, &value, sizeof(value), 0);
perror("recv");
printf("Пришло число: %d \n",value);
close(sock);
perror("close");
return value;
}
|
PHP
|
UTF-8
| 4,750
| 2.515625
| 3
|
[] |
no_license
|
<?php
namespace Common\Model;
use Think\Model;
//飞船信息
class AirshipModel extends Model{
/*
ALTER TABLE `airship` ADD `type` INT( 3 ) NOT NULL DEFAULT '1' COMMENT '类型 1|文字 2|图片 3|语音' AFTER `airship_content` ,
ADD `url` TEXT NOT NULL COMMENT '图片音频地址 图片使用,隔开' AFTER `type` ,
ADD `times` INT( 11 ) NOT NULL COMMENT '语音时长(秒)' AFTER `url` ;
*/
protected $tableName = 'airship';
/*
* 获取我的飞船列表
*/
public function getMyShipList($userid,$limit1) {
$where = " userid =".$userid;
$Model = M('Airship');
$result = $Model->where($where)->limit($limit1)->order('addtime desc')->select();
if(!empty($result)){
$UserModel = D('User');
$fabuzhe= $UserModel->getusermsgbyuserid($userid);
$AirShipStopsModel=D("AirShipStops");
for($i=0;$i<count($result);$i++){
$result[$i]['usermsg'] =$fabuzhe; //发布者信息
//停靠点(用户信息、星球信息)
$result[$i]['stopsmsg']= $AirShipStopsModel->getMyShipStops($result[$i]["airship_id"] );
}
}
if(!$result){
$result=array();
//$result=(object)array();
}
return $result;
}
/*
* 获取飞船详情
*/
public function getShipDetail($airship_id) {
$UserModel = D('User');
$where = "airship_id =".$airship_id;
$Model=M("Airship");
$result = $Model->where($where)->find();
if($result){
$result['user_msg'] = $UserModel->getusermsgbyuserid($result["userid"]);
if($result['url']!=""){
$imgarr = explode(",",$result['url']);
for($i=0;$i<count($imgarr);$i++){
$result['urlpath'][$i]["img"]=imgpath($imgarr[$i]);
}
}
}
if(!$result){
$result=(object)array();
}
return $result;
}
/*
* 根据爱好id(字符串)获取爱好信息
*/
public function getHobbyNameString($hobbyid) {
if($hobbyid==0){
$result="";
return $result;
}
$hobby = explode(",", $hobbyid);
if(count($hobby)!=0){
for($i=0;$i<count($hobby);$i++){
$hobbyname = $this->getHobbyName($hobbyid);
}
$result = implode(",", $hobbyname);
}else{
$result="";
}
return $result;
}
/*
* 根据爱好id获取爱好信息
*/
public function getHobbyName($hobbyid) {
$model = M('Hobby');
$where = "hobbyid =".$hobbyid;
$result = $model->where($where)->find();
return $result;
}
/*
* 发送飞船(添加)
*/
public function addship($data) {
$model = M('Airship');
$data['addtime'] = time();
$data['airship_status'] = 0;
$result = $model->add($data);
return $result;
}
/*
* 判断飞船id与userid是否一致
*/
public function judgeUserShip($userid,$airship_id) {
$model = M('Airship');
$where = " airship_id =".$airship_id;
$result = $model->field('userid')->where($where)->find();
if($result['userid'] == $userid){
return true;
}else{
return false;
}
}
/*
*删除airship
*/
public function deleteAirShip($airship_id) {
$model = M('Airship');
$where = " airship_id =".$airship_id;
$result = $model->where($where)->delete();
return $result;
}
/*
* 删除airship_stops中的airship
*/
public function deleteAirShipStops($airship_id) {
$model = M('Airship_stops');
$where = " airship_id =".$airship_id;
$result = $model->where($where)->delete();
return $result;
}
/*
* 改变飞船状态
*/
public function changeAirShipStatus($airship_id) {
$model = M('Airship');
$where = " airship_id =".$airship_id;
$data['airship_status'] = 0;
$result = $model->where($where)->save($data);
return $result;
}
/*
* 修改飞船信息
*/
public function editpost($where,$data) {
$Model = M('airship');
$res = $Model->where($where)->save($data);
return $res;
}
/*
* 改变停靠仓飞船状态
*/
public function changeAirStopsStatus($airship_id,$airship_stops_id) {
$model = M('Airship_stops');
$where = " airship_id =".$airship_id." and airship_stops_id =".$airship_stops_id;
$data['stops_status'] = 2;
$data['leavetime'] = time();
$result = $model->where($where)->save($data);
return $result;
}
}
|
Python
|
UTF-8
| 2,682
| 3.484375
| 3
|
[] |
no_license
|
import numpy as np
#needed: derivee par rapport au parametres et derivee de la sortie par rapport aux entrees
#modules:
#1) module (eg lineaire) : ok
#2) module activation : pas de parametres, seulement derivee
class Loss(object):
def forward(self, y, yhat):
return
#cout
def backward(self, y, yhat):
return
#calcul le gradient du cout
#############################NOTES
## DEUX TYPES DE MODULES: Activation et Lineires
## Pour les fonctions d'activation: pas de parametres w_ij, seulement une derivee
## En gros, c'est ton g' (2 si tu transformes ton erreur en faisant *2 partout)
class SigmoidModule(object):
#
def __init__(self):
self._parameters = None #matrice de poids par exemple
self._gradient = None #accumule le gradient calcule
def zero_grad(self):
self._gradient = np.zeros(self._gradient.shape())
#Annule gradient
def forward(self, X):
np.dot(w.T, X)
return
#passe forward
def update_parameters(self, gradient_step):
return
#mise a jour des parametres selon le gradient et le pas gradient_step
def backward_update_gradient(self, input, delta):
return
#met a jour la valeur du gradient par rapport au parametres
def backward_delta(self, input, delta):
return
#derivee de l'erreur : renvoie l'erreur derriere
class LinearModule(object):
def __init__(self,n,m):
self._parameters = np.zeros((n,m)) #matrice de poids par exemple
self._gradient = np.zeros((n,m))#accumule le gradient calcule
def zero_grad(self):
#Annule gradient
self._gradient = np.zeros(self._gradient.shape())
def forward(self, X):
return np.dot(self._parameters.T, X.T).T
#passe forward
def update_parameters(self, gradient_step):
self._parameters -= gradient_step * self._gradient
return
#mise a jour des parametres selon le gradient et le pas gradient_step
def backward_update_gradient(self, input, delta):
# EN GROS: accumulation du gradient, qui est la derivee de la Loss par rapport aux poids
# Donc une matrice de taille de w_ij pour i,j qui varient bien pour les poids
# On accumule le gradient pour pouvoir faire du stochastique ou du batch
# C'est pas optimise, il faudrait plutot faire du calcul avec des tenseurs plutot que de faire des appels systemes a chaque fois
#self._gradient = self.gradi np.dot(input, delta)
return
#met a jour la valeur du gradient par rapport au parametres
def backward_delta(self, input, delta):
delta *
return
#derivee de l'erreur : renvoie l'erreur derriere
def main():
datax = np.random.random_sample((1,5))
m = LinearModule(5,1)
result = m.forward(datax)
m.backward_update_gradient(datax, [0,0,0,0])
print(result)
return
if __name__ == "__main__":
main()
|
C#
|
UTF-8
| 7,702
| 2.765625
| 3
|
[] |
no_license
|
//#define LOGGING_DEBUG
#define LOGGING_INFO
using CodeJam._2014.Round2;
using CodeJam.Utils.geom;
using CodeJam.Utils.graph;
using CodeJam.Utils.math;
using CodeJamUtils;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utils;
using Wintellect.PowerCollections;
using Logger = Utils.LoggerFile;
namespace Year2014.Round3.Problem1
{
public class MagicalMarvelousTourInput
{
public int N;
public int p;
public int q;
public int r;
public int s;
}
public class MagicalMarvelousTour : InputFileProducer<MagicalMarvelousTourInput>, InputFileConsumer<MagicalMarvelousTourInput, String>
{
public MagicalMarvelousTourInput createInput(Scanner scanner)
{
MagicalMarvelousTourInput input = new MagicalMarvelousTourInput();
input.N = scanner.nextInt();
input.p = scanner.nextInt();
input.q = scanner.nextInt();
input.r = scanner.nextInt();
input.s = scanner.nextInt();
//Logger.LogInfo("Input {}", scanner.finishPlayBack());
return input;
}
public String processInput(MagicalMarvelousTourInput input)
{
List<int> values = new List<int>();
//running sums is sum given index elements
List<long> runningSums = new List<long>();
runningSums.Add(0);
for (int n = 0; n < input.N; ++n)
{
values.Add((int)((1L * n * input.p + input.q) % input.r + input.s));
runningSums.Add(runningSums[n] + values[n]);
}
long minZ = 0;
long maxZ = runningSums.GetLastValue();
while(minZ < maxZ)
{
long z = minZ + (maxZ-minZ) / 2;
int i = findAtMost(runningSums, 0, input.N , z);
int j = findAtMost(runningSums, i, input.N , z + runningSums[i]);
Preconditions.checkState(runningSums[i] <= z);
Preconditions.checkState(i == input.N || runningSums[i+1] > z);
Preconditions.checkState(sumInc(runningSums, i+1, j) <= z);
Preconditions.checkState(j == input.N || sumInc(runningSums, i + 1, j + 1) > z);
Preconditions.checkState(j >= i);
long rightSectionSum = sumInc(runningSums, j + 1, input.N );
if (rightSectionSum > z)
{
minZ = z + 1;
}
else
{
maxZ = z;
}
}
Preconditions.checkState(minZ == maxZ);
return (1d * (runningSums.GetLastValue() - minZ) / runningSums.GetLastValue()).ToString(CultureInfo.GetCultureInfo("en-US"));
}
public static long sumInc(List<long> runningSums, int left, int right)
{
if (right >= runningSums.Count)
return 0;
if (right < 0)
return 0;
return runningSums[right] - (left > 0 ? runningSums[left - 1] : 0);
}
public static int findAtMost(List<long> runningSums, int minToTake, int maxToTake, long z)
{
while(minToTake < maxToTake)
{
//Check invariant
Preconditions.checkState(runningSums[minToTake] <= z);
//round up
int index = minToTake + (maxToTake-minToTake+1) / 2;
if (runningSums[index] > z)
{
//too far, maximum must be before index
maxToTake = index - 1;
}
else
{
minToTake = index;
}
}
Preconditions.checkState(minToTake == maxToTake);
return minToTake;
}
public String processInputOrig(MagicalMarvelousTourInput input)
{
List<int> values = new List<int>();
for (long n = 0; n < input.N; ++n )
{
values.Add( (int) ( (n * input.p + input.q) % input.r + input.s));
}
List<long> runningSums = new List<long>();
runningSums.Add(values[0]);
for (int n = 1; n < input.N; ++n)
{
runningSums.Add(runningSums[n - 1] + values[n]);
}
long lowestMax = long.MaxValue;
Func<int, int, long> sumInc = (__left, __right) =>
{
if (__right >= runningSums.Count)
return 0;
if (__right < 0)
return 0;
return runningSums[__right] - ( __left > 0 ? runningSums[__left - 1] : 0);
};
for (int start = 0; start < input.N; ++start )
{
long leftSum = -1;
if (start > 0)
{
leftSum = runningSums[start - 1];
}
//Binary search for stop
int minStop = start;
int maxStop = input.N - 1;
while(maxStop > minStop)
{
int midPoint = (maxStop + minStop) / 2;
long middle = sumInc(start, midPoint);
long right = sumInc(midPoint + 1, input.N - 1);
Logger.LogDebug("Finding midpoint. Range [{}-{}] middle {} [{}-{}] right {} min/max {} {}",
start, midPoint,
middle,
midPoint+1, input.N - 1,
right, minStop, maxStop);
long diff = right - middle;
int nextVal = values[midPoint + 1];
Logger.LogDebug("Difference {}. Value mid+1 {}", diff, nextVal);
if (right > middle && diff < nextVal)
{
Logger.LogDebug("Right sum is larger, but if switch mid+1, the right sum will stay less, and |diff| > current difference {} < {}", diff, nextVal);
minStop = maxStop = midPoint;
break;
}
if (middle >= right)
{
maxStop = midPoint;
}
else
{
minStop = midPoint+1;
}
}
Preconditions.checkState(minStop == maxStop);
Logger.LogDebug("Binary search yielded range [{}-{}] Sums {} {} {}", start, minStop,
sumInc(0, start - 1), sumInc(start, minStop), sumInc(minStop + 1, input.N - 1));
long[] sums = new long[] { sumInc(0, start - 1), sumInc(start, minStop), sumInc(minStop + 1, input.N - 1) };
int stop = minStop;
long localLow = sums.Max();
// long oldLowestMax = lowestMax;
lowestMax = Math.Min(lowestMax, localLow);
//if (lowestMax != oldLowestMax)
{
// Logger.LogDebug("Choosing range [{} to {}] with sums {} {} {}", start, stop, leftSum, middleSum, rightSum);
}
}
return (1d * (runningSums.GetLastValue() - lowestMax) / runningSums.GetLastValue()).ToString(CultureInfo.GetCultureInfo("en-US"));
}
}
}
|
Java
|
UTF-8
| 1,342
| 2.296875
| 2
|
[] |
no_license
|
package com.sample.kcquickstart;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.utils.AppInfoParser;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.sink.SinkConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KCQuickstartSinkConnector extends SinkConnector {
private static Logger log = LoggerFactory.getLogger(KCQuickstartSinkConnector.class);
Map<String, String> settings;
private KCQuickstartSinkConnectorConfig config;
@Override
public String version() {
return AppInfoParser.getVersion();
}
@Override
public void start(Map<String, String> props) {
log.info("Starting KCQuickstartSinkConnectorConfig");
this.config = new KCQuickstartSinkConnectorConfig(props);
this.settings = props;
}
@Override
public Class<? extends Task> taskClass() {
return KCQuickstartSinkTask.class;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
List<Map<String, String>> configs = new ArrayList();
for (int i = 0; i < maxTasks; i++) {
configs.add(this.settings);
}
return configs;
}
@Override
public void stop() {
}
@Override
public ConfigDef config() {
return KCQuickstartSinkConnectorConfig.conf();
}
}
|
C++
|
WINDOWS-1252
| 1,215
| 3.34375
| 3
|
[] |
no_license
|
/*
Question:
Write a program to print all Subsequences of String which Start with Vowel and End with Consonant
Given a string return all possible subsequences which start with vowel and end with a consonant. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order.
Examples:
Input : abc
Output : ab, ac, abc
Input : aab
Output : ab, aab
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
const int max_n = 1e5+5;
int main()
{
int n; cin>>n; int a[max_n]; long sum=0;
for(auto i=0;i<n;i++)
{
cin>>a[i];
sum+=a[i];
}
double mean, median;
mean = (double)sum/n;
sort(a,a+n);
if(n%2==0)
median = (double)(a[n/2-1]+a[n/2])/2;
else
median = a[n/2];
int mode=a[0], mx=1, cnt=1;
for(auto i=0;i<n-1;i++)
{
if(a[i]==a[i+1]) {
++cnt;
}
else
cnt=1;
if(cnt>mx)
{
mx=cnt;
mode=a[i];
}
}
cout<<mean<<"\n"<<median<<"\n"<<mode;
return 0;
}
|
C++
|
UTF-8
| 6,182
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
// OilerMotor.h
//
// (c) 2021 Mark Naylor
//
// defines class for motors driving an oiler, extends MotorClass and adds support for an input pin that signals when units of work (i.e. oil drips) are seen from from motor
// functionally adds support to:
// only count work units that are separated by a specified debounce time (in milliseconds)
// idle the motor when a specified threshold of work units is met
// restart the motor after a specified time (in seconds) is passed
//
// This class implements a state table to control how the motor state changes in response to external events (e.g. signal work done, timer tick, on or off request
//
// Different types of motos used to do oiling e.g. a stepper motor or simple dc motor controlled by a relay switch derive from this class and override specific
// functions to idle, stop and start the motor.
//
#ifndef _OILER_MOTOR_h
#define _OILER_MOTOR_h
#include "Motor.h"
class OilerMotorClass : public MotorClass
{
protected:
class StateTable
{
typedef uint16_t ( OilerMotorClass::*OilerMotorStateCallback )( uint32_t ulParam );
public:
typedef struct
{
uint16_t uiCurrentState; // Current state
uint16_t uiEventId; // Event that happened
OilerMotorStateCallback FnState; // function to be called to process this event when in this state
} STATE_TABLE_ENTRY, * PSTATE_TABLE_ENTRY;
StateTable ( PSTATE_TABLE_ENTRY pTable, uint16_t uiNumEntries );
uint16_t GetCurrentState ( void );
bool ProcessEvent ( OilerMotorClass* pMotor, uint16_t uiEventId, uint32_t ulParam );
protected:
PSTATE_TABLE_ENTRY m_pTable; // ptr to array of table entries
uint16_t m_uiNumTableEntries; // number of table entries
uint16_t m_uiCurrentState; // Current State
void SetState ( uint16_t uiNewState );
};
public:
// State table functions
virtual uint16_t TurnOn ( uint32_t ulParam ); // function called to turn motor on and return new state
virtual uint16_t TurnOff ( uint32_t ulParam ); // function called to turn motor off and return new state
virtual uint16_t CheckWork ( uint32_t ulParam ); // function called to check if sufficient oil has been produced and to idle motor if it has
virtual uint16_t CheckAlert ( uint32_t ulParam ); // function called to check if threshold exceeded for oil to be produced
virtual uint16_t CheckRestart ( uint32_t ulParam ); // function called to check if restart required
virtual uint16_t DoNothing ( uint32_t ulParam );
// abstract function that derived classes must implement
virtual void Idle () = 0; // Idle motor, still energised but not moving
virtual void Start () = 0; // Start motor
virtual void PowerOff () = 0; // power off motor
protected:
uint8_t m_uiWorkPin; // input Pin that indicates when a unit of work has been seen
uint32_t m_ulWorkThreshold; // number of units to be seen before idling motor
uint32_t m_ulDebounceMin; // number of milliseconds that must elapse before a subsequent workpin signal is treated as real
uint16_t m_uiWorkCount; // number of work units seen since last reset
uint32_t m_ulLastWorkSignal; // time of last signal in millis
uint16_t m_uiRestartValue; // Value after which motor should be restarted
uint32_t m_ulAlertThreshold; // if beyond this threshold then the motor is taking too long to oil
bool m_bError; // true if motor not completed work within alert threshold
uint32_t m_ulModeMetricAtStart; // value of mode metric being used when motor last started
uint32_t m_ulModeMetricAtIdle; // value of mode metric being used when motor last idled
StateTable m_MotorState;
/*
* Oiler Motor State table
*/
public:
enum eOilerMotorState : uint16_t // States motor can be in
{
OFF = 0, // OFF => not energised, default state at start must be 0
IDLE, // IDLE imples not moving but is being held stationary
MOVING
};
enum eOilerMotorEvents : uint16_t // events that can change motor state
{
TURN_ON = 0, // Request to turn on
TURN_OFF, // Request to turn off
WORK_SEEN, // Output seen
TIMER // Timer check
};
private:
StateTable::STATE_TABLE_ENTRY MotorTable [ 12 ]
{
{ OFF, TURN_ON, &OilerMotorClass::TurnOn }, // start motor moving
{ OFF, TURN_OFF, &OilerMotorClass::DoNothing }, // if off no need to turn off, ignore
{ OFF, WORK_SEEN, &OilerMotorClass::DoNothing }, // if off and oil drips output, ignore
{ OFF, TIMER, &OilerMotorClass::DoNothing }, // if off ignore time
{ MOVING, TURN_ON, &OilerMotorClass::DoNothing }, // if moving no need to start moving, ignore
{ MOVING, TURN_OFF, &OilerMotorClass::TurnOff }, // if moving, turn off
{ MOVING, WORK_SEEN, &OilerMotorClass::CheckWork }, // if moving and oil drip see check if enough produced and idle motor
{ MOVING, TIMER, &OilerMotorClass::CheckAlert }, // if moving, check if taking too long
{ IDLE, TURN_ON, &OilerMotorClass::TurnOn }, // start motor moving
{ IDLE, TURN_OFF, &OilerMotorClass::TurnOff }, // turn off
{ IDLE, WORK_SEEN, &OilerMotorClass::DoNothing }, // oil produced whilst idle - ignore
{ IDLE, TIMER, &OilerMotorClass::CheckRestart } // see if we need to restart based on time idle
};
public:
OilerMotorClass ( uint8_t uiWorkPin, uint32_t ulThreshold, uint32_t ulDebouncems, uint32_t ulSpeed, uint16_t uiRestartThreshold );
virtual bool On ( void );
virtual bool Off ( void );
uint32_t GetModeMetricAtStart ( void );
uint32_t GetModeMetricAtIdle ( void );
void IncWorkUnits ( uint16_t uiNewUnits = 1 );
void ResetWorkUnits ( void );
void SetDebouncems ( uint32_t ulDebouncems );
void SetWorkThreshold ( uint32_t ulWorkThreshold );
void SetRestartThreshold ( uint16_t uiRestartValue );
void SetAlertThreshold ( uint32_t ulAlertThreshold );
void SetModeMetricAtStart ( uint32_t ulMetric );
void SetModeMetricAtIdle ( uint32_t ulMetric );
bool Action ( eOilerMotorEvents eAction, uint32_t ulParam = 0UL );
uint16_t GetWorkUnits ();
eOilerMotorState GetOilerMotorState ();
bool IsIdle ();
bool IsMoving ();
bool IsOff ();
bool IsInError ();
};
#endif
|
Java
|
UTF-8
| 1,856
| 2.46875
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package org.firstinspires.ftc.robotcontroller.internal.Core.Utility;
import com.disnodeteam.dogecv.CameraViewDisplay;
import com.disnodeteam.dogecv.DogeCV;
import com.disnodeteam.dogecv.detectors.roverrukus.GoldAlignDetector;
import com.disnodeteam.dogecv.detectors.roverrukus.SamplingOrderDetector;
import com.qualcomm.robotcore.hardware.HardwareMap;
public class UtilGoldDetector {
public GoldAlignDetector detector;
public UtilGoldDetector(HardwareMap hardwareMap){
detector = new GoldAlignDetector(); // Create detector
detector.init(hardwareMap.appContext, CameraViewDisplay.getInstance()); // Initialize it with the app context and camera
detector.useDefaults(); // Set detector to use default settings
// Optional tuning
detector.alignSize = 100; // How wide (in pixels) is the range in which the gold object will be aligned. (Represented by green bars in the preview)
detector.alignPosOffset = 0; // How far from center frame to offset this alignment zone.
detector.downscale = 0.4; // How much to downscale the input frames
detector.areaScoringMethod = DogeCV.AreaScoringMethod.MAX_AREA; // Can also be PERFECT_AREA
//detector.perfectAreaScorer.perfectArea = 10000; // if using PERFECT_AREA scoring
detector.maxAreaScorer.weight = 0.005; //
detector.ratioScorer.weight = 5; //
detector.ratioScorer.perfectRatio = 1.0; // Ratio adjustment
detector.enable(); // Start the detector!
}
public boolean isAligned(){
return detector.getAligned();
}
public double getPos(){
return detector.getXPosition();
}
public double getAlignSize(){return detector.alignSize;}
public void setAlignSize(double size){detector.alignSize = size;}
public void stop(){
detector.disable();
}
}
|
Python
|
UTF-8
| 17,025
| 2.71875
| 3
|
[] |
no_license
|
import hand
import math
import random
import sys
from autonomic import axon, help, Dendrite
from datastore import Drinker
# Broken after some major refactoring, despite
# Ken's hard work. Probably not too far off; the
# nitty gritty work is still solid. Needs a
# sitin/sitout functionality of some kind.
class Player(object):
name = ''
status = 'in'
money = 0
round_money = 0
hand_money = 0
besthand = None
winlimit = None
hand = []
def __init__(self, name, money):
self.name = name
self.money = money
def __repr__(self):
r = "Player(name=%r, money=%r, round_money=%r, hand_money=%r, "\
"status=%r, hand=%r, winlimit=%r, besthand=%r)" % \
(self.name, self.money, self.round_money, self.hand_money,
self.status, self.hand, self.winlimit, self.besthand)
return r
def bet(self, money):
self.money -= money
self.round_money += money
self.hand_money += money
def reset(self):
self.winlimit = None
self.besthand = None
self.round_money = 0
self.hand_money = 0
self.hand = []
class Holdem(Dendrite):
def __init__(self, cortex):
super(Holdem, self).__init__(cortex)
self.firstpassed = None
self.lastraised = None
self.blind = 1
self.littleblind = None
self.bigblind = None
self.cardpointer = 0
self.playerpointer = 0
self.players = {}
self.burncards = []
self.pot = 0
self.bet = 0
self.hand = []
self.playingholdem = False
self.stages = (
'blind',
'bet', # set player pointer to left of dealer at each bet phase
'flop',
'bet',
'turn',
'bet',
'river',
'bet',
'distribute', # move dealer
)
self.stage = 0
@axon
@help("STARTING_FUNDS PLAYER_1 PLAYER_2 ... [PLAYER_N] <start holdem game>")
def holdem(self):
if self.playingholdem:
self.announce("Game already in progress.")
return
try:
self.stake = int(self.values.pop(0))
except:
self.announce("First entry must be a number.")
return
if len(self.values) < 2:
self.announce("You must have at least two players.")
return
self.playingholdem = True
self.order = self.values
random.shuffle(self.order)
self.dealer = 0
for player in self.order:
self.players[player] = Player(player, self.stake)
self._suits = ['s', 'h', 'd', 'c']
self.suits = (u'\u2660', u'\u2665', u'\u2666', u'\u2663')
self.ordinal = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
self.cards = []
for suit in self.suits:
for ordinal in self.ordinal:
self.cards.append(ordinal + suit)
self.deal()
def checkround(self):
fn = {
"flop": self.flop,
"turn": self.turncard,
"river": self.river,
"distribute": self.distribute,
}.get(self.stages[self.stage])
if fn:
fn()
@axon
@help("<stop playing>")
def sitout(self):
self._set_status("sitout")
@axon
@help("<resume playing>")
def sitin(self):
self._set_status("waiting")
def _set_status(self, status):
player = self.lastsender
if player not in self.players:
self.announce("You ain't in this game, pardner")
return
self.players[player].status = status
@axon
@help("AMOUNT <raise the bet by [amount]>")
def raiseit(self):
player = self.lastsender
if player != self.order[self.playerpointer]:
self.chat("Not your turn")
return
try:
money = self.values[0]
amount = int(money)
except:
self.announce("That's not money")
return
if amount <= 0:
self.announce("That's not money")
return
amount += self.bet
difference = amount - self.players[player].round_money
if difference > self.players[player].money:
self.announce("You don't have enough money")
return
elif difference == self.players[player].money:
self.allin()
return
self.pot += difference
self.players[player].bet(difference)
self.lastraised = player
self.firstpassed = None
if self.bet == 0:
message = player + " bets " + str(amount) + ". "
if amount == self.bet:
message = player + " calls. "
elif amount > self.bet:
message = player + " raises the bet to " + str(amount) + ". "
self.bet = amount
self.turn(prepend=message)
@axon
@help("<match the current bet>")
def callit(self):
player = self.lastsender
if player != self.order[self.playerpointer]:
self.chat("Not your turn")
return
difference = self.bet - self.players[player].round_money
if difference == 0:
return self.knock()
if difference > self.players[player].money:
self.announce("You don't have enough money")
return
self.pot += difference
self.players[player].bet(difference)
if self.players[player].money == 0:
self.players[player].status = "allin"
message = player + " calls. "
self.turn(prepend=message)
@axon
@help("<show how much money you have>")
def mymoney(self):
self.chat(str(self.players[self.lastsender].money))
@axon
@help("<show how much money everybody has>")
def allmoney(self):
for player, p in self.players.iteritems():
self.chat("%s: %d, %s" % (player, p.money, p.status))
print p
@axon
@help("<pass>")
def knock(self):
player = self.lastsender
if player != self.order[self.playerpointer]:
self.chat("Not your turn")
return
# feels a little awkward, but it's logical.
if self.bet == self.blind * 2 and player == self.bigblind:
self.lastraised = self.bigblind
self.bigblind = None
self.littleblind = None
self.announce("%s passes." % player)
self.turn(jump=0)
return
difference = self.bet - self.players[player].round_money
if difference > 0:
self.announce("You can't pass.")
return
if not self.firstpassed:
self.firstpassed = player
message = player + " passes. "
self.turn(prepend=message)
@axon
@help("<you can probably figure this one out>")
def fold(self):
player = self.lastsender
if player != self.order[self.playerpointer]:
self.chat("Not your turn.")
return
self.players[player].status = "folded"
message = player + " folds. "
remaining = 0
for player in self.players:
if self.players[player].status in ("in", "allin"):
remaining += 1
lastman = player
if remaining == 1:
self.distribute(lastman)
else:
self.turn(prepend=message)
@axon
@help("<go all in>")
def allin(self):
player = self.lastsender
if player != self.order[self.playerpointer]:
self.chat("Not your turn")
return
money = self.players[player].money + self.players[player].round_money
difference = self.bet - self.players[player].round_money
if self.bet < money:
self.bet = money
self.pot += self.players[player].money
self.players[player].bet(self.players[player].money)
self.players[player].status = "allin"
# see if it was actually a raise
if difference > 0:
self.lastraised = player
self.firstpassed = None
message = player + " goes all in. "
self.turn(prepend=message)
@axon
@help("<show the current bet amount>")
def thebet(self):
self.chat("Bet is " + str(self.bet))
@axon
@help("<show the amount in the pot>")
def thepot(self):
self.chat("Pot is " + str(self.pot))
def turn(self, jump=1, prepend=""):
start = self.playerpointer
self.playerpointer += jump
self.playerpointer = self.playerpointer % len(self.players)
# This is a bit convoluted, but it's trying to determine if everyone
# has had a chance to play. If we go all the way around the table
# without finding anyone 'in', we still move to the next round. That
# means no one is 'in' or only one person is 'in'.
in_count = len([p for p in self.players.itervalues()
if p.status == "in"])
if in_count > 1:
next_round = False
while True:
player = self.order[self.playerpointer]
if player in (self.lastraised, self.firstpassed):
next_round = True
if self.players[player].status == "in":
break
self.playerpointer = (self.playerpointer + 1) % len(self.players)
if start == self.playerpointer:
next_round = True
break
else:
next_round = True
if next_round:
self.announce(prepend)
self.firstpassed = None
self.lastraised = None
stillin = 0
for p in self.players.itervalues():
if p.status in ("in", "allin"):
stillin += 1
potbuffer = 0
for p in self.players.itervalues():
if p.status == "allin" and p.money <= self.bet:
#p.winlimit = self.pot + p.money * stillin
p.winlimit = p.hand_money * stillin
potbuffer += p.money
p.money = 0
if p.status == "allin" and p.money > self.bet:
p.money -= self.bet
p.status = "in"
potbuffer += self.bet
self.pot += potbuffer
for p in self.players.itervalues():
p.round_money = 0
self.stage += 1
self.checkround()
else:
player = self.order[self.playerpointer]
self.announce(prepend + player + "'s turn.")
def deal(self):
self.bet = 0
self.pot = 0
self.burncards = []
self.stage = 0
self.cardpointer = 0
self.hand = []
for p in self.players.itervalues():
p.reset()
self.dealer = (self.dealer + 1) % len(self.players)
self.playerpointer = self.dealer
random.shuffle(self.cards)
for card in range(2):
for p in self.players.itervalues():
if p.status not in ["sitout", "done"]:
p.status = "in"
p.hand.append(self.cards[self.cardpointer])
self.cardpointer += 1
# handle initial states here
for player, p in self.players.iteritems():
self.chat(" ".join(p.hand), player)
self.pot = self.blind * 3
self.bet = self.blind * 2
self.littleblind = self.order[(self.dealer + 1) % len(self.players)]
self.bigblind = self.order[(self.dealer + 2) % len(self.players)]
self.players[self.littleblind].bet(self.blind)
self.players[self.bigblind].bet(self.blind * 2)
message = self.littleblind + " puts in little blind for " + str(self.blind) + ", "
message += self.bigblind + " puts in big blind for " + str(self.blind * 2) + ". "
self.stage = 1
self.turn(jump=3, prepend=message)
return
def nextbet(self, type=""):
self.announce(type + ": " + " ".join(self.hand))
self.bet = 0
self.lastraised = None
self.firstpassed = None
self.playerpointer = self.dealer
self.stage += 1
self.turn()
def burn(self):
self.burncards.append(self.cards[self.cardpointer])
self.cardpointer += 1
def flop(self):
self.burn()
for card in range(3):
self.hand.append(self.cards[self.cardpointer])
self.cardpointer += 1
self.nextbet("Flop")
def turncard(self):
self.burn()
self.hand.append(self.cards[self.cardpointer])
self.cardpointer += 1
self.nextbet("Turn")
def river(self):
self.burn()
self.hand.append(self.cards[self.cardpointer])
self.cardpointer += 1
self.nextbet("River")
def translator(self, handstring):
"Translate the hand string to a list of Card objects."
base = list(handstring)
handobjects = []
while len(base):
# Account for the 10 card being two characters.
ordinal = base.pop(0)
if ordinal == '1':
base.pop(0)
ordinal = '10'
ordinal = self.ordinal.index(ordinal) + 1
suit = self.suits.index(base.pop(0)) + 1
handobjects.append(hand.Card(suit, ordinal))
return handobjects
def distribute(self, lastman=None, side=False):
if lastman:
self.players[lastman].money += self.pot
self.announce("%s takes pot of %d because everyone else folded." %
(lastman, self.pot))
else:
contenders = []
for player, p in self.players.iteritems():
if p.status in ("in", "allin"):
self.announce("%s: %s" % (player, " ".join(p.hand)))
cardstock = self.translator("".join(p.hand) + "".join(self.hand))
(hand_type, besthand, kicker) = hand.find_best_hand(cardstock)
p.besthand = besthand
contenders.append((hand_type, besthand, kicker, player))
winners = hand.find_winners(contenders)
if len(winners) == 1:
winner = winners[0]
p = self.players[winner]
# Decode it because the card object encodes it and so does
# announce.
handstr = (' '.join(str(c) for c in p.besthand)).decode('utf-8')
if not p.winlimit or p.winlimit >= self.pot:
p.money += self.pot
pot_type = ' side' if side else ''
self.announce("%s wins%s pot of %d with a %s" %
(winner, pot_type, self.pot, handstr))
else:
p.money += p.winlimit
p.status = "waiting"
self.pot -= p.winlimit
self.announce("%s wins main pot of %d with a %s" %
(winner, p.winlimit, handstr))
if self.pot > 0:
self.distribute(side=True)
return
else:
self.announce("Split pot ...")
for winner in winners:
p = self.players[winner]
if p.winlimit:
amount = math.floor(p.winlimit / len(winners))
p.money += math.floor(p.winlimit / len(winners))
p.status = "waiting"
self.pot -= p.winlimit
self.announce(winner + " takes " + str(amount))
self.distribute()
return
amount = math.floor(self.pot / len(winners))
for winner in winners:
p = self.players[winner]
p.money += amount
self.pot -= amount
self.announce(winner + " takes " + str(amount))
left = 0
last = None
players_to_pop = []
for player, p in self.players.iteritems():
if p.money == 0:
p.status = "done"
self.announce(player + " is out.")
self.order.remove(player)
players_to_pop.append(player)
else:
left += 1
last = player
for player in players_to_pop:
self.players.pop(player)
if self.burncards:
self.announce("Burn cards were: %s" % " ".join(self.burncards))
if left == 1:
self.announce("Game over, bitches. Bow to " + last)
self.playingholdem = False
else:
self.deal()
|
PHP
|
UTF-8
| 5,052
| 2.5625
| 3
|
[] |
no_license
|
<?php
//
// This software is intended as a prototype for the Défi Info neige Contest.
// Copyright (C) 2014 Heritage Software.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License
//
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/
//
class PushQueueFeeder extends DBInteractor
{
const PushTypeMoveCar = 0;
const PushTypeChangedStatus = 1;
public function resolveNotificationsForPushQueue()
{
$this->notificationsForMoveCar();
$this->notificationsForRoadSideStatusChanged();
}
private function notificationsForMoveCar()
{
$startTime = date("Y/m/d H:i:s", strtotime("+15 minutes"));
$endTime = date("Y/m/d H:i:s", strtotime("+20 minutes"));
$stmtString = "SELECT * FROM RoadSides"
. " WHERE (RoadStatus=2 AND DatePlannedStart > :StartTimePlanned AND DatePlannedStart <= :EndTimePlanned)"
. " OR (RoadStatus=3 AND DateReplannedStart > :StartTimeReplanned AND DateReplannedStart <= :EndTimeReplanned)";
$params = array(":StartTimePlanned" => $startTime,
":EndTimePlanned" => $endTime,
":StartTimeReplanned" => $startTime,
":EndTimeReplanned" => $endTime);
$stmt = $this->dbConnection->prepare($stmtString);
try {
$stmt->execute($params);
} catch (Exception $ex) {
print_r($ex);
die();
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$roadSideID = $row['ID'];
$this->findUsersParkedOnRoadSideAndAddToPushQueueForType($roadSideID, PushQueueFeeder::PushTypeMoveCar);
}
}
private function notificationsForRoadSideStatusChanged()
{
$stmtString = "SELECT * FROM ChangedRoadSidesQueue";
$stmt = $this->dbConnection->prepare($stmtString);
try {
$stmt->execute();
} catch (Exception $ex) {
//print_r($ex);
//die();
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$roadSideID = $row['RoadSideID'];
$this->findUsersParkedOnRoadSideAndAddToPushQueueForType($roadSideID, PushQueueFeeder::PushTypeChangedStatus);
$this->deleteChangedRoadSideFromQueue($roadSideID);
}
}
private function findUsersParkedOnRoadSideAndAddToPushQueueForType($roadSideID,$pushType)
{
$stmtStr = "SELECT UserID From UserParkedRoadSides"
. " WHERE RoadSideID=:RoadSideID";
$params = array(":RoadSideID" => $roadSideID);
$stmt = $this->dbConnection->prepare($stmtStr);
try {
$stmt->execute($params);
} catch (Exception $ex) {
//print_r($ex);
//die();
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$userID = $row['UserID'];
$this->addUserNotificationToPushQueueForType($userID, $roadSideID, $pushType);
}
}
private function addUserNotificationToPushQueueForType($userID,$roadSideID,$pushType)
{
if ($pushType == PushQueueFeeder::PushTypeMoveCar)
{
$message = "Le déneigement de votre rue va commencé.";
}
else if ($pushType == PushQueueFeeder::PushTypeChangedStatus)
{
$message = "Le statut de votre rue a changé.";
}
$stmtStr = "INSERT INTO PushQueue (UserID,Message,Type,AffectedID)"
. " VALUES (:UserID,:Message,:Type,:AffectedID)";
$params = array(":UserID" => $userID,
":Message" => $message,
":Type" => $pushType,
":AffectedID" => $roadSideID);
$stmt = $this->dbConnection->prepare($stmtStr);
try {
$stmt->execute($params);
} catch (Exception $ex) {
//print_r($ex);
//die();
}
}
private function deleteChangedRoadSideFromQueue($roadSideID)
{
$deleteString = "DELETE FROM ChangedRoadSidesQueue"
. " WHERE RoadSideID=:RoadSideID";
$params = array(":RoadSideID" => $roadSideID);
$deleteStatement = $this->dbConnection->prepare($deleteString);
try {
$deleteStatement->execute($params);
} catch (Exception $ex) {
//print_r($ex);
//die();
}
}
}
|
Python
|
UTF-8
| 909
| 3
| 3
|
[
"MIT"
] |
permissive
|
import os
from typing import Optional, Sequence
from objcache import ObjectCache
from tests.utils import ObjectCacheForTesting, delete_object_cache_for_testing, ObjectClassForTesting, GENERATED_PATH
class TestObjectCache:
cache: Optional[ObjectCache] = None
test_cache_path: Sequence[str] = ('a', 'b')
stored_result: ObjectClassForTesting = ObjectClassForTesting('abc')
def setup_method(self):
if not os.path.exists(GENERATED_PATH):
os.makedirs(GENERATED_PATH)
self.cache = ObjectCacheForTesting(self.test_cache_path)
def teardown_method(self):
self.cache = None
delete_object_cache_for_testing()
def test_store_and_get(self):
self.cache.store(self.stored_result)
self.cache = ObjectCacheForTesting(self.test_cache_path) # reload cache
gotten = self.cache.get()
assert gotten == self.stored_result
|
SQL
|
UTF-8
| 856
| 3.5
| 4
|
[] |
no_license
|
CREATE procedure sp_acc_rpt_list_cheque_deposited(@FromDate datetime,
@ToDate datetime)
as
Select Deposits.DepositID,"Deposit ID"=Deposits.FullDocID,
"Deposit Date"= Deposits.DepositDate,
"Account Number"= Bank.Account_Number,
"Bank"=BankMaster.BankName,
"Branch"=BranchMaster.BranchName,
"Amount"=Deposits.Value,
"Staff"=accountsmaster.accountname
From Deposits
Inner Join Bank On Deposits.AccountID = Bank.BankID
Inner Join BankMaster On BankMaster.BankCode=Bank.BankCode
Inner Join BranchMaster On BranchMaster.BranchCode=Bank.BranchCode
Left Outer Join Accountsmaster On Deposits.staffID = accountsmaster.accountid
Where (dbo.stripdatefromtime(Deposits.Depositdate) between @FromDate and @Todate) and TransactionType=5 And IsNULL(Status,0) & 192 =0
Order by Deposits.DepositID,Deposits.DepositDate
|
PHP
|
UTF-8
| 2,876
| 2.515625
| 3
|
[] |
no_license
|
<?php
namespace App\Controller\Backend;
use App\Entity\Genre;
use App\Form\GenreType;
use App\Repository\GenreRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/** @Route("/admin", name="backend_genre_") */
class GenreAdminController extends AbstractController
{
/**
* @Route("/genre", name="list", methods={"GET"})
*/
public function index(GenreRepository $genreRepo)
{
$genres = $genreRepo->findAll();
return $this->render('backend/genre/index.html.twig', [
'page_title' => 'Liste des genres',
'genres' => $genres
]);
}
/**
* @Route("/genre/{id}", name="show", methods={"GET", "POST"}, requirements={"id"="\d+"})
*/
public function show(Genre $genre, Request $request, EntityManagerInterface $em)
{
$form = $this->createForm(GenreType::class, $genre);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($genre);
$em->flush();
$this->addFlash(
'success',
'Les informations du genre ' . $genre->getName() . ' ont été mis à jour !'
);
}
return $this->render('backend/show.html.twig', [
'page_title' => 'Administration - ' . $genre->getName(),
'form' => $form->createView()
]);
}
/**
* @Route("/genre", name="add", methods={"POST"})
*/
public function add(Request $request, EntityManagerInterface $em)
{
$genre = new Genre();
$form = $this->createForm(GenreType::class, $genre);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($genre);
$em->flush();
$this->addFlash(
'success',
'La genre ' . $genre->getName() . ' a été ajouté à la base de données !'
);
return $this->redirectToRoute('backend_genre_list');
}
return $this->render('backend/show.html.twig', [
'page_title' => 'Administration - Ajouter un genre',
'form' => $form->createView()
]);
}
/**
* @Route("/genre/{id}", name="delete", methods={"DELETE"}, requirements={"id"="\d+"})
*/
public function delete(Genre $genre, EntityManagerInterface $em)
{
$em->remove($genre);
$em->flush();
$this->addFlash(
'success',
'Le genre ' . $genre->getName() . ' a été supprimé de la base de données !'
);
return $this->redirectToRoute('backend_genre_list');
}
}
|
C#
|
UTF-8
| 651
| 2.6875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace RockPaperScissors.GameOptions
{
public class Paper : IGameOption
{
public override string ToString() => "Paper";
public int GetSortOrder() => 0;
public int HandleOpposingOption(IGameOption opposingOption)
{
if (opposingOption is Rock) return 1;
else if (opposingOption is Paper) return -1;
else if (opposingOption is Scissors) return 0;
else if (opposingOption is Flamethrower) return 0;
throw new Exception("Undefined behavior for specified type");
}
}
}
|
Java
|
UTF-8
| 746
| 2.09375
| 2
|
[] |
no_license
|
package at.ac.tuwien.dsg.comot.model.type;
public enum ResourceType {
// tosca artifact types
SCRIPT("sh"),
WAR_FILE("war"),
CHEF("chef"),
CHEF_SOLO("chef-solo"),
APT_GET_COMMAND("apt"),
MISC("misc"),
// tosca properties types
OS("os"),
ACTION("action"),
// tosca os properties
INSTANCE_TYPE("instanceType"),
PROVIDER("provider"),
IMAGE("baseImage"),
PACKAGES("packages");
private final String type;
ResourceType(String type) {
this.type = type;
}
@Override
public String toString() {
return type;
}
public static ResourceType fromString(String type) {
if (type != null) {
for (ResourceType b : ResourceType.values()) {
if (type.equalsIgnoreCase(b.type)) {
return b;
}
}
}
return null;
}
}
|
Java
|
UTF-8
| 1,543
| 4.125
| 4
|
[] |
no_license
|
import java.io.*;
class Calculator {
static int add(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
static int multiply(int a, int b) {
return a * b;
}
static int divide(int a, int b) {
return a / b;
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int firstnum, secondnum, result = 0;
char choice;
int flag = 0;
System.out.print("Enter first number: ");
firstnum = Integer.parseInt(br.readLine());
System.out.print("Enter second number: ");
secondnum = Integer.parseInt(br.readLine());
System.out.println("Enter + for addition\nEnter - for subtraction\nEnter * for multipliction\nEnter / for division");
System.out.print("Enter your choice: ");
choice = br.readLine().trim().charAt(0);
if(choice == '+')
result = add(firstnum, secondnum);
else if(choice == '-')
result = subtract(firstnum, secondnum);
else if(choice == '*')
result = multiply(firstnum, secondnum);
else if(choice == '/')
result = divide(firstnum, secondnum);
else {
flag = 1;
System.out.println("Wrong Choice!");
}
if(flag == 0) {
System.out.println(firstnum + " " + choice + " " + secondnum + " = " + result + "\nThank You!");
}
}
}
|
C#
|
UTF-8
| 927
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
using System;
namespace SudokuApplication.Core.Models.PlayerDecisions
{
/// <summary>
/// Represents a player decision where the whole sudoku grid changes.
/// </summary>
public abstract class CompletelyChangeSudokuGridDecision
{
private SudokuRow[] sudokuGridBeforeDecision;
public CompletelyChangeSudokuGridDecision(SudokuRow[] sudokuGrid)
{
this.SudokuGridBeforeDecision = sudokuGrid;
}
public SudokuRow[] SudokuGridBeforeDecision
{
get
{
return this.sudokuGridBeforeDecision;
}
private set
{
if (value == null || value.Length != 9)
{
throw new ArgumentException("SudokuGrid must have nine elements!");
}
this.sudokuGridBeforeDecision = value;
}
}
}
}
|
C
|
UTF-8
| 2,926
| 3.296875
| 3
|
[] |
no_license
|
#include "rogue.h"
#include "utils.h"
void AddPositionYX(int **frontier, int y, int x, int count)
{
frontier[count][0] = y;
frontier[count][1] = x;
}
int CheckPosition(int y, int x)
{
char temp = mvinch(y, x);
return (temp != '.' && temp != '|' && temp != '-');
}
int AddNeighbors(int **frontier, int ***cameFrom, int count, int y, int x)
{
/* North neighbor */
if (y > 0 && cameFrom[y - 1][x][0] < 0 && CheckPosition(y - 1, x))
{
AddPositionYX(frontier, y - 1, x, count);
cameFrom[y - 1][x][0] = y;
cameFrom[y - 1][x][1] = x;
++count;
}
/* South neighbor */
if (y < SCREEN_HEIGHT - 1 && cameFrom[y + 1][x][0] < 0 && CheckPosition(y + 1, x))
{
AddPositionYX(frontier, y + 1, x, count);
cameFrom[y + 1][x][0] = y;
cameFrom[y + 1][x][1] = x;
++count;
}
/* East neighbor */
if (x < SCREEN_WIDTH - 1 && cameFrom[y][x + 1][0] < 0 && CheckPosition(y, x + 1))
{
AddPositionYX(frontier, y, x + 1, count);
cameFrom[y][x + 1][0] = y;
cameFrom[y][x + 1][1] = x;
++count;
}
/* West neighbor */
if (x > 0 && cameFrom[y][x - 1][0] < 0 && CheckPosition(y, x - 1))
{
AddPositionYX(frontier, y, x - 1, count);
cameFrom[y][x - 1][0] = y;
cameFrom[y][x - 1][1] = x;
++count;
}
return count;
}
void Pathfind(Coordinate *end, Coordinate *start)
{
/* Prepare memory for algorithm */
int **frontier = (int **)SafeMalloc(sizeof(int *) * SCREEN_HEIGHT * SCREEN_WIDTH);
int ***cameFrom = (int ***)SafeMalloc(sizeof(int **) * SCREEN_HEIGHT);
int x, y;
int frontierIndex;
int frontierCount;
for (int i = 0; i < SCREEN_HEIGHT * SCREEN_WIDTH; ++i)
{
frontier[i] = (int *)SafeMalloc(sizeof(int) * 2);
}
for (int i = 0; i < SCREEN_HEIGHT; ++i)
{
cameFrom[i] = (int **)SafeMalloc(sizeof(int *) * SCREEN_WIDTH);
for (int j = 0; j < SCREEN_WIDTH; ++j)
{
cameFrom[i][j] = (int *)SafeMalloc(sizeof(int) * 2);
cameFrom[i][j][0] = -1;
cameFrom[i][j][1] = -1;
}
}
/* Intialize starting conditions */
frontierIndex = 0;
frontierCount = 0;
cameFrom[start->y][start->x][0] = -9; /* Flags for origin */
cameFrom[start->y][start->x][1] = -9;
AddPositionYX(frontier, start->y, start->x, frontierCount);
frontierCount++;
/* Search for end location. */
while (frontierIndex < frontierCount)
{
y = frontier[frontierIndex][0];
x = frontier[frontierIndex][1];
++frontierIndex;
if (y == end->y && x == end->x)
{
break;
}
frontierCount = AddNeighbors(frontier, cameFrom, frontierCount, y, x);
}
/* Reverse traverse */
y = end->y;
x = end->x;
while (y != start->y || x != start->x)
{
int tempY = y;
y = cameFrom[tempY][x][0];
x = cameFrom[tempY][x][1];
mvprintw(y, x, "+");
}
}
|
JavaScript
|
UTF-8
| 462
| 3.625
| 4
|
[] |
no_license
|
/*jshint multistr:true */
var text = "Hey, how are you doing? \ My name is Chetana. \ blah blah blah Chetana";
var myName = "Chetana";
var hits = [];
for (var i=0; i<text.length; i++)
{
if (text[i]==="C")
{
for(var j=i; j<(i+myName.length); j++)
{ hits.push(text[j]);
}
}}
if (hits==0)
{console.log("Your name wasn't found!");}
else
{console.log(hits);}
/*Output:
[ 'C', 'h', 'e', 't', 'a', 'n', 'a', 'C', 'h', 'e', 't', 'a', 'n', 'a' ]*/
|
Java
|
UTF-8
| 1,490
| 2.59375
| 3
|
[] |
no_license
|
package application.DAO;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import application.model.DailyStockInExpenses;
import application.util.Database;
import application.util.Date;
public class DailyStockInExpensesDAOImpl implements DailyStockInExpensesDAO {
private static DailyStockInExpensesDAOImpl instance = new DailyStockInExpensesDAOImpl();
@Override
public List<DailyStockInExpenses> getAll() {
// TODO Auto-generated method stub
List<DailyStockInExpenses> list = new LinkedList<DailyStockInExpenses>();
try {
Statement st = Database.getInstance().getDBConn().createStatement();
ResultSet rs = st.executeQuery("SELECT st.stock_in_ID, st.stock_in_date, s.name, st.invoice_num, st.invoice_date, (SELECT SUM(std.quantity*i.price) FROM stock_in_transaction_details std INNER JOIN items i ON std.item_ID = i.item_ID WHERE std.stock_in_ID = st.stock_in_ID) AS amount FROM suppliers s INNER JOIN stock_in_transactions st ON s.supplier_ID = st.supplier_ID");
while(rs.next()) {
list.add(new DailyStockInExpenses(rs.getInt("stock_in_ID"), Date.parse(rs.getString("stock_in_date")), rs.getString("name"), rs.getInt("invoice_num"), Date.parse(rs.getString("invoice_date")), rs.getDouble("amount")));
}
st.close();
rs.close();
} catch(Exception err) {
err.printStackTrace();
}
return list;
}
public static DailyStockInExpensesDAOImpl getInstance() {
return instance;
}
}
|
Shell
|
UTF-8
| 908
| 4.125
| 4
|
[] |
no_license
|
#------------------------------------------------------
# arrayify()
#
# Break list up by a particular delimiter.
#-----------------------------------------------------#
arrayify() {
# Errors.
ERR_NO_ARG="No argument supplied.\n"
# Arguments.
if [ $# -eq 1 ]
then
__STRSRC__="$1"
else
while [ $# -gt 0 ]
do
case "$1" in
# Store command line flag and add flag to error msg.
-d|--delim|--delimiter)
shift
[ ! -z "$1" ] && __STRDELIM__="$1"
[ -z "$1" ] && printf "$ERR_NO_ARG" && exit 1
;;
-t|--this|--source)
shift
__STRSRC__="$1"
;;
esac
shift
done
fi
# printf "%s\n" "printf "$__STRSRC__" \| sed "s/${DELIM:-','}/ /g""
#printf "%s" "$__STRSRC__" | sed "s/${DELIM:-','}/ /g"
# Return the new "array"
[ -z $__STRDELIM__ ] && __STRDELIM__=","
echo "$__STRSRC__" | sed "s/$__STRDELIM__/ /g"
unset __STRDELIM__
unset __STRSRC__
}
|
Markdown
|
UTF-8
| 148,306
| 2.671875
| 3
|
[] |
no_license
|
---
title: "Introdução a análise de dados ambientais em R"
author: "Wilson Souza & Thiago Couto"
date: "2020-11-11"
site: "bookdown::bookdown_site"
always_allow_html: true
documentclass: book
bibliography: [book.bib, packages.bib]
biblio-style: apalike
link-citations: yes
description: "Este é o primeiro livro da série de livros análise de dados ambientais em R"
---
# Prefácio {-}
In this book, we will introduce an interesting
# Sobre os autores {-}
**Wilson Souza**
Possui graduação em Licenciatura em Ciências Biológicas pela Universidade Federal do Rio de Janeirocom dupla diplomação com a Universidade de Coimbra - Portugal, Bacharelado em Biologia Marinha pela Universidade Federal do Rio de Janeiro e Mestrado em Oceanografia Biológica pela Universidade Federal do Rio Grande. Trabalha desde 2012 com ecologia de benthos de substrato incosolidado. Aprendeu a linguagem R durante o mestrado e desde então tem se dedicado a ampliar seus conhecimentos em bioestatística voltado para análises ambientais e ecológicas de organismos bentônicos marinhos.
**Thiago Couto**
<!--chapter:end:index.Rmd-->
# O que é o R?
## Porque usá-lo para análise de dados?
# O RStudio
## O ambiente RStudio
### Script
### Environment
### History
### Console
### Files
### Packages
### Plot
### Help
<!--chapter:end:01-intro.Rmd-->
# Importação, organização e sumarização dos dados
## Primeiro passo: Importando a planilha de dados para o R
Ao se trabalhar com R a primeira pergunta que nos vem a cabeça é: Como inserir meus dados neste ambiente de trabalho? A resposta é simples e também complexa. Pois depende do formato do arquivo de dados que está usando ( \*.csv, \*.xls, \*.xlsx, \*.txt entre outros) e para o mesmo formato existem inúmeras vias possíveis para se fazer isso. Não vou especificar todas as vias, mas as mais comuns utilizando os comandos básicos do R e por meio da interface gráfica do RStudio.
Porém para importar a planilha é necessário definir o ambiente de trabalho no seu computador. Este ambiente é onde sua planilha e seus demais dados a serem trabalhados estão. Podemos realizar isso por via de comandos ou também pela própria interface dos RStudio. Se realizado por via de comandos há diferença entre o sistema operacional (Windows, Linux ou macOS) que estiver utilizando.
setwd(choose.dir("path")) # path é o caminho do diretório escolhido para Windows
setwd("path") # path é o caminho do diretório escolhido para Linux
**[INSERIR PRINTS E EXPLICAÇÃO DA VIA GRÁFICA DE DEFINIÇÃO DO AMBIENTE DE TRABALHO]**
*setwd()* é a função responsável por escolher e definir o diretório a ser trabalhado. Após isso podemos importar a planilha com os dados que utilizaremos.
Imagine a seguinte planilha no formato \*.xlsx, previamente criada em um editor de planilhas, como excel, libreoffice calc e outros.
**[Inserir imagem da planilha]**
### Importando a planilha por meio de comandos:
```r
dados <- read.csv(file = "planilha.csv", header = TRUE, sep = ",")
```
O comando *read.csv()* importou a planilha que está no formato *.csv utilizando os argumentos: file - o qual indica o nome do arquivo a ser importado; header - o qual indica se as colunas da planilha tem nome e sep - o qual indica qual o caracter separador das colunas
O comando acima importou a planilha e o guardou e um objeto chamado dados que será o que nós utilizaremos de agora em diante sempre que quisermos acessar a a planilha no R.
Para importação de arquivos que estão no formato \*.xls ou \*.xlsx é necessário a instalação de algum pacote que permita a realização desse processo. Um pacote que instalaremos aqui é o readxl. Não se preocupe com o processo de instalação de pacotes, neste momento, falaremos sobre ele ao longo do livro, sempre que necessário.
```r
## install.packages("readxl")
library(readxl)
```
```r
dados <- read_excel(path = "planilha.xlsx", col_names = TRUE)
```
O comando *read_excel()* é similar ao *read.csv()* embora seus argumentos sejam diferentes. O argumento path é similar ao file, o argumento col_names é similar ao header. Repare que não temos o argumento sep, pois em um arquivo excel as variáveis são salvas em colunas diferentes.
**[Inserir imagem do processo de importação via interface gráfica]**
**[Inserir imagem do resultado de importação - o arquivo presente no environment]**
## Segundo passo: Ajustando os dados
Uma falha comum de muitos usuários iniciantes é passar para as análises antes de verificar se a planilha está organizada corretamente. Uma forma de previnir isso é conhecendo os seus dados e sabendo o que eles significam. Os dados, geralmente, podem ser: categóricos/qualitativos ou mensuráveis/quantitativos. Quando qualitativos temos de informar que eles consistem em fatores. Para isso vamos executar alguns comandos onde poderemos avaliar se no processo de importação as variáveis presentes na planilha de dados são reconhecidas como esperamos que seja.
Ao executarmos a função *str()* do arquivo dados podemos ver no console o seguinte resultado
```r
str(dados)
```
```
## tibble [40 × 4] (S3: tbl_df/tbl/data.frame)
## $ ano : num [1:40] 2020 2020 2020 2020 2020 2020 2020 2020 2020 2020 ...
## $ local : chr [1:40] "Ambiente 1" "Ambiente 1" "Ambiente 1" "Ambiente 1" ...
## $ comprimento: num [1:40] 10 11 15 12 17 14 19 16 15 12 ...
## $ peso : num [1:40] 20 21 24 24 23 28 26 25 21 22 ...
```
Seu resultado nos informa sobre o tipo de objeto que o arquivo é. Neste caso um objeto do tipo tibble ou data frame.
Também nos e mostrado as variáveis presentes (ano, local, comprimento e peso) e ao lado de cada variável nos é indicado o tipo de variável que ele considerou.
num = numerico, chr = caracter e há outras que não estão indicadas aqui, lógica, inteiro, fator entre outros.
Repare que a variável ano foi indicada como númerico. Variáveis consideradas númericas são aquelas as quais foram mensuradas. Ano não é uma variável possível de ser medida, porém devido ao seu registro ter sido em valores númericos foi assim que ela foi entendida. Portanto temos que transforma-la.
Pensando no que definimos acima com variáveis categóricas e mensuráveis. Ano e local podem ser classificados como variáveis categóricas. A todas as variáveis de nossas planilha consideradas categóricas temos que transformar para fator. Este processo pode ser feito da seguinte forma:
```r
dados$ano <- as.factor(dados$ano)
dados$local <- as.factor(dados$local)
```
Repare que neste processo inserimos o operador **\$** (cifrão). Este é um operador importante em toda linguagem de programação e será bastante utilizado. Ele permite acessar alguma variável dentro de um dado objeto. Pensando no objeto "dados" (nossa planilha), ao colocarmos seu nome e em seguida o operador **\$** podemos acessar as variáveis dentro dele.
Inserimos também a função *as.factor()* que é a responsável por criar uma variável a qual será considerada categórica.
O comando portanto é lido da seguinte forma:
1. "dados\$ano <-" indica que uma variável ano será criada dentro do objeto "dados".
2. "as.factor(dados\$ano)" indica que o objeto criado consistirá na variável ano que está no objeto dados porém considerando-a como factor.
Uma dúvida pode aparece aqui: É o que aconteceu com a variável ano que já existia dentro da planilha dados? Temos duas variáveis ano, agora?
A resposta é que quando criamos um objeto ou variável com o mesmo nome o anterior é substituído. Imagine o seguinte exemplo.
```r
idade <- 30
```
Repare o objeto idade criado no environment.
Agora crie um segundo objeto com o mesmo nome e repare no enviroment.
```r
idade <- 40
```
Reparou que ao criar um segundo objeto de mesmo nome que antes o primeiro foi apagado e substituído pelo segundo? Este é o mesmo processo que ocorreu quando realizamos a função que definiu ano e local como fatores.
Vamos observar novamente a função str() para verificar se ano e locais são fatores
```r
str(dados)
```
```
## tibble [40 × 4] (S3: tbl_df/tbl/data.frame)
## $ ano : Factor w/ 2 levels "2020","2021": 1 1 1 1 1 1 1 1 1 1 ...
## $ local : Factor w/ 2 levels "Ambiente 1","Ambiente 2": 1 1 1 1 1 1 1 1 1 1 ...
## $ comprimento: num [1:40] 10 11 15 12 17 14 19 16 15 12 ...
## $ peso : num [1:40] 20 21 24 24 23 28 26 25 21 22 ...
```
Como pode verificar agora temos 2 variáveis como fatores e 2 númericas. Mais que isso, essa função nos indica ao lado dos fatores um "w/2 levels" que está nos dizendo que essa variável tem 2 niveis. De maneira similar as variáveis númericas indicam um colchetes com os seguintes valores [1:40] que significa que temos 40 valores/observações/linhas.
Observe a planilha dados no environment. Repare que ao lado do nome dados há escrito 40obs. of 4 variables. Isto indica que temos 40 observações e 4 variáveis.
Que tal agora observarmos nossa planilha?
```r
head(dados)
```
```
## # A tibble: 6 x 4
## ano local comprimento peso
## <fct> <fct> <dbl> <dbl>
## 1 2020 Ambiente 1 10 20
## 2 2020 Ambiente 1 11 21
## 3 2020 Ambiente 1 15 24
## 4 2020 Ambiente 1 12 24
## 5 2020 Ambiente 1 17 23
## 6 2020 Ambiente 1 14 28
```
A função *head()* reproduz, no painel do console as primeiras linhas de nossa planilha
```r
View(dados)
```
A função *View()* abre uma aba, ao lado de seu script mostrando todos dados.
Experimente agora só escrever dados e rodar, o que aparece? experimente clicar no nome dados, presente no environment. O que você observou?
Se no primeiro caso você observou a planilha aparecendo no console parabéns você está indo no caminho certo. Se no segundo momento você observou que ao clicar sobre o nome dados ele executou a mesma coisa que a função *View()* você está indo maravilhosamente bem. Continue assim!
Isto não é tudo, mas sim o necessário começarmos a sumarizar os dados de maneira eficiente.
Não se esqueça que antes de trabalharmos nossos dados temos que entender o que eles são e a que eles se referem. A análise de dados sem prévio conhecimento sobre o que eles significam pode levar a interpretações errôneas, caso as análises realizadas indiquem algum resultado, ou então a muita dor de cabeça se algum comando para uma dada análise não funcionar como esperado.
Portanto siga os passos precisamente, não pule etapas para que não haja lacunas em seu conhecimento e busque diversificar a fonte do seu conhecimento. Pois o R é uma linguagem de programação e que como demonstramos até o momento há muitas vias possíveis de escrita para um mesmo resultado e diferentes autores podem escrever de formas diferentes.
## Terceiro passo: Sumarizando os dados graficamente
Já importamos nossa planilha e já a ajustamos. Que tal começarmos a ver a "mágica" acontecer e graficarmos nossso dados.
Muitos gráficos podem ser realizados, mas lembre-se que há toda uma ciência sobre isso.
Pensando nos gráficos mais comuns e úteis para nosso dia-a-dia e que nos permitem sumarizar nossos dados temos os histogramas, gráficos de barras, linhas e boxplots. Vamos então começar com esses e com o objetivo inicial de sumarizar nossos dados.
### HISTOGRAMAS
Para isso vamos aplicar a função *hist()* para visualizar os valores da variável comprimento.
```r
hist(dados$comprimento)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-11-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Repare que um gráfico foi gerado na sua janela lateral, na guia plots.
Perceba também que voltamos a usar o operador *\$* (cifrão).
Nosso gráfico não está aparentemente muito agradável e um pouco sem cor. Vamos inserir alguns argumentos estéticos que melhoram sua visualização e entender como ele sumariza nossos dados.
```r
hist(dados$comprimento,
ylim = c(0, 10),
xlim = c(9, 20),
col = "blue",
main = "Meu Histograma",
xlab = "Comprimento",
ylab = "Frequência absoluta")
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-12-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Temos aqui nosso histograma com alguns argumentos que permitem melhorar sua visualização. Ele nos permite visualizar os dados da variável comprimento e sua frequência de ocorrência.
Podemos observar nele que o valor mínimo observado é 10 e que o máximo é 19 e que as frequências das diferentes classes de comprimento formadas, variam entre 0 e aproximadamente 9. Será que isto que observamos está correto. Vamos ver no tópico a seguir.
Ainda em relação ao histograma podemos ver na função *hist()* que utilizamos diversos argumentos como: xlim, ylim, col, main, xlab e ylab, além de uma função chamada *c()*. Verifique a tabela abaixo para detalhes de cada um desses argumentos e da função *c()*. OBS: Essa função *c()* é muito importante e será utilizada constantemente ao longo de seu trajeto no R.
**[INSERIR TABELA EXPLICANDO OS ARGUMENTOS E A FUNÇÃO CONCATENAR]**
### GRÁFICO DE BARRAS
Se já chegamos até esse ponto vamos exercitar um pouco antes de plotar o gráfico de barras.
Acesse a seguinte planilha: abundância. Vamos inseri-la no R com o nome abundancia. repare que retirei o acento. Sempre que trabalharmos com linguagem de programação evite acentuações, espaços, cedilhas (ç) e atente a maiúsculas e minúsculas, pois isso pode interferir no seu código
Se estiver iniciando o R agora lembre-se de definir o ambiente de trabalho.
```r
abundancia <- read_excel("abundancia.xlsx", col_names = TRUE)
```
Repare que ela está no formato \*.xlsx e apresenta as seguintes variáveis: mes e N. Onde N significa o número de indivíduos observado.
Vamos apenas conferir se está tudo certo com os dados usando a função str().
```r
str(abundancia)
```
```
## tibble [12 × 3] (S3: tbl_df/tbl/data.frame)
## $ mes : num [1:12] 1 2 3 4 5 6 7 8 9 10 ...
## $ N : num [1:12] 100 70 50 30 35 40 60 90 110 150 ...
## $ desvio: num [1:12] 10 12 11 8 8 14 11 9 12 15 ...
```
Vamos converter a variável mês em factor.
```r
abundancia$mes <- as.factor(abundancia$mes)
```
Repare que agora que sabemos os passos a realizar desde a importação dos arquivos tudo ficou muito mais fácil e fluído, e apenas realizamos três etapas, sendo uma delas apenas conferência.
Seguindo para o gráfico de barras a fim de mostrar o número de indivíduos ao longo dos meses temos que:
```r
barplot(abundancia$N)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-16-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Assim como o histograma o simples uso da função sem argumentos gera um gráfico de dificil análise e esteticamente não muito agradavel.
Vamos portanto adicionar alguns argumentos já conhecidos e outros novos que permitirão a melhor análise do gráfico.
```r
barplot(abundancia$N,
ylim = c(0, 200),
xlab = "Mês",
ylab = "Abundância",
names.arg = abundancia$mes,
col = "green")
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-17-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Podemos extrair desse gráfico que a abundância dos indivíduos variam ao longo dos meses com valores mínimos em torno de 50 indivíduos nos meses 4, 5 e 6 e valores máximos em torno de 200 indivíduos no mês 11.
Podemos ver que os argumentos utilizados permitiram referenciar as barras, ajustar o eixo y, adicionar cores e adicionar os nomes dos eixos. Para detalhes sobre os argumentos e funções utilizadas no *barplot()* ver tabela abaixo.
<table class="table" style="width: auto !important; margin-left: auto; margin-right: auto;">
<thead>
<tr>
<th style="text-align:left;"> Argumentos </th>
<th style="text-align:left;"> Características </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;font-weight: bold;"> ylim </td>
<td style="text-align:left;width: 30em; "> Refere-se aos limites do eixo y </td>
</tr>
<tr>
<td style="text-align:left;font-weight: bold;"> c() </td>
<td style="text-align:left;width: 30em; "> É usada quando se deseja unir 2 ou mais objetos em um vetor, no exemplo acima ela foi usada para concatenar os valores 0 e 200, que indicam os limites mínimo e máximo do eixo y </td>
</tr>
<tr>
<td style="text-align:left;font-weight: bold;"> xlab </td>
<td style="text-align:left;width: 30em; "> É usado para dar nome ao eixo x </td>
</tr>
<tr>
<td style="text-align:left;font-weight: bold;"> ylab </td>
<td style="text-align:left;width: 30em; "> É usado para dar nome ao eixo y </td>
</tr>
<tr>
<td style="text-align:left;font-weight: bold;"> names.arg </td>
<td style="text-align:left;width: 30em; "> É usado para definir o nome das categorias/barras representadas no eixo x, neste caso as categorias usadas estão vinculadas a coluna mes do objeto abundancia </td>
</tr>
<tr>
<td style="text-align:left;font-weight: bold;"> col </td>
<td style="text-align:left;width: 30em; "> É usado para definir a cor das barras </td>
</tr>
</tbody>
</table>
**[INSERIR TABELA EXPLICANDO OS ARGUMENTOS E A FUNÇÃO CONCATENAR]**
### GRÁFICO DE LINHAS
Assim como o gráfico de barras podemos desejar fazer um gráfico de linhas para isso podemos utilizar a função *plot()* e continuar trabalhando com os dados de abundância por mês
Contudo para fazer um gráfico de linhas pelo comando básico do R (utilizando a função *plot()*) precisamos indicar que ambos os eixos apresentam variáveis númericas. Portanto teremos que modificar a variável mês de fator para numerica.
Porém não precisamos fazer isso em um comando separado podemos aplicar a função que converte uma variável em númerica dentro da função que plota o gráfico. Vamos visualizar como isso ocorre na prática.
```r
plot(x = as.numeric(abundancia$mes), y = abundancia$N)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-19-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Pronto, na função acima aplicamos a função *plot()* indicando os argumentos x e y que definem quem estará no eixo x e quem estará no eixo y, e para a variável que estará no eixo x (variável mês) adicionamos a função *as.numeric()* a qual a converte em númerico apenas para a execução do plot.
Porém a função *plot()* não realizou um gráfico de linhas como esperado, pois para isso precisamos indica-lo por meio de argumentos. Como demonstraremos a seguir
```r
plot(x = as.numeric(abundancia$mes),
y = abundancia$N,
xlab = "Mês",
ylab = "Abundância",
main = "Meu gráfico de linha",
ylim = c(0, 200),
type = "l",
col = "green",
lwd = 2)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-20-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Repare que um gráfico de linha foi plotado e o resultado deste indica o memso que o gráfico de barras que realizamos acima.
Alguns argumentos novos foram inseridos, os detalhes deles podem ser visualizados na tabela abaixo:
**[INSERIR TABELA EXPLICANDO OS ARGUMENTOS E A FUNÇÃO CONCATENAR]**
### BOXPLOT
Vamos voltar a nossa primeira planilha (dados) e executar um gráfico do tipo boxplot e ver o que ele nos informa.
```r
boxplot(formula = dados$comprimento ~ dados$ano)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-21-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Repare que a escrita para esse gráfico é ligeiramente diferente. Ele usa a função *boxplot()*, um argumento chamado formula onde nele inserimos a variável independente (variável do eixo X) e a variável dependente (variável do eixo Y). Entre ambas as variáveis é possível ver o caracter "~" (til). A forma de ler essa escrita é a seguinte: Realize um boxplot da variável comprimento da planilha dados em função da variável ano da planilha dados. A variável til é lida como ("em função de")
Vamos adicionar alguns argumentos que permitem deixar o gráfico mais apresentável.
```r
boxplot(formula = dados$comprimento ~ dados$ano,
col = c("blue", "green"),
xlab = "Ano",
ylab = "Comprimento",
main = "Meu Boxplot")
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-22-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Repare que não adicionamos nenhum argumento ou função diferente do que já fizemos anteriormente. Ou seja, uma vez conhecendo a função, os argumentos por vezes se repetem.
O boxplot porém nos fornece algumas informações extras em relação ao resumo dos dados. Podemos extrair dele dados como média, mediana (segundo quartil), primeiro e terceiro quartil, assim como máximos e mínimos da variável dependente.
As linhas de cada box (caixa) que se referem a cada um dos anos representam, em suas extremidades os valores máximos e mínimos de comprimento de cada ano. A topo e a base de cada "box" indicam o primeiro e terceiro quartil, respectivamente, do comprimento. A linha no interior da caixa indica a mediana (segundo quartil) e a metade do box (não indicada graficamente) indica a média.
Podemos por meio desse gráfico então ter uma ideia do que os dados indicam quanto as medidas de tendência central e algumas medidas de dispersão em relação as categorias definidas.
## Quarto passo: Sumarizando os dados numericamente
Temos visto, até este ponto de maneira geral, como resumir os dados graficamente.
Porém muitas vezes precisamos demonstrar numericamente quais são os valores que resumem dos dados. Estes valores consistem nas medidas de tendência central e nas suas medidas de dispersão.
O R permite, de maneira simples, sumarizar os dados por meio da seguinte função.
```r
summary(dados)
```
```
## ano local comprimento peso
## 2020:20 Ambiente 1:15 Min. :10.00 Min. :18.00
## 2021:20 Ambiente 2:25 1st Qu.:12.00 1st Qu.:20.00
## Median :14.00 Median :21.50
## Mean :13.97 Mean :21.73
## 3rd Qu.:15.00 3rd Qu.:23.00
## Max. :19.00 Max. :28.00
```
```r
summary(abundancia)
```
```
## mes N desvio
## 1 :1 Min. : 30.00 Min. : 8.00
## 2 :1 1st Qu.: 47.50 1st Qu.: 9.75
## 3 :1 Median : 80.00 Median :11.50
## 4 :1 Mean : 88.75 Mean :11.75
## 5 :1 3rd Qu.:120.00 3rd Qu.:14.00
## 6 :1 Max. :180.00 Max. :17.00
## (Other):6
```
Repare que summary(dados) ou summary(abundancia) o R nos informou as variáveis presentes nestas planilhas e quando fator indicou quais são e quantos de cada existem e quando númerico nos retornou valores como média, mediana, mínimo, máximo, primeiro e terceiro quartis.
As medidas de tendência central mais conhecidas e aplicadas são média, mediana e moda.
Para obtenção da média precisamos somar todos os valores e dividir pela quantidade de valores ou no R podemos fazer isso de maneira mais simples por meio da função *mean()*:
```r
mean(dados$comprimento)
```
```
## [1] 13.975
```
Como podemos verificar a média do comprimento na planilha dados é de 13.975.
De maneira similar podemos calcular a mediana, que consiste no valor central da distribuição de valores de uma dada variável. Podemos visualiza-la por meio da função *median()*.
```r
median(dados$comprimento)
```
```
## [1] 14
```
Como podemos verificar o valor que se encontra no meio da distribuição de valores da variável comprimento é 14.
As medidas de dispersão são utilizadas para demonstrar a variabilidade dos dados...[explicar mais]
Os limites inferior e superior de uma dada variável quantitativa são denominados mínimo e máximo e podem ser obtidos por meio das funções que calculam o mínimo e máximo. Apesar de seu resultado aparecer na função *summary()*, que aplicamos anteriormente, podemos obte-la separadamente para uma variável especifica. Vamos conferi-la com o conjunto de dados que utilizamos anteriormente.
```r
min(dados$comprimento)
```
```
## [1] 10
```
```r
max(dados$comprimento)
```
```
## [1] 19
```
Uma outra forma de obter os valores máximo e mínimo é usando a função *range()*.
```r
range(dados$comprimento)
```
```
## [1] 10 19
```
Como puderam verificar utilizando a função *min()* e *max()* ou *range()* obtemos os valores mínimo e máximo da variável comprimento. Repare que usamos o operador cifrão (**\$**) após o nome do conjunto de dados. Como você aprendeu anteriormente ele permite acessar as variáveis que estão dentro do objeto dados.
Com os valores mínimo e máximo podemos obter nossa primeira medida de dispersão dos dados. A amplitude que consiste na diferença entre os valores máximo e mínimo de nossa amostra. Está é a forma mais simples de verificar a dispersão de seus dados. Ela apresenta suas falhas, porém tem a vantagem de fornecer a distância na qual seus dados variam na mesma unidade em que eles estão.
A amplitude é utilizada para dados quantitativos, descrever a variabilidade de uma amostra, porém não para inferência estatística.
```r
max(dados$comprimento) - min(dados$comprimento)
```
```
## [1] 9
```
Como podemos ver, ao calcular a diferença entre o máximo e mínimo da mesma variável obtemos a diferença entre elas e esse valor consiste na amplitude desta variável.
Uma outra forma de realizar esta mesma operação é utilizando a função *diff()* que calcula a diferença. Quando inserimos a função *range()* dentro da função *diff()* o R nos retorna o resultado da diferença dos valores obtidos pela função *range()*.
```r
diff(range(dados$comprimento))
```
```
## [1] 9
```
O desvio padrão. Esta é uma das medidas de variação mais importantes que iremos realizar. Ele mede a distância dos valores observados em relação a sua média.
Durante a coleta de dados em estudos ambientais, o que normalmente é extraído de informação é uma fração de um todo, ou seja, uma amostra de uma população. Portanto quando se deseja avaliar o desvio padrão, assim como outras medidas de variabilidade, devemos considerar se estamos avaliando uma amostra ou toda a população. Se uma amostra é considerada o nos referimos a ela como desvio padrão amostral e a representamos por (s) se toda a população é considerada nos referimos a ela como desvio padrão populacional e a representamos por (sigma).
Neste livro vamos abordar e considerar o desvio padrão como o desvio padrão amostral.
Para calcular o desvio padrão amostral utilizamos a seguinte formula abaixo:
**[INSERIR FORMULA]**
Podemos calcular o desvio padrão a partir de suas partes, considerando sua formula ou a partir de uma função pré-existente no R. Vamos conferir as duas formas.
Para facilitar o entendimento do código vamos começar criando os seguintes objetos:
```r
comp <- dados$comprimento
comp.media <- mean(dados$comprimento)
N <- length(dados$comprimento)
comp
```
```
## [1] 10 11 15 12 17 14 19 16 15 12 14 15 12 12 14 13 12 11 14 14 13 12 11 15 12
## [26] 14 13 12 11 15 15 17 16 17 15 16 15 16 15 17
```
```r
comp.media
```
```
## [1] 13.975
```
```r
N
```
```
## [1] 40
```
* "comp" contêm os dados da variável comprimento presente na planilha dados
* "comp.media" contêm um dado que consiste na média da variável comprimento
* "N" representa a quantidade de observações presentes na variável comprimento. Repare que aqui utilizamos uma nova função chamada length() a qual contabiliza o número de observações de objeto.
```r
sqrt((sum((comp - comp.media)^2)) / (N - 1))
```
```
## [1] 2.106005
```
```r
sd(dados$comprimento)
```
```
## [1] 2.106005
```
```r
sd(comp)
```
```
## [1] 2.106005
```
Destas três formas cabe explicarmos a primeira. Nela vamos entender como lemos uma função. O ideal é ler de dentro para fora. Como uma equação matemática. Mas não se assuste é mais fácil do que parece. Começamos a leitura da seguinte forma:
1. (comp - comp.media): Realize a diferença dos valores presentes em comp de sua média.
2. ((comp - comp.media)^2): Eleve esses valores, obtidos da diferença, ao quadrado.
3. (sum((comp - comp.media)^2)): Soma todos os valores, obtidos pela diferença elevados ao quadrado.
4. (sum((comp - comp.media)^2)) / (N - 1): Divida a soma dos valores da diferença elevado ao quadrado pelo número de observações menos 1.
5. sqrt((sum((comp - comp.media)^2)) / (N - 1)): Extraia a raíz quadrada da divisão da soma dos valores da diferença elevado ao quadrado pelo número de observações menos 1.
Repare que a leitura segue a ordem dos passos do cálculo que seria feito a mão usando a equação apresentada acima.
Mas caso não queira escrever a formula o R fornece a função *sd()* que pode ser aplicada a uma variável dentro de uma planilha de dados ou a um vetor que contenha um conjunto de observações do seu interesse.
Pronto, agora enetendemos como ler um código que apresenta funções dentro de funções e entendemos como realizar o desvio padrão de três formas distintas (existem diversas outras formas) no R. Agora você já pode escolher a que mais lhe agrada. Qual você prefere? Bem, essa é uma escolha sua.
Assim como o desvio padrão temos também a variância. A mais importante medida de variabilidade dos dados. Há todo um conjunto espécial de análise de dados voltado para ela. Mas como poderão ver, ela não difere muito do desvio padrão, apenas pelo fato de que consiste no seu valor elevado ao quadrado, no entanto a variância amostral é representada por s² enquanto que o desvio padrão é representado por s.
Partindo dessa ideia a variância é nada mais que estimar o desvio padrão e eleva-lo ao quadrado. Vamos observar o seu resultado utilizando sua formula e a função predefinida pelo R.
```r
(sum((comp - comp.media)^2)) / (N - 1)
```
```
## [1] 4.435256
```
```r
sd(dados$comprimento)^2
```
```
## [1] 4.435256
```
```r
var(dados$comprimento)
```
```
## [1] 4.435256
```
Pronto aqui estão 3 maneiras de encontrar a variância de seus dados. A primeira é similar ao que realizamos anteriormente para o desvio padrão porém sem a raíz quadrada. A segunda consiste em elevar ao quadrado o resultado do desvio padrão e a terceira é aplicando a função *var()* a variável comprimento presente na planilha dados.
Difícil? Espero que não.
Mas vamos entender o significado do desvio padrão e variância. Pois ambos estão intimamente relacionados.
Como conversamos anteriormente as medidas de tendência central nos informam sobre a distância das observações de uma dada variável em relação a sua medida de tendência central (normalmente a média). Se somarmos a diferença das observações de uma dada variável de sua média obteremos o valor de 0 (tabela abaixo). Contudo se elevarmos cada diferença ao quadrado e dividirmos pela quantidade de observações menos 1 (subtrai-se 1 das observações porque estamos trabalhando com amostras) teremos a média das distâncias das observações ao quadrado (variância). Porém algumas vezes esse valor pode não ser fácil de interpretar e não reflete diretamente a unidade da variável mensurada. Com isso uma forma mais intuitiva utilizada para interpretar a dispersão dos dados em relação a sua média consiste no desvio padrão, pois como vimos este consiste na raiz quadrada da variância, ao fazermos isso nos obtemos a distância média das observações em relação a sua média na mesma unidade de medida em que se encontram.
O coeficiente de variação é outra medida importante e de fácil interpretação sobre a variabilidade dos dados. Este consiste em representar o desvio padrão em termos percentuais. Este é simples de calcular e intuitivo de interpretar.
Não há, até o momento, uma função no pacote básico do R que o calcule. Vamos calcular e ver o que ele quer dizer.
```r
sd(dados$comprimento)/mean(dados$comprimento)*100
```
```
## [1] 15.0698
```
Pronto, calculamos o coeficiente de variação da variável comprimento. O desvio padrão de uma dada observação apresenta a mesma unidade de suas observações, correto? Então podemos dividi-lo pela média das próprias observações e multiplicar por 100 com isso temos que a variável comprimento tem uma variação em torno da média de ±15,07%.
Com isso verificamos as principais medidas de tendência central e dispersão. Mas fica uma questão, como incorpora-las aos gráficos para que assim possamos resumir os dados graficamente de maneira mais completa.
Vamos em frente! Vamos utilizar nossa planilha dados e verificar a média do comprimento e do peso por ano e por ambiente e incorporar em cada um dos gráficos seus respectivos desvios padrões.
Neste caso vamos primeiro precisar organizar os dados que queremos plotar. Como desejamos plotar a média do comprimento por ano e ambiente, vamos primeiro construir passo a passo uma tabela que apresente 4 colunas a primeira com o ano, a segunda com ambiente, a terceira com a média do comprimento e a última com o desvio padrão.
```r
dados.2 <- split(x = dados, f = dados$ano)
ano.2020 <- dados.2$`2020`
ano.2021 <- dados.2$`2021`
ano.2020.local <- split(x = ano.2020, f = ano.2020$local)
ano.2021.local <- split(x = ano.2021, f = ano.2021$local)
ano.2020.local.1 <- ano.2020.local$`Ambiente 1`
ano.2020.local.2 <- ano.2020.local$`Ambiente 2`
ano.2021.local.1 <- ano.2021.local$`Ambiente 1`
ano.2021.local.2 <- ano.2021.local$`Ambiente 2`
```
Pronto! Dividimos os nosso dados de acordo com os fatores que desejamos. Agora vamos obter as métricas média e desvio padrão.
```r
ano.2020.local.1.comp.media <- mean(ano.2020.local.1$comprimento)
ano.2020.local.1.comp.dp <- sd(ano.2020.local.1$comprimento)
ano.2020.local.2.comp.media <- mean(ano.2020.local.2$comprimento)
ano.2020.local.2.comp.dp <- sd(ano.2020.local.2$comprimento)
ano.2021.local.1.comp.media <- mean(ano.2021.local.1$comprimento)
ano.2021.local.1.comp.dp <- sd(ano.2021.local.1$comprimento)
ano.2021.local.2.comp.media <- mean(ano.2021.local.2$comprimento)
ano.2021.local.2.comp.dp <- sd(ano.2021.local.2$comprimento)
```
Pronto! Média e desvio padrão do comprimento calculado para cada ano e local. Agora vamos unir esses resultados em uma data frame
```r
dados.media <- c(ano.2020.local.1.comp.media,
ano.2020.local.2.comp.media,
ano.2021.local.1.comp.media,
ano.2021.local.2.comp.media)
dados.dp <- c(ano.2020.local.1.comp.dp,
ano.2020.local.2.comp.dp,
ano.2021.local.1.comp.dp,
ano.2021.local.2.comp.dp)
```
Vamos criar as variáveis categoricas e ano e local para adicionar a esse dados
```r
ano <- c("2020", "2020", "2021", "2021")
local <- c("Ambiente 1", "Ambiente 2", "Ambiente 1", "Ambiente 2")
dados.3 <- as.data.frame(cbind(ano, local, dados.media, dados.dp))
str(dados.3)
```
```
## 'data.frame': 4 obs. of 4 variables:
## $ ano : chr "2020" "2020" "2021" "2021"
## $ local : chr "Ambiente 1" "Ambiente 2" "Ambiente 1" "Ambiente 2"
## $ dados.media: chr "14.1" "13.1" "13" "14.8"
## $ dados.dp : chr "2.84604989415154" "1.28668393770792" "1.58113883008419" "1.93464651625488"
```
```r
dados.3$ano <- as.factor(dados.3$ano)
dados.3$local <- as.factor(dados.3$local)
dados.3$dados.media <- as.numeric(dados.3$dados.media)
dados.3$dados.dp <- as.numeric(dados.3$dados.dp)
```
```r
dados.3
```
```
## ano local dados.media dados.dp
## 1 2020 Ambiente 1 14.1 2.846050
## 2 2020 Ambiente 2 13.1 1.286684
## 3 2021 Ambiente 1 13.0 1.581139
## 4 2021 Ambiente 2 14.8 1.934647
```
Repare que durante todo este processo utilizamos três funções que não haviamos utilizado antes. As funções *split()* que divide a planilha de acordo com as categorias presentes na variável que definimos, *as.data.frame()* que faz com que um conjunto de objetos sejam convertidos em data frame e *cbind()* o qual une objetos como colunas. Essas funções também serão comumente utilizadas durante seus passos iniciais no R.
Pronto! depois de alguns passos conseguimos construir nossa nova tabela com os dados resumidos.
É um processo longo porém necessário para se acostumar com o ambiente de trabalho e a linguagem que o R usa. Há caminhos mais rápidos e tão eficientes quanto. Que se tornam uteis quando lidamos com muitas categorias dentro de uma variável. Contudo para isso é necessário a instalação de algum pacote (Há vários pacotes que apresentam funções que realizam este processo). Vamos utilizar um exemplo começando pela instalação do pacote chamado Rmisc.
O comando abaixo realiza a instalação desse pacote. Conforme já fizemos com o pacote readxl
```r
## install.packages("Rmisc")
```
Após instalado vamos carrega-lo pelo comando a seguir. Conforme já fizemos com o pacote readxl
```r
library(Rmisc)
```
Agora vamos conhecer a função *summarySE()* deste pacote o qual realiza os passos que fizemos acima e ainda apresenta outros resultados. Mas iremos focar na média e desvio padrão.
```r
resultado <- summarySE(data = dados,
measurevar = "comprimento",
groupvars = c("ano", "local"))
resultado
```
```
## ano local N comprimento sd se ci
## 1 2020 Ambiente 1 10 14.1 2.846050 0.9000000 2.0359414
## 2 2020 Ambiente 2 10 13.1 1.286684 0.4068852 0.9204382
## 3 2021 Ambiente 1 5 13.0 1.581139 0.7071068 1.9632432
## 4 2021 Ambiente 2 15 14.8 1.934647 0.4995236 1.0713715
```
Repare que a função *summarySE()* apresenta, basicamente, 3 argumentos, "data" que pede que se insira a planilha a ser utilizada, "measurevar" o qual pede a variável quantitativa que será sumarizada e "groupvars" o qual pede as variáveis categoricas segundo as quais a variável mensurável será agrupada. Observe também que para esta função as variáveis devem ser colocadas entre aspas.
Pronto com a função acima realizamos os mesmos passos que antes e guardamos o resultado dentro de um objeto chamado resultado. Repare que essa função nos resumiu os dados de comprimento de acordo com as duas variáveis categóricas que indicamos: ano e local. Em seu resumo ele nos forneceu, na seguinte ordem, a coluna ano, local, N (número de observações), comprimento (média do comprimento), sd (desvio padrão), se (erro padrão), ci (intervalo de confiança de 95%).
Agora vamos usar o objeto resultado para desenvolver o gráfico de barras com o erro padrão. Mas lembre-se o objeto dados.3 também pode ser utilizado.
```r
grafico <- barplot(formula = comprimento ~ ano + local,
data = resultado,
beside = TRUE,
col = c("red", "blue"),
ylim = c(0, 30),
ylab = "Comprimento médio (cm)",
legend.text = TRUE)
arrows(x0 = grafico,
y0 = resultado$comprimento + resultado$sd,
y1 = resultado$comprimento - resultado$sd,
code = 3,
angle = 90,
length = 0.05)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-42-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Note que nesta função *barplot()* utilizamos algumas mudanças em relação ao que fizemos anteriormente, como os argumentos "formula" o qual indica a variável resposta em função das variáveis categóricas o qual será plotado (Caso altere a ordem ano + local para local + ano a ordem do gráfico também será alterado. Teste você mesmo, veja o acontece). Neste caso como temos mais de uma variável categórica adicionamos um argumento novo chamado "legend.text" o qual adiciona uma legenda ao gráfico.
Para adicionar os desvios no gráfico de barras precisamos criar um objeto que armazena o gráfico, por isso adicionamos a função barplot() a um objeto denominado grafico.
Agora que construimos o gráfico, a função *arrows()* é responsável por adicionar as barras de desvios no gráfico. Ela apresenta alguns argumentos diferentes do que já vimos em outros gráficos. "x0" indica o objeto onde o gráfico foi armazenado; "y0" e "y1" são escritos como uma operação matemática onde devemos incluir o valor da média + e - a coluna onde está a variável referente ao desvio; "code" determina o tipo de seta que será plotada; "angle" é o ângulo da haste da barra até a ponta; "length" é o comprimento das bordas da barra.
Terminamos de construir e entender os componentes do nosso primeiro gráfico com suas barras de erro.
O entendimento principal para construção desse gráfico consiste em entender como organizar os dados a serem graficados. Ao se usar a função *barplot()* para construção do gráfico de barras com os desvios, devemos ter uma ou mais colunas com as categorias, outra com os valores que desejamos e outra com os valores dos desvios.
Vamos realizar um segundo tipo de gráfico onde temos apenas uma variável categórica e seus respectivos desvios. Para isso utilizaremos nosso conjunto de dados abundancia (lembre-se que mês é uma variável categórica e deve ser identificada como fator).
Neste conjunto de dados não precisamos reorganizar os dados pois eles já se encontram organizados e já temos os valores dos desvios.
```r
grafico <- barplot(abundancia$N,
ylim = c(0, 200),
xlab = "Mês",
ylab = "Abundância",
names.arg = abundancia$mes,
col = "green")
arrows(x0 = grafico,
y0 = abundancia$N + abundancia$desvio,
y1 = abundancia$N - abundancia$desvio,
code = 3,
angle = 90,
length = 0.05)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-43-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Repare que é quase a mesma coisa que fizemos antes. A única diferença é que guardamos o gráfico gerado em um objeto chamado grafico.
Pronto, gráfico realizado.
Durante nosso percurso neste livro realizaremos muito mais gráficos aliados as análises estatísticas básicas mais comumente utilizadas. Não se assuste com a quantidade de etapas e funções e argumentos e nomes, eles irão se repetir tantas e tantas vezes daqui em diante que você não esquecerá. O aprendizado do R é exponencial e ele lhe permitirá entender como nunca o mundo da análise de dados.
**Resumo das etapas até o presente momento:**
**importar planinha >> conferir as variáveis >> sumarizar numericamente os dados >> sumarizar graficamente os dados**
**[TEMOS QUE FAZER UM ESQUEMA DESSAS ETAPAS]**
<!--chapter:end:02-literature.Rmd-->
# Qui-quadrado (χ²)
Em alguns momentos podemos estar trabalhando com variáveis categóricas e lidarmos com perguntas sobre estas variáveis e portanto pode ser necessário avaliarmos se a frequência das observações de uma dada variável categórica se ajusta ao que se é esperado (χ² para ajuste de frequências) ou se as proporções das observações de duas ou mais variáveis categóricas são independentes uma da outra (χ² para independência).
Portanto, como podemos perceber, para este teste iremos precisar apenas de uma variável (se estivermos avaliando o ajuste de frequências) ou duas variáveis (se avaliarmos a independência) e estas devem ser categóricas. Como aprendemos anteriormente as variáveis categóricas devem ser classificadas como factor (pela função *as.factor()*) no R.
Vamos conferir em detalhes e com exemplos como realizar estas duas análises no R. Mas antes vamos sumarizar suas principais características.
**[FAZER UMA TABELA COM AS CARACTERÍSTICAS DOS TESTES ABAIXO]**
**χ² para ajuste de frequências**
**Tipo e quantidade de variáveis: Utiliza apenas uma variável categórica;**
**H0: O número de observações em cada grupo da variável categórica é igual ao predito pela teoria;**
**Fórmula: X²=somatório(Ob-Es)²/Es;**
**OBS: Se há apenas 2 categorias, dentro da variável, não há a necessidade de post-hoc e expressa-la graficamente;**
**[FAZER UMA TABELA COM AS CARACTERÍSTICAS DOS TESTES ACIMA]**
## χ² para ajuste de frequências
Imagine o seguinte exemplo: Você foi a praia e verificou uma enorme quantidade de produtos plásticos, esquecidos pelas pessoas. Após um tempo de observação você percebeu que haviam tanto sacolas quanto linhas de pesca e levantou a seguinte pergunta: Será que se coletarmos estes plásticos na praia e o categorizarmos eles apresentarão quantidades similares? A partir desta pergunta a seguinte hipótese nula (H0) é naturalmente construída: Não há diferenças entre estes dois tipos de plásticos (linha de pesca e sacolas). O χ² objetiva responder a essa pergunta e fornecer subsídio estatístico para corroborar ou refutar essa hipótese.
Após a observação, coleta (há muitas formas de coleta, não vamos detalhar elas neste momento), classificação e contagem dos fragmentos plásticos os seguintes valores foram observados: 520 sacolas plásticas e 470 fragmentos de linhas de pesca. Considerando que deveriamos encontrar quantidades similares de ambos os tipos de plásticos. Ou seja, do total de fragmentos coletados (520 para sacolas e 470 para linhas pesca) cada um deles contribuem com 50% (percentuais iguais) do total coletado?
Vamos começar criando 2 vetores onde o primeiro corresponde aos valores observados e o segundo as proporções esperadas para cada valor.
```r
observados <- c(520, 470)
esperados <- c(0.5, 0.5)
observados
```
```
## [1] 520 470
```
```r
esperados
```
```
## [1] 0.5 0.5
```
Note que criamos o vetor "observados" e o vetor "esperados". O primeiro corresponde ao que coletamos e o segundo as proporções que esperamos de ambos.
Para realizar o teste do χ² para ajuste de frequências, vamos utilizar a função *chisq.test()*.
```r
chisq.test(x = observados, p = esperados)
```
```
##
## Chi-squared test for given probabilities
##
## data: observados
## X-squared = 2.5253, df = 1, p-value = 0.112
```
Para este teste temos que esta função utiliza 2 argumentos. x: no qual inserimos o vetor númerico que contém os valores referentes a quantidade da variável nominal que contabilizamos e p: no qual inserimos o vetor númerico que contem as proporções esperadas associado a cada grupo da categoria avaliada.
Note que o resultado indica o teste realizado, o nome do vetor que contém os dados e na terceira linha ele apresenta o resultado como valor do teste do χ²,o grau de liberdade (df do inglês degrees of freedom) e o valor de probabilidade associado (do inglês p-value).
Uma característica do χ² é que quanto mais similares forem os valores observados menor será o valor do χ² mas nunca menor que 0 e com o p-value máximo igual a 1 e quanto mais dissimilares forem os valores observados maior será o χ² (tendendo a infinito) e menor será o p-value (tendendo a 0)
Com isso podemos observar que o χ² varia entre (0 e + infinito) enquanto que o p-value varia entre (0 e 1) com uma relação inversa entre eles. Quanto maior o χ² menor o p-value e quanto menor o χ² maior o p-value. Experimente você altere os valores de maneira que eles sejam exatamente os mesmos e de que eles difiram bastante, repare nos valores de χ² e p-value.
Por convenção indicamos que um teste estatístico que apresenta p-value < 0,05 indica diferenças significativas entre os valores observados. Dessa forma, assumindo essa convenção, podemos concluir que a quantidade de sacolas não difere da quantidade de linhas de pesca. Portanto aceitamos a hipótese nula.
Não é comum representar o resultado deste teste graficamente apenas como valor mas se mesmo assim quiser representa-lo utilize um gráfico de barras.
Vamos verificar outros exemplos e avaliar suas hipóteses nulas.
Imagine um segundo exemplo. 300 flores foram fotografadas e classificadas pela cor e ao final foi obtido um total de 170 flores vermelhas e 130 flores verdes. Ao ler alguns trabalhos e analisar os resultados observados para outra região foi levantada a hipótese de que 70% das flores seriam vermelhas e 30% seriam verdes. Com base nesses dados podemos perguntar: As flores fotografadas confirmam os resultados esperados?
Vamos avaliar este caso, conforme fizemos acima.
```r
flores.observadas <- c(170, 130)
flores.esperadas <- c(0.7, 0.3)
```
Observe que igual nosso exemplo anterior criamos um vetor que engloba os valores observados e outro com os valores esperados. Note que a diferença está nos valores esperados, onde alteramos a proporção, que não é mais de 50% para cada, mas sim de 70% para um e 30% para outro, porém expressos em proporção. Perceba, também, que os valores seguem a ordem em que foram inseridos, portanto o primeiro valor observado inserido corresponde ao primeiro valor esperado inserido e assim por diante.
Conduzindo a análise temos o seguinte resultado
```r
chisq.test(x = flores.observadas, p = flores.esperadas)
```
```
##
## Chi-squared test for given probabilities
##
## data: flores.observadas
## X-squared = 25.397, df = 1, p-value = 4.667e-07
```
Perceba que o valor do χ² aumentou em relação ao exemplo anterior e o p-value diminuiu para um valor bem próximo a 0. Este resultado indica que os valores observados de flores vermelhas e verdes não apresentam as proporções que se esperam de 70% e 30%. Portanto refutamos a hipótese nula de que elas se encontram nas proporções esperadas. Diversas questões podem explicar a ausência dessa relação hipotetizada, como: a amostragem não foi realizada corretamente; há diferença quanto a espécie de flor, há diferença nas proporções em relação ao ambiente, a estação do ano ou a alguma outra característica ambiental entre outras hipóteses.
Vamos seguir em frente e olhar para um outro exemplo. Suponha que foram coletados 60 indivíduos de siri em um estuário. Eles foram classificados em relação ao sexo e foram obtidos 41 fêmeas e 19 machos. Espera-se que a razão sexual desta espécie seja de 1:1 (50% para cada sexo). Os indivíduos amostrados confirmam o que é esperado?
```r
siris.observados <- c(1380, 1280)
siris.esperados <- c(0.5, 0.5)
chisq.test(x = siris.observados, p = siris.esperados)
```
```
##
## Chi-squared test for given probabilities
##
## data: siris.observados
## X-squared = 3.7594, df = 1, p-value = 0.05251
```
Com este caso podemos observar que o valor do χ² indicou um p-value próximo a 0,05, indicando que temos de ter cuidado com as afirmações relativas a hipótese testada. Contudo, como o valor é >0,5 podemos corroborar a hipotese nula e dizer que os valores observados para fêmeas e machos encontram-se dentro da proporção esperada de 1:1.
E se ao invês de 2 grupos tivessemos 3 ou mais. Como realizariamos o χ²? Vamos ver com um exemplo.
Imagine que você foi a uma floresta e classificou as árvores em altas, médias e baixas e contabilizou 55, 31 e 27 respectivamente. De acordo com a literatura é esperado que as proporções de árvores altas, médias e baixas seja de 1:1:1. Vamos analisar e verificar se podemos afirmar que o observado corrobora o esperado.
```r
arvores.observadas <- c(55, 31, 27)
arvores.esperadas <- c(1/3, 1/3, 1/3)
chisq.test(x = arvores.observadas, p = arvores.esperadas)
```
```
##
## Chi-squared test for given probabilities
##
## data: arvores.observadas
## X-squared = 12.177, df = 2, p-value = 0.002269
```
Neste exemplo podemos perceber que a análise é igual a todos os casos anteriores, a diferença é que adicionamos um grupo a mais e consequentemente um valor a mais. Devido a essa mudança tivemos que dividir as probabilidades (objeto arvores.esperadas) em 3 valores e de igual probabilidade, já que o hipotetizado consistia em proporções iguais para os três grupos definidos. De acordo com o resultado obtido podemos perceber que o que foi observado não corrobora o esperado.
Vamos observar quais seriam as quantidades de árvores esperadas de acordo com as quantidades que observamos e as proporções que esperamos.
Para isso precisamos primeiramente inserir o resultado em um objeto e a seguir acessar os componentes desse objeto pelo operador matemático **\$** (cifrão), seguido pelo objeto "expected" criado pela função *chisq.test()*.
```r
resultado <- chisq.test(x = arvores.observadas, p = arvores.esperadas)
resultado$expected
```
```
## [1] 37.66667 37.66667 37.66667
```
Pronto.
Os exemplos acima tratam de avaliar o χ² em variáveis que apresentam dois ou mais grupos. Em caso onde o grau de liberdade é 1 (dois grupos) e o número de observações é considerado baixo é sugerido a aplicação da correção de Yates. Quando o número de observações é elevado ela não distorce o resultado. O risco de se usar o χ² sem a correção de Yates consiste em inflar o valor de χ² e portanto diminuir o p-value o que nos levaria ao risco de rejeitarmos a hipótese nula quando ela é verdadeira (erro tipo I).
A função do χ² no pacote base do R não realiza essa correção para este teste, apenas para o próximo caso que iremos tratar (χ² para independência). Contudo ele oferece outro método para avaliação deste teste que consiste na simulação de Monte Carlo. Não entraremos em detalhes de como funciona este teste, mas o que alertamos é que se o número de observações utilizado é considerado baixo correções devem ser aplicada. Embora os cálculos envolvidos para realização da correção de Yates não seja complicada sugerimos a leitura da literatura especializada na análise.
Vamos verificar um exemplo onde a correção de Monte Carlo, a qual é possível de ser realizada de maneira rápida e prática no R, é aplicada.
Imagine que você foi em campo e contabilizou as espécies de cracas que identificou. Foram contabilizados 12 cracas da espécie A e 24 da espécie B. Trabalhos anteriores demonstraram que ambas as espécies encontram-se na proporção de 1:1. Aplicando a simulação de Monte Carlo o número de indivíduos observados de ambas as espécies corroboram o esperado?
```r
N.especies <- c(12, 24)
prop.especies <- c(0.5, 0.5)
chisq.test(x = N.especies, p = prop.especies, simulate.p.value = FALSE)
```
```
##
## Chi-squared test for given probabilities
##
## data: N.especies
## X-squared = 4, df = 1, p-value = 0.0455
```
```r
chisq.test(x = N.especies, p = prop.especies, simulate.p.value = TRUE)
```
```
##
## Chi-squared test for given probabilities with simulated p-value (based
## on 2000 replicates)
##
## data: N.especies
## X-squared = 4, df = NA, p-value = 0.06647
```
Pronto. Basta usarmos o argumento simulate.p.value e indicar "FALSE" quando não queremos a simulação de Monte Carlo, ou apenas omitirmos este argumento, ou usar este argumento e indicar "TRUE" o qual realiza a simulação de Monte Carlo. Verifique que com a aplicação desta simulação o p-value aumenta indicando que torna mais dificil rejeitarmos a hipótese nula. Após aplicarmos a correção na nossa análise podemos afirmar que não há diferença na quantidade de cracas observadas em relação as proporções esperadas, para ambas as espécies de cracas.
Relembrando. Sempre tome cuidado com afirmações! Principalmente quando o número de observações é baixo. Mesmo que o teste estatístico indique diferenças uma baixa quantidade de observações devem ser analisadas cuidadosamente, no entanto devemos aplicar correções matemáticas nestes casos.
## χ² para independência
Realizamos este teste quando objetivamos saber se a frequência dos grupos de uma variável é independente de outra variável.
Diferente do primeiro caso de χ² que abordamos, este lida com duas variáveis categóricas ao invés de uma. Portanto é necessário o desenvolvimento de uma tabela de contigência.
A tabela de contigência consiste em uma tabela com o número de observações referentes as duas variáveis selecionadas. Veremos alguns exemplos abaixo.
Para o momento. Veja o sumário abaixo no qual detalhamos as principais características desta análise.
**[FAZER UMA TABELA COM AS CARACTERÍSTICAS DOS TESTES ABAIXO]**
**χ² para independência**
**Tipo e quantidade de variáveis: Utiliza duas (ou mais) variáveis categóricas;**
**H0: As proporções relativas de uma variável são independentes de uma segunda variável;**
**OBS: Diferentemente do primeiro teste do qui-quadrado neste caso utiliza-se 2 variáveis categóricas;**
**Como caracteristica intrinseca a este teste é necessário primeiramente a construção da tabela de contigência;**
**[FAZER UMA TABELA COM AS CARACTERÍSTICAS DOS TESTES ACIMA]**
Imagine a seguinte situação: Insetos foram coletados, ao acaso, em uma região costeira. Todos os insetos foram avaliados quanto a espécie e a presença de parasitas. Os seguintes valores foram obtidos: 55 indivíduos da espécie A com parasita, 75 indivíduos da espécie A sem parasita, 90 indivíduos da espécie B com parasita e 110 indivíduos da espécie B sem parasita. Foi levantada a hipótese nula de que a população infectada pelo parasita é a mesma para ambas as espécies.
Vamos começar criando uma matriz com esses valores, onde as linhas corresponderão as espécies e as colunas a presença/ausência do parasita.
```r
dados <- matrix(data = c(55, 75, 90, 110), ncol = 2, byrow = TRUE)
rownames(dados) <- c("Espécie A", "Espécie B")
colnames(dados) <- c("Com parasita", "Sem parasita")
dados
```
```
## Com parasita Sem parasita
## Espécie A 55 75
## Espécie B 90 110
```
Pronto nossa tabela de contigência está criada. Vamos seguir para a análise
```r
chisq.test(x = dados)
```
```
##
## Pearson's Chi-squared test with Yates' continuity correction
##
## data: dados
## X-squared = 0.13543, df = 1, p-value = 0.7129
```
Análise realizada. Díficil, penso que não. Vamos detalhar o que fizemos para construção da tabela de contigência e verificar o que a análise nos diz.
Para construção da tabela de contigência nós criamos um conjunto de dados por meio da função concatenar "*c()*" com os valores na ordem que definimos na questão, usamos o argumento "ncol" para indicar que os dados criados vão estar dispostos em 2 colunas e o argumento "byrow = TRUE" para indicar que os dados serão inseridos em ordem por linha, neste caso a função começará preenchendo a primeira linha da primeira coluna, segunda linha da primeira coluna, primeira linha da segunda coluna e segunda linha da segunda coluna. Perceba que os valores na matriz correspondem ao que foi indicado na questão. Espécie A com parasita apresenta 55 indivíduos, espécie B com parasita 75 indivíduos e assim por diante. As funções *rownames()* e *colnames()* são responsáveis por indicar os nomes das linhas e colunas respectivamente. Nós indicamos o nome do conjunto de dados os quais vamos dar os nomes (seja da linha ou da coluna) dentro do parênteses e assinalamos os nomes com o uso da função concatenar *c()*. Executar ao fim o nome dados nos retorna a matriz criada no console.
Ao executarmos a função *chisq.test()* utilizando apenas a matriz como objeto do argumento "x" ele nos retorna o χ² com a correção de Yates. O que é sugerido para quando estamos lidando com matrizes 2X2. No geral o resultado é similar ao que executamos no tópico anterior.
Uma atenção deve ser dada ao grau de liberdade o qual indica o valor de 1. O cálculo do grau de liberdade consiste no número de linhas menos um multiplicado pelo número de colunas menos um. Como temos 2 linhas e 2 colunas o grau de liberdade será: $(2-1)*(2-1) = 1*1 = 1$.
De acordo com o resultado obtido pelo teste não podemos refutar nossa hipótese nula. Portanto dizemos que a proporção da população infectada pelo parasita é a mesma nas duas espécies.
Vejamos um segundo exemplo.
Durante 2 anos camarões foram coletados, em um estuário, e todos eles foram sexados em machos e fêmeas. Objetivou-se com esses dados saber se há algum desvio da razão sexual entre os anos.
Vamos começar desenvolvendo um conjunto de dados na forma de planilha. Como comumente seus dados devem estar planilhados e vamos ensina-lo a construir uma tabela de contingência a partir desses dados.
```r
ano <- c(rep("Ano 1", 150), rep("Ano 2", 225))
sexo <- c(rep("macho", 55), rep("fêmea", 95), rep("macho", 105), rep("fêmea", 120))
dados <- data.frame(cbind(ano, sexo))
head(dados)
```
```
## ano sexo
## 1 Ano 1 macho
## 2 Ano 1 macho
## 3 Ano 1 macho
## 4 Ano 1 macho
## 5 Ano 1 macho
## 6 Ano 1 macho
```
```r
tab.cont <- table(dados)
tab.cont
```
```
## sexo
## ano fêmea macho
## Ano 1 95 55
## Ano 2 120 105
```
Pronto. Utilizando as funções acima (*c()*, *rep()*, *data.frame()* e *cbind()*) criamos um data frame com 2 colunas onde na primeira inserimos os anos e na segunda os sexos e usamos a função *head()* para visualizar no console as primeiras linhas deste data frame. Utilizamos, também, a função *table()* para criar nossa tabela de contingência. Vamos agora analisar os dados.
```r
chisq.test(tab.cont)
```
```
##
## Pearson's Chi-squared test with Yates' continuity correction
##
## data: tab.cont
## X-squared = 3.2817, df = 1, p-value = 0.07006
```
Pronto. Como podem ver a representação do resultado é similar ao exemplo acima. Contudo nossos dados são diferentes e portanto nossa hipótese nula é diferente.
Nossa hipótese nula pode ser escrita de três formas. Vejamos os 3 exemplos abaixo:
* H0: Na população amostrada a proporção de machos e fêmeas é independente do ano;
* H0: Na população amostrada a razão sexual dos camarões é a mesma entre os anos;
* H0: A proporção de camarões entre os anos é a mesma para ambos os sexos;
Como o teste resultou em um p-value maior que 0,05 podemos dizer, por essa via, que corroboramos nossa hipótese nula.
Neste ponto é bom relembramos da importância do número de observações de cada grupo. Se este número for pequeno incertezas podem ser geradas e ajustes devem ser feitos. Para saber mais sugerimos a leitura da literatura especializada. Contudo, para definir o que é um número baixo de observações sigamos o cálculo sugerido por Zar (2014) o qual define como: $n = 6rc$.
Onde, n é o número de observações mínimo de cada grupo, r é o número de linhas (rows) e c é o número de colunas (column). Dessa forma, em uma tabela de contigência do tipo 2x2 o número de observações mínimo para cada grupo deve ser de: $n = 6*(2)*(2) = 24$. Ou seja, 24 observações.
Esta análise pode ser conduzida, também, quando lidamos com mais de um grupo em uma categoria e neste caso teriamos uma tabela de contigência 2X3, 2X4, 3X3 e assim por diante. Vamos ver um exemplo.
Três pesquisadores analisaram fotografias de espécies bentônicas em um costão objetivando avaliar a abundância de duas espécies uma introduzida e uma nativa. Considere todo o processo amostral similar e que os pesquisadores avaliaram as mesmas fotografias. Neste caso nossa hipótese nula é que a proporção entre as espécies é independente dos pesquisadores.
Vamos construir nossa matriz de uma terceira forma.
```r
pesquisadores <- c("pesquisador 1", "pesquisador 2", "pesquisador 3")
sp.nativa <- c(70, 79, 38)
sp.introduzida <- c(84, 95, 80)
dados <- matrix(c(sp.nativa, sp.introduzida), nrow = 2, byrow = T)
colnames(dados) <- pesquisadores
rownames(dados) <- c("Espécie nativa", "Espécie introduzida")
dados
```
```
## pesquisador 1 pesquisador 2 pesquisador 3
## Espécie nativa 70 79 38
## Espécie introduzida 84 95 80
```
Pronto. Os dados foram construídos passo a passo. Vamos analisar e verificar o resultado.
```r
chisq.test(dados)
```
```
##
## Pearson's Chi-squared test
##
## data: dados
## X-squared = 6.2322, df = 2, p-value = 0.04433
```
Repare que há algo diferente, como realizamos a análise em uma tabela 2X3 por padrão a função *chisq.test()* não realiza a correção de Yates. Pois não é necessário.
Analisando o resultado podemos inferir que as proporções observadas de espécies nativas e introduzidas são diferentes em função do pesquisador. Ou seja, rejeitamos nossa hipótese nula de que as proporções são similares. Contudo o p-value foi bem próximo ao limiar de 0,05. Como pesquisador podemos nos aprofundar na questão e nos perguntar onde está essa diferença? Entre o pesquisador 1 e o pesquisador 2 ou entre outra dupla de pesquisadores? Como observamos isso?
Para responder essa pergunta em específico, vamos subdividir nossa tabela de contigência para todos os pares de observações e armazena-los em outros objetos.
```r
p1.p2 <- dados [, -3]
p1.p3 <- dados [, -2]
p2.p3 <- dados [, -1]
```
Pronto, criamos as nossas tabelas 2X2 para cada par de comparações. Repare que usamos a nossa tabela dados originalmente criada seguida por colchetes e dentro do colchetes inserimos virgula e menos o número referente a coluna. O colchetes após o nome dos dados nos permite acessar as linhas e colunas de um conjunto de dados quaisquer com isso podemos remove-las ou seleciona-las. Qualquer número antes da virgula indica a linha e qualquer número após a linha indica a coluna. O sinal de menos indica que vamos remover e se não colocarmos sinal indica que iremos selecionar. No primeiro caso onde inserimos "-3" após a virgula estamos indicando que vamos remover a terceira coluna do objeto dados e armazenar este resultado em um novo objeto chamado p1.p2. O mesmo raciocínio segue nos demais casos.
Sabendo isso vamos realizar a função *chisq.test()* para cada par de observações e analisar seu resultado.
```r
chisq.test(p1.p2)
```
```
##
## Pearson's Chi-squared test with Yates' continuity correction
##
## data: p1.p2
## X-squared = 0, df = 1, p-value = 1
```
```r
chisq.test(p1.p3)
```
```
##
## Pearson's Chi-squared test with Yates' continuity correction
##
## data: p1.p3
## X-squared = 4.3623, df = 1, p-value = 0.03674
```
```r
chisq.test(p2.p3)
```
```
##
## Pearson's Chi-squared test with Yates' continuity correction
##
## data: p2.p3
## X-squared = 4.5663, df = 1, p-value = 0.03261
```
Feito. Repare que não há diferenças entre o pesquisador 1 e o pesquisador 2. Mas entre o pesquisador 3 e os demais há diferença. Isto indica que é o pesquisador 3 que apresenta diferenças na proporção de espécies nativas e introduzidas, em relação aos demais pesquisadores.
Quando analisamos todo o conjunto de dados não observamos esta característica, mas ao separarmos os dados a diferença fica evidenciada.
Uma prática comum nesta análise é demonstrar o resultado por meio gráfico. Portanto, vamos observar como representar graficamente este último exemplo.
Primeiro vamos transformar nossa tabela de contigência em uma tabela no qual os valores irão corresponder a proporções relativas. Para isso vamos usar a função *prop.table()* e armazenar este resultado em um objeto chamado tabela.
```r
tabela <- prop.table(x = dados)
tabela
```
```
## pesquisador 1 pesquisador 2 pesquisador 3
## Espécie nativa 0.1569507 0.1771300 0.08520179
## Espécie introduzida 0.1883408 0.2130045 0.17937220
```
Como podem ver o resultado deste nosso passo nos retornou uma tabela de proporções em relação ao total. Podemos transformar-la em percentual. Vamos ver o processo
```r
tabela <- prop.table(x = dados)*100
tabela
```
```
## pesquisador 1 pesquisador 2 pesquisador 3
## Espécie nativa 15.69507 17.71300 8.520179
## Espécie introduzida 18.83408 21.30045 17.937220
```
Como podem ver, basta multiplicar a tabela por 100.
Mas vamos pensar um pouco na nossa análise e no que ela avalia. O χ² está avaliando as proporções relativas entre os grupos de uma dada variável, neste último caso a proporção das espécie em relação aos pesquisadores. Então a tabela de proporções ou percentual que nos interessa é a relação entre a espécie nativa e introduzida por pesquisador. A função *prop.table()* nos permite definir isso por meio do argumento "margin", vamos verificar o resultado olhando para o resultado em percentual.
```r
prop.table(x = dados, margin = 1)*100
```
```
## pesquisador 1 pesquisador 2 pesquisador 3
## Espécie nativa 37.43316 42.24599 20.32086
## Espécie introduzida 32.43243 36.67954 30.88803
```
```r
prop.table(x = dados, margin = 2)*100
```
```
## pesquisador 1 pesquisador 2 pesquisador 3
## Espécie nativa 45.45455 45.4023 32.20339
## Espécie introduzida 54.54545 54.5977 67.79661
```
Como podem visualizar, se usarmos margin = 1 ele nos retorna os valores em função das linhas (espécies), se utilizarmos margin = 2 ele nos retorna os valores em função das colunas (pesquisadores).
Vamos utilizar margin = 2 para construir nossa tabela e plotarmos nosso gráfico.
```r
tabela <- prop.table(x = dados, margin = 2)*100
par(mar = c(4, 4, 4, 13))
barplot(tabela,
col = c("red", "darkblue"),
legend.text = TRUE,
args.legend = list(x = "right", bty = "n", inset = -0.6))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-63-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Como podem ver o nosso gráfico foi realizado. Mas adicionamos uma série de comandos novos. Vamos explica-lo passo a passo.
Primeiro contruímos a tabela com os dados em percentuais relativos ao pesquisador e o armazenamos em um objeto chamado tabela.
Posteriormente utilizamos uma função chamada *par()* com o argumento mar no qual concatenamos 4 valores. Esta função juntamente com esse argumento permite que redimensionemos a janela gráfica. Os quatro valores concatenados referem-se as margens inferior, esquerda, superior e direita, respectivamente.
Nosso último passo é a nossa já conhecida função *barplot()*, onde inserimos como primeiro valor o objeto que contem os dados que queremos graficar "tabela", seguido pelo argumento "col" que define as cores de acordo com as linhas da tabela, por sua vez definimos se a legenda será plotada com o argumento "legend.text" e por último indicamos a posição e o formato da legenda por meio do argumento "args.lengend". Neste último argumento precisamos inserir uma função list no qual indicamos a posição da legenda pelo argumento "x", o argumento "bty" o qual define que a legenda não tera uma caixa desenhada em seu entorno e o argumento "inset" que define a posição da legenda em relação ao eixo x.
Para plotar um gráfico via *barplot()* a escrita pode ser feita de muitas maneiras, principalmente no que se refere a inserção da legenda. Experimente desenvolver um gráfico do mesmo estilo usando o conhecimento aprendido no capítulo anterior sobre gráficos.
<!--chapter:end:03-method.Rmd-->
# Teste-t.
Ao iniciarmos nossos estudos geralmente estamos interessados em saber se alguma característica da população que coletamos e analisamos é similar a uma outra população. Podemos abordar essa ideia por diversos caminhos porém vamos iniciar nossas análises em R através do teste-t para uma amostra e a discussão sobre hipótese nula, caudalidade e nível de confiança. A partir de então seguiremos para o teste-t com duas amostras e o teste-t pareado.
## Teste-t para uma amostra
Conduzimos esse teste quando objetivamos comparar se a média de uma dada variável é similar a um valor esperado. Ao falarmos de média percebemos que a variável com a qual estamos lidando é do tipo númerica ou inteiro (a diferença entre ambas consiste na presença de casas decimais), ou seja, quantitativo. Ao compararmos a média de nossa variável a um valor previamente estipulado 2 hipóteses são construídas, a hipótese nula (H0) e a hipótese alternativa (HA). H0 diz que a média de nossa variável é similar ao valor previamente estipulado, enquanto que HA diz que a média de nossa variável é diferente do valor previamente estipulado.
Matematicamente podemos obter o resultado do teste-t pela seguinte fórmula: $t_s=(x-mi)/(s/sqrt(n))$. Onde, x: média da amostra, mi: média teórica esperada, s: desvio padrão da amostra, n: tamanho da amostra.
Vamos verificar como conduzir esse teste no R por meio de exemplos utilizando valores fictícios.
Imagine o seguinte exemplo: 100 camarões foram coletados em um estuário. Suas medidas em relação ao tamanho foram tomadas e deseja-se saber se o seu tamanho médio é similar ou não ao tamanho médio (25,80 mm) da mesma espécie observada em outro estuario.
A partir do exemplo acima podemos definir nossas hipóteses, onde.
H0: média observada igual à média esperada;
HA: média observada diferente da média esperada;
Vamos começar gerando os dados relativos ao tamanho observado dos camarões que coletamos
```r
set.seed(1234)
tamanho.camarao <- rnorm(n = 100) + runif(n = 100, min = 17, max = 33)
```
A função *set.seed()* define os números aleatórios que serão gerados. Dessa forma, quando aplicado essa função associada a um número comum, no caso "1234", os números gerados aqui serão os mesmos em qualquer lugar.
A nossa segunda linha de comando utiliza a função *rnorm()* o qual gera números aleatórios considerando uma distribuição normal e soma esses valores gerados a uma distribuição uniforme gerada pela função *runif()*. A estas funções adicionamos argumentos que definem a quantidade de números gerados (argumento "n"), o valor mínimo que pode ser gerado (argumento "min") e o valor máximo que pode ser gerado (argumento "max"). E guardamos o resultado obtido em um objeto chamado tamanho.camarao. Repare que o nome do objeto não apresenta espaços ou acentos, que pode gerar problemas e/ou dificuldades na condução das análises.
Vamos verificar o resultado. Basta digitarmos o nome do objeto.
```r
tamanho.camarao
```
```
## [1] 26.36501 25.73118 23.16434 26.93999 25.85006 29.22289 21.34791 22.92014
## [9] 19.70599 31.88009 25.58378 20.48762 19.18464 29.19344 27.02799 31.80449
## [17] 26.70808 27.30077 23.83039 33.02083 23.89138 17.01159 20.68980 22.81711
## [25] 18.44307 23.54454 30.40893 21.37080 25.12759 23.97507 30.85514 25.59575
## [33] 17.99771 29.42112 24.44470 19.22824 26.81323 20.57450 24.53800 32.36946
## [41] 25.23524 19.84181 19.61879 27.74526 31.68906 23.66401 28.26906 24.93702
## [49] 31.93121 29.25393 23.70445 25.96390 20.11329 20.45772 17.87934 26.57236
## [57] 22.84551 16.27916 28.03817 24.16301 31.17074 20.02190 26.56155 20.62508
## [65] 18.92214 20.38837 27.83197 18.62320 19.12094 29.29845 22.72270 28.68786
## [73] 22.64878 30.43969 19.48136 24.94834 28.74896 24.99252 21.52521 22.19714
## [81] 22.72903 23.69804 30.32393 29.37573 29.65554 22.18997 24.85922 21.19787
## [89] 27.94906 28.93757 27.42930 23.87127 33.93523 21.89126 26.24338 29.48277
## [97] 26.96407 19.72505 28.14750 24.06552
```
Vamos observar as métricas e gráficos, conforme já fizemos nos capítulos anteriores, mas relativos ao objeto criado.
```r
mean(tamanho.camarao)
```
```
## [1] 24.86218
```
```r
min(tamanho.camarao)
```
```
## [1] 16.27916
```
```r
max(tamanho.camarao)
```
```
## [1] 33.93523
```
```r
length(tamanho.camarao)
```
```
## [1] 100
```
```r
hist(tamanho.camarao)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-66-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Como podemos ver os valores mínimo e máximo são similares ao que definimos e o número de elementos é o mesmo. Graficamente podemos ver que a distribuição é normal, pois como vimos utilizamos uma função que cria uma distribuição normal com limites definidos pela função *runif()*. Além disso vemos que há uma maior frequência dos valores em torno de 25.
Vamos verificar, agora se esse valor que geramos (obtivemos de tamanho do camarão) são similares ao observado em outra localidade, por meio do teste-t para uma amostra.
```r
esperado = 25.80
t.test(x = tamanho.camarao, mu = esperado)
```
```
##
## One Sample t-test
##
## data: tamanho.camarao
## t = -2.2432, df = 99, p-value = 0.02711
## alternative hypothesis: true mean is not equal to 25.8
## 95 percent confidence interval:
## 24.03263 25.69173
## sample estimates:
## mean of x
## 24.86218
```
Dois comandos foram executados, no primeiro criamos um objeto, denominado "esperado", que guarda o valor referente ao tamanho de camarão observado em outro estuário (25,80 mm). O segundo comando que realizamos refere-se a função do teste-t no qual inserimos 2 argumentos. O primeiro argumento (x) refere-se ao nosso objeto que contem os dados referentes ao tamanho que coletamos e o segundo argumento (mu) refere-se ao objeto que contem a média do tamanho obtido em outro estuário.
Conforme podemos visualizar no resultado temos 9 linhas. A primeira linha nos diz qual teste está sendo conduzido, neste caso é ("One Sample t-test" ou teste-t par auma amostra), a segunda linha nos retorna o conjunto de dados que utilizamos, a terceira linha nos retorna o valor do teste t (t = -2,2432) o grau de liberdade (df = 99) e o valor de probabilidade associado ao teste (p-value = 0,02711), a quarta linha nos retorna qual é nossa hipótese alternativa, caso a aceitemos (a qual nos diz que: a média dos nossos dados não é igual à 25,8), a quinta e sexta linhas nos fornece o intervalo de confiança de 95% dos nossos dados (24,03263 e 25,69173) e da sétima a nona linha refere-se a informação relativa a média dos nossos dados (24,86218).
Em resumo, podemos inferir que a média dos nossos dados é diferente do valor esperado pois o p-value foi menor que 0,05. Além disso podemos dizer que a média do tamanho dos camarões que coletamos (24,86 mm) é estatisticamente menor do que a média presente no outro estuário (25,80 mm). De outra forma podemos dizer que se rejeitarmos H0 cometeremos um erro de 1,5% (p-value em percentual), ou seja, 1,5% de estarmos cometendo o erro tipo 1 (rejeitar a H0 quando ela é verdadeira), como 1,5% é menor que 5%, temos subsídio para afirmar que a média obtida (24,86 mm) é diferente da média esperada (25,80 mm) (98,5% de certeza).
Ok, verificamos e entendemos como conduzir a análise. Mas há um conceito estatístico importante na análise do teste-t, a caudalidade. No exemplo anterior nós trabalhamos com as hipóteses de que a média de um conjunto de dados é igual (H0) ou diferente (HA) da média esperada. O que implica em dizer que a média que observamos pode ser maior ou menor do que o esperado. Contudo em algumas instâncias podemos querer verificar se a média do nosso conjunto de dados é maior ou igual ou menor ou igual a média esperada e não diferente. Desta diferença na construção da hipótese que emerge o conceito da caudalidade. No exemplo anterior foi testado a hipótese bicaudal que é tido como padrão ("default") na função do R que executamos.
A diferença entre realizar o teste-t bicaudal ou unicaudal depende da pergunta feita previamente e dos dados coletados. Então antes de realizar este teste mantenha-se atento a hipótese que se deseja testar.
Agora imagine o seguinte exemplo: Em um costão rochoso foi observado ao longo do dia "1" 100 estrelas do mar em diferentes alturas, em relação a baixamar. Essas alturas foram quantificadas (valores serão construídos abaixo). Sabe-se que no dia anterior "0" a altura média das estrelas no mesmo costão foi de 0,90 m. Sabe-se também que o dia anterior (dia 0) foi mais frio e que dias mais frios implicam em maiores alturas. A partir dessas informações e quais são as hipóteses testadas e o resultado do teste-t.
H0: A média da altura das estrelas do mar no costão no dia "1" é menor ou igual ao dia "0"
HA: A média da altura das estrelas do mar no costão no dia "1" é maior que a do dia "0"
Matematicamente podemos escrever da seguinte forma:
H0: μ ≤ 0,90
HA: μ > 0,90
```r
set.seed(1234)
dados <- rnorm(n = 100, sd = 0.02) + runif(n = 100, min = 0.4, max = 1.3)
```
Observe que geramos os dados de maneira similar ao que fizemos no exemplo anterior, a diferença é que inserimos um argumento na função *rnorm()* que corresponde ao desvio padrão (de 0,02) dos dados normais que estamos gerando.
```r
mean(dados)
```
```
## [1] 0.8479302
```
```r
min(dados)
```
```
## [1] 0.387487
```
```r
max(dados)
```
```
## [1] 1.290766
```
```r
length(dados)
```
```
## [1] 100
```
```r
hist(dados)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-69-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Conforme também fizemos anteriormente calculamos algumas métricas para entender os dados e um histograma básico para visualizar a forma dos dados que representam a altura que as estrelas se encontram no ambiente.
```r
dia.0 = 0.90
t.test(x = dados, mu = dia.0, alternative = "greater")
```
```
##
## One Sample t-test
##
## data: dados
## t = -2.2073, df = 99, p-value = 0.9852
## alternative hypothesis: true mean is greater than 0.9
## 95 percent confidence interval:
## 0.8087617 Inf
## sample estimates:
## mean of x
## 0.8479302
```
Agora construímos um objeto chamado "dia.0" que nos retorna o valor médio encontrado para altura das estrelas do mar no costão no dia 0 e seguimos com o teste-t onde avaliamos se os dados que obtivemos do dia 1 são menores ou iguais ao dia 0, por meio do argumento "alternative" definido-o como "greater". Este argumento novo que incluímos pode ser definido de 3 formas: "two-sided" que é o padrão ("default"), "greater" ou "less". O argumento "alternative" seguirá o sinal da hipótese alternativa que foi construída para o teste.
Com isso podemos avaliar o resultado que é similar ao que vimos anteriormente com poucas mudanças. A primeira linha (One Sample t-test) informa sobre o teste realizado. A segunda linha indica o nome do conjunto de dados que inserimos. A terceira linha nos dá o valor do teste-t (t = -2,2073), do grau de liberdade (df = 99) e da probabilidade associada ao teste (p-value = 0.9852). A quarta linha indica a hipótese alternativa, caso seja aceita (o que não é o caso), que é verdade que a média dos nossos dados são maiores que 0,90 m. A quinta e sexta linha indicam o intervalo de confiança de 95% dos nossos dados (0,8087617 e inf). A sétima, oitava e nona linha referem-se a média dos dados.
Como podemos notar pelo p-value do nosso resultado este demonstra que não temos informação o suficiente para rejeitar nossa hipótese nula (H0). Portanto a média dos nossos dados é menor ou igual a 0,90.
Outro conceito importante de qualquer teste inferencial (ex. teste-t) é o nível de confiança. Até o presente momento consideramos o nível de confiança de 95%. Se quisermos altera-lo no teste-t devemos adicionar o argumento "conf.level" em proporção (0-1). A sua alteração implica na zona de rejeição da hipótese nula, se aumentarmos o seu valor fica mais dificil rejeitarmos a hipótese nula e se diminuirmos o seu valor fica mais fácil rejeitar a hipótese nula. Vejamos um outro exemplo.
Imagine o seguinte exemplo: Um pesquisador avaliou o tamanho das cracas incrustadas no casco de uma embarcação. Objetivando saber se o tamanho médio de bivalves difere do teórico esperado (20 mm) um teste-t bicaudal foi aplicado a um nível de confiança de 95% e 99%.
Vamos descrever as hipóteses e realizar a análise para ambos os níveis de confiança.
Neste caso temos as seguintes hipóteses:
H0: O tamanho médio observado é similar ao teórico
HA: O tamanho médio observado difere do teórico
Conforme já realizado anteriormente vamos gerar os dados e explora-los com a algumas métricas estatśticas e grafica de maneira similar ao que fizemos no exemplo anterior.
```r
set.seed(1234)
dados <- rnorm(n = 100, sd = 1.9) + runif(n = 100, min = 5, max = 25)
mean(dados)
```
```
## [1] 14.72583
```
```r
min(dados)
```
```
## [1] 3.596275
```
```r
max(dados)
```
```
## [1] 27.27792
```
```r
length(dados)
```
```
## [1] 100
```
```r
hist(dados)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-71-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Agora sigamos com a condução da análise.
```r
teorico <- 13.5
t.test(x = dados, mu = teorico, conf.level = 0.95)
```
```
##
## One Sample t-test
##
## data: dados
## t = 2.3113, df = 99, p-value = 0.02289
## alternative hypothesis: true mean is not equal to 13.5
## 95 percent confidence interval:
## 13.67349 15.77817
## sample estimates:
## mean of x
## 14.72583
```
```r
t.test(x = dados, mu = teorico, conf.level = 0.99)
```
```
##
## One Sample t-test
##
## data: dados
## t = 2.3113, df = 99, p-value = 0.02289
## alternative hypothesis: true mean is not equal to 13.5
## 99 percent confidence interval:
## 13.33290 16.11876
## sample estimates:
## mean of x
## 14.72583
```
Como podem ver ambos os resultados (com diferentes níveis de confiança) retornam o mesmo valor do teste-t e do "p-value". E neste ponto precisamos ir com calma para evitar erro de interpretação do resultado e entender estatisticamente o que está acontencendo.
Quando representamos o nível de confiança (representado pelo argumento "conf.level") por um valor probabilístico de 0,95 ou 0,99 estamos dizendo que o nível de significância é 0,05 e 0,01, respectivamente. Quando olhamos para o resultado do p-value, temos que levar em consideração o nível de significância (que consiste em: 1 - nível de confiança).
Vejamos o nosso resultado.
No primeiro caso ("conf.level = 0.95") temos p-value = 0.02289, como este valor é menor que 0,05 (nosso nível de significância), isso quer dizer que a média teórica está fora do intervalo de confiança dos dados, portanto rejeitamos a hipótese nula.
No segundo caso ("conf.level = 0.99") temos o mesmo "p-value", contudo este valor é maior que nosso nível de significância (0,01), isso quer dizer que nossa média teórica está dentro do intervalo de confiança, portanto aceitamos a hipótese nula de que a média observada é similar a média teórica.
O nível de significância a aplicar nos seus dados depende das informações que possui sobre o organismo e o ambiente que está estudando. Apesar da regra-de-bolso dizer 0,05 e por "default" o R definir esse nível de significância é necessário discutir o que ele representa para seus dados e qual a implicação para sua hipótese e as medidas que serão tomadas. Uma dica importante é: reporte sempre o intervalo de confiança, indique o nível de significância (consiste em: 1 menos o nível de confiança) que foi aplicado e no seu texto deixe claro a escolha do nível de significância, principalmente se for diferente do que é definido como padrão.
BÔNUS:
Embora não seja comum, podemos plotar um gráfico que represente o nosso resultado estatístico como uma curva de densidade no qual é representado o valor do teste-t, o grau de liberdade e o valor de proabilidade associado. Para isso vamos usar um pacote o qual precisa ser instalado chamado "webr" e precisamos carrega-lo usando a função library(). Após isso é só inserir a função que desenvolve o teste-t dentro da função plot(). Veja o resultado para ambos os níveis de confiança estabelecidos previamente. OBS: Uma vez instalado o pacote não precisa instala-lo novamente.
```r
## install.packages("webr")
library(webr)
```
```r
plot(t.test(x = dados, mu = teorico, conf.level = 0.95))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-74-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
```r
plot(t.test(x = dados, mu = teorico, conf.level = 0.99))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-74-2.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Verifique que esses plots nos fornecem as curvas do teste-t aos níveis de confiança de 95% e 99%, demarca os limites inferior e superior de vermelho e marca como ponto azul na curva de densidade o valor do teste-t associado. Como esse valor está dentro da região demarcada no nível de confiança de 95%, neste caso rejeitamos a hipótese nula e como no nível de confança de 99% o ponto azul está fora da região demarcada aceitamos a hipótese nula.
## Teste-t para duas amostras
Conduzimos esse teste quando objetivamos comparar se a média de dois grupos (= amostras, populações etc) são similares. Portanto para sua realização é necessário uma variável mensurável e uma variável categórica com 2 grupos.
Ou seja, partindo desse objetivo as hipótese nula e alternativa desse teste são as seguintes:
H0: A diferença na média da variável quantitativa dos grupos é igual a 0;
HA: A diferença na média da variável quantitativa dos grupos é diferente de 0;
Outra forma de interpretamos a hipótese relativa a esste teste é:
H0: A média da variável quantitativa é igual entre grupos;
HA: A média da variável quantitativa é diferente entre grupos;
Outra forma de escrevermos a hipótese deve-se ao fato da caudalidade do teste e, se unicaudal, pode ser escrita da seguinte forma:
H0: A média da variável quantitativa é maior ou igual (ou menor ou igual) entre grupos;
HA: A média da variável quantitativa é menor (ou maior) entre grupos;
A partir desse teste alguns pressupostos estatísticos precisam ser avaliados e portanto algumas análises precisam ser realizadas antes da interpretação do resultado do teste-t. Pressupostos como normalidade (ambos os grupos devem provir de uma população com distribuição normal) e homocedasticidade (A variância entre os dois grupos devem ser iguais). Demonstraremos a frente como realizar alguns desses testes. Mas, primeiro vamos gerar os dados a serem trabalhados para esta etapa. Execute o código abaixo e você irá visualizar no "environment" do seu RStudio um objeto chamado gastropode que corresponde a um data frame com o conjunto de dados que iremos trabalhar.
```r
grupos <- c(rep(x = "Alimento A", 50), rep(x = "Alimento B", 50))
set.seed(123)
alimento.A <- rnorm(n = 50, mean = 0.7, sd = 0.2)
set.seed(4321)
alimento.B <- rnorm(n = 50, mean = 0.2, sd = 0.2)
Alimento <- c(alimento.A, alimento.B)
gastropode <- as.data.frame(cbind(grupos, round(Alimento, 3)))
colnames(gastropode) <- c("Alimento", "Peso")
rm(list = "grupos", "alimento.A", "alimento.B", "Alimento")
```
Vamos, agora, verificar os dados por meio da função *head()* e a estrutura dos dados por meio da função *str()* e alterar a estrutura dos dados se necessário.
```r
head(gastropode)
```
```
## Alimento Peso
## 1 Alimento A 0.588
## 2 Alimento A 0.654
## 3 Alimento A 1.012
## 4 Alimento A 0.714
## 5 Alimento A 0.726
## 6 Alimento A 1.043
```
```r
str(gastropode)
```
```
## 'data.frame': 100 obs. of 2 variables:
## $ Alimento: chr "Alimento A" "Alimento A" "Alimento A" "Alimento A" ...
## $ Peso : chr "0.588" "0.654" "1.012" "0.714" ...
```
```r
gastropode$Alimento <- as.factor(gastropode$Alimento)
gastropode$Peso <- as.numeric(gastropode$Peso)
str(gastropode)
```
```
## 'data.frame': 100 obs. of 2 variables:
## $ Alimento: Factor w/ 2 levels "Alimento A","Alimento B": 1 1 1 1 1 1 1 1 1 1 ...
## $ Peso : num 0.588 0.654 1.012 0.714 0.726 ...
```
Agora que importamos e organizamos nossa planilha vamos analisar nosso exemplo.
100 indivíduos de uma espécie de gastropode foi coletada e mantida em cultivo para avaliação da dieta. 50 indivíduos foram mantidos com uma dieta rica no Alimento A e 50 indivíduos com uma dieta rica no Alimento B. Todos os indivíduos foram pesados antes e depois do experimento. A planilha a seguir informa a alteração de peso dos organismos, em gramas, após a dieta oferecida.
Antes de conduzirmos o teste-t vamos praticar fazendo a avaliação gráfica e númerica dos dados.
```r
## par(mfrow = c(2, 1))
hist(gastropode$Peso [gastropode$Alimento == "Alimento A"],
xlab = "Alteração do peso",
ylab = "Frequência",
main = "Alimento A",
ylim = c(0, 20),
xlim = c(-0.5, 1.5))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-77-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
```r
hist(gastropode$Peso [gastropode$Alimento == "Alimento B"],
xlab = "Alteração do peso",
ylab = "Frequência",
main = "Alimento B",
ylim = c(0, 20),
xlim = c(-0.5, 1.5))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-77-2.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
```r
## par(mfrow = c(1, 1))
boxplot(Peso ~ Alimento, data = gastropode)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-78-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Os 5 comandos acima realizam: a divisão da janela gráfica em 2 linhas e 1 coluna, o histograma dos dados para Alimento A, o histograma dos dados para Alimento B, a divisão da janela gráfica em 1 linha e 1 coluna e o boxplot para ambos os dados, respectivamente.
A função *par()* com o argumento "mfrow" e a função c(2, 1) com os valores 2 e 1 divide a janela gráfica em 2 linhas e 1 coluna. Caso queira retornar ao padrão normal basta limpar a janela gráfica clicando no ícone que parece uma vassoura acima dos gráficos (mas isso limpará todos os gráficos anteriores) ou então utilizar a função *par()* e "re"dividir a janela gráfica em 1 linha e 1 coluna "par(mfrow = c(1, 1))".
Os 2 gráficos, após a divisão da janela em 2 linhas e 1 coluna, consistem em histogramas em relação aos dados de peso por Alimento. Na primeira linha indicamos a variável peso dentro da planilha gastropode por meio do operador matemático $ (cifrão) e selecionamos os dados correspondentes ao Alimento utilizando colchetes [] dentro do qual selecionamos a variável Alimento dentro da planilha gastropode e por meio do sinal de igual duplicado (==) indicamos entre aspas ("") o grupo (ou categoria) que desejamos. Os demais argumentos são já bem conhecidos e iguais para ambos os histogramas, diferindo apenas o título do gráfico que é definido pelo argumento "main".
O Boxplot resume os dados por Alimento e nos indica outras métricas (quartis), como vimos anteriormente no tópico sobre gráficos.
Mas se desejarmos observar os valores númericos que resumem os dados, podemos seguir o que aprendemos anteriormente.
```r
summary(gastropode)
```
```
## Alimento Peso
## Alimento A:50 Min. :-0.1180
## Alimento B:50 1st Qu.: 0.2172
## Median : 0.4475
## Mean : 0.4652
## 3rd Qu.: 0.6843
## Max. : 1.1340
```
```r
mean(gastropode$Peso)
```
```
## [1] 0.46519
```
```r
mean(gastropode$Peso [gastropode$Alimento == "Alimento A"])
```
```
## [1] 0.7069
```
```r
mean(gastropode$Peso [gastropode$Alimento == "Alimento B"])
```
```
## [1] 0.22348
```
Utilizando o pacote Rmisc temos uma forma mais simples de escrita e eficiente para observar esses valores e algumas outras métricas (ex.: número amostral, média, desvio padrão, erro padrão e intervalo de confiança).
```r
library(Rmisc)
summarySE(data = gastropode, measurevar = "Peso", groupvars = "Alimento")
```
```
## Alimento N Peso sd se ci
## 1 Alimento A 50 0.70690 0.1852070 0.02619223 0.05263525
## 2 Alimento B 50 0.22348 0.1573551 0.02225337 0.04471982
```
Ok, até aqui observamos como estão os nossos dados e podemos ver que a administração da Alimento A resultou em um maior ganho de peso pelos gastropodes do que a Alimento B. Mas será que o que observamos grafica e numericamente se reflete estatisticamente? Vamos a nossa avaliação dos pressupostos do teste-t para duas amostras e se cumpridos para a avaliação do teste-t.
Uma das formas mais convencionais de avaliar a normalidade é pelo teste de shapiro-wilks e a homocedasticidade pelo teste de Bartlett. Vamos avalia-las.
```r
shapiro.test(gastropode$Peso [gastropode$Alimento == "Alimento A"])
```
```
##
## Shapiro-Wilk normality test
##
## data: gastropode$Peso[gastropode$Alimento == "Alimento A"]
## W = 0.98923, p-value = 0.9266
```
```r
shapiro.test(gastropode$Peso [gastropode$Alimento == "Alimento B"])
```
```
##
## Shapiro-Wilk normality test
##
## data: gastropode$Peso[gastropode$Alimento == "Alimento B"]
## W = 0.98059, p-value = 0.5769
```
```r
bartlett.test(Peso ~ Alimento, data = gastropode)
```
```
##
## Bartlett test of homogeneity of variances
##
## data: Peso by Alimento
## Bartlett's K-squared = 1.2826, df = 1, p-value = 0.2574
```
Como podemos observar, ambos os grupos apresentam dados normais e homocedásticos, para um nível de confiança de 95%, já que o p-value foi superior a 0,05. Dessa forma vamos dar continuidade a nossa análise e verificar se as médias dos grupos são diferentes.
```r
t.test(Peso ~ Alimento,
data = gastropode,
var.equal = TRUE,
conf.level = 0.95)
```
```
##
## Two Sample t-test
##
## data: Peso by Alimento
## t = 14.065, df = 98, p-value < 2.2e-16
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## 0.4152153 0.5516247
## sample estimates:
## mean in group Alimento A mean in group Alimento B
## 0.70690 0.22348
```
Repare que a forma da escrita se alterou um pouco. Mas como podem ver, nada complicado. Agora escrevemos a variável quantitativa (peso) em função da (~) variável categórica (Alimento). Guarde bem essa forma de escrita pois ela será utilizada para praticamente todos os testes a partir daqui e para inúmeras outras funções. Adcionamos o argumento "data" que indica a planilha de onde estamos utilizando as variáveis, o argumento "var.equal" o qual indica que a variância entre os grupos é igual e o argumento "conf.level" o qual define o nível de confiança com qual estamos trabalhando.
De acordo com nosso resultado podemos ver que o o valor do teste-t é 14,065, o grau de liberdade de 98 (o qual consiste no total de observações subtraído de um por grupo), o valor de probabilidade associado ao teste ($2.2\times10^{-6}$), o intervalo de confiança de 95% (0,415 e 0,551) que refere-se a diferença da média entre os grupos (a diferença da média dos grupos é: 0,70690 - 0,22348 = 0,48342), ou seja, o intervalo de confiança é em função dessa diferença e as últimas linhas do resultado representam as médias de alteração do peso para cada Alimento (Alimento A = 0,70690 e Alimento B = 0,22348). De acordo com esse resultado refutamos a hipótese nula de que as médias são similares. Portanto podemos dizer que dependendo da Alimento (A ou B) utilizada na dieta podemos ter diferentes alterações no peso dos gastropodes.
Da mesma forma que avaliamos para o teste-t de uma amostra, podemos plotar o resultado como um gráfico da função de densidade do teste-t. Só devemos lembrar de carregar o pacote "webr".
```r
library(webr)
plot(t.test(Peso ~ Alimento,
data = gastropode,
var.equal = TRUE,
conf.level = 0.95))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-83-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Neste gráfico podemos ver que o resultado do teste-t, indicado pelo ponto azul, está muito além do nível da zona de rejeição, indicando que os dois grupos apresentam médias bem diferentes em outras palavras a diferença entre as duas médias é altamente significativa e diferente de 0.
Vamos exercitar nosso conhecimento em R e teste-t com um outro exemplo (Gere a planilha abaixo).
```r
grupos <- c(rep(x = "Ano 0", 36), rep(x = "Ano 20", 36))
set.seed(245)
ano.0 <- rnorm(n = 36, mean = 15.7, sd = 0.2) + runif(n = 36)
set.seed(356)
ano.20 <- rnorm(n = 36, mean = 16.2, sd = 0.5) + runif(n = 36)
ano <- c(ano.0, ano.20)
lagoa <- as.data.frame(cbind(grupos, round(ano, 3)))
colnames(lagoa) <- c("Ano", "Temperatura")
rm(list = "grupos", "ano.0", "ano.20", "ano")
```
Imagine que durante um ano você mensurou a temperatura de uma lagoa três vezes por mês durante todos os meses ao longo de 1 ano. 20 anos depois você retornou a lagoa e mensurou novamente a temperatura três vezes por mês durante um ano. Considerando um nível de confiança de 99% a temperatura é igual ou diferente entre os anos?
A primeira coisa que devemos fazer é escrever nossa hipótese. Vamos a ela.
H0: A média da temperatura é igual entre os anos;
HA: A média da temperatura é diferente entre os anos;
Com a hipótese construída vamos verificar a estrutura dos dados (modificar se necessário) e sumarizar nossos dados grafica e matematicamente.
```r
head(lagoa)
```
```
## Ano Temperatura
## 1 Ano 0 16.345
## 2 Ano 0 16.383
## 3 Ano 0 15.727
## 4 Ano 0 16.058
## 5 Ano 0 15.842
## 6 Ano 0 16.158
```
```r
str(lagoa)
```
```
## 'data.frame': 72 obs. of 2 variables:
## $ Ano : chr "Ano 0" "Ano 0" "Ano 0" "Ano 0" ...
## $ Temperatura: chr "16.345" "16.383" "15.727" "16.058" ...
```
```r
lagoa$Ano <- as.factor(lagoa$Ano)
lagoa$Temperatura <- as.numeric(lagoa$Temperatura)
str(lagoa)
```
```
## 'data.frame': 72 obs. of 2 variables:
## $ Ano : Factor w/ 2 levels "Ano 0","Ano 20": 1 1 1 1 1 1 1 1 1 1 ...
## $ Temperatura: num 16.3 16.4 15.7 16.1 15.8 ...
```
```r
## par(mfrow = c(2, 1))
hist(lagoa$Temperatura [lagoa$Ano == "Ano 0"],
xlab = "Temperatura (°C)",
ylab = "Frequência",
main = "Ano 0",
ylim = c(0, 15),
xlim = c(15, 19))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-86-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
```r
hist(lagoa$Temperatura [lagoa$Ano == "Ano 20"],
xlab = "Temperatura (°C)",
ylab = "Frequência",
main = "Ano 20",
ylim = c(0, 15),
xlim = c(15, 19))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-86-2.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
```r
boxplot(Temperatura ~ Ano, data = lagoa)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-87-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Como podem verificar a análise gráfica não diferiu do que fizemos no exemplo anterior. Quanto ao seu resultado podemos notar uma maior temperatura média anual da lagoa 20 anos depois da primeira amostragem.
```r
summary(lagoa)
```
```
## Ano Temperatura
## Ano 0 :36 Min. :15.58
## Ano 20:36 1st Qu.:16.08
## Median :16.41
## Mean :16.52
## 3rd Qu.:16.86
## Max. :18.74
```
```r
library(Rmisc)
summarySE(data = lagoa, measurevar = "Temperatura", groupvars = "Ano")
```
```
## Ano N Temperatura sd se ci
## 1 Ano 0 36 16.14661 0.3301591 0.05502652 0.1117098
## 2 Ano 20 36 16.89750 0.6409853 0.10683089 0.2168782
```
Aplicando a função *summarySE()* do pacote Rmisc obtivemos sumarizamos nossos dados como mostrado acima e em relação aos valores de média e desvios podemos observar que a média é bem próxima, mas será que elas são estatisticamente iguais? Para isso vamos realizar o teste-t.
Antes do teste vamos calcular os pressupostos do teste, normalidade e homocedasticidade.
```r
shapiro.test(lagoa$Temperatura [lagoa$Ano == "Ano 0"])
```
```
##
## Shapiro-Wilk normality test
##
## data: lagoa$Temperatura[lagoa$Ano == "Ano 0"]
## W = 0.97181, p-value = 0.4771
```
```r
shapiro.test(lagoa$Temperatura [lagoa$Ano == "Ano 20"])
```
```
##
## Shapiro-Wilk normality test
##
## data: lagoa$Temperatura[lagoa$Ano == "Ano 20"]
## W = 0.9571, p-value = 0.1747
```
```r
bartlett.test(Temperatura ~ Ano, data = lagoa)
```
```
##
## Bartlett test of homogeneity of variances
##
## data: Temperatura by Ano
## Bartlett's K-squared = 14.189, df = 1, p-value = 0.0001653
```
Como podemos ver os dados são normais, porém não são homocedasticos (a variância não é igual entre os grupos). Neste caso podemos fazer um teste-t de Welch (este teste aplica uma correção quando as variâncias não são iguais). Contudo, o teste de Welch ele é comumente usado quando o N amostral é considerado baixo (menor que 10 para um dos dois grupos). Vamos Analisar o teste-t considerando a variância igual e desigual para ver se há diferença significativa no resultado do teste ou não.
```r
t.test(Temperatura ~ Ano,
data = lagoa,
var.equal = TRUE,
conf.level = 0.99)
```
```
##
## Two Sample t-test
##
## data: Temperatura by Ano
## t = -6.2486, df = 70, p-value = 2.837e-08
## alternative hypothesis: true difference in means is not equal to 0
## 99 percent confidence interval:
## -1.069087 -0.432691
## sample estimates:
## mean in group Ano 0 mean in group Ano 20
## 16.14661 16.89750
```
```r
t.test(Temperatura ~ Ano,
data = lagoa,
var.equal = FALSE,
conf.level = 0.99)
```
```
##
## Welch Two Sample t-test
##
## data: Temperatura by Ano
## t = -6.2486, df = 52.35, p-value = 7.594e-08
## alternative hypothesis: true difference in means is not equal to 0
## 99 percent confidence interval:
## -1.0721092 -0.4296686
## sample estimates:
## mean in group Ano 0 mean in group Ano 20
## 16.14661 16.89750
```
Como podem notar a forma de escrever o teste é similar ao exemplo anterior as alterações consistem nas variáveis e conjunto de dados utilizado e como foi pedido no teste a alteração do nível de confiança para 99% (conf.level = 0,99) e os dois teste-t (com variância igual e com variância desigual - Welch).
Olhando para os dois resultados ambos os testes demonstraram diferenças significativas entre os anos, pois o p-value foi menor que 0,01 (lembrar que como o nível de confiança foi alterado para 0,99 a significância só ocorrerá se o p-value for menor que 0,01, como é o caso). Porém podemos ver que não há muita diferença em relação aos valores de ambos os teste-t, pois como comunicamos a aplicação do teste-t de Welch apresenta maior importância quando as variâncias são desiguais e o número amostral de um dos grupos é muito pequeno.
Assim como fizemos anteriormente vamos olhar o resultado em relação a distribuição da função de densidade do teste-t para um nível de confiança de 99%. Só devemos lembrar de carregar o pacote "webr" se ainda não foi carregado.
```r
library(webr)
plot(t.test(Temperatura ~ Ano,
data = lagoa,
var.equal = TRUE,
conf.level = 0.99))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-91-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
De acordo com esse exemplo podemos afirmar que os anos diferem entre si e que em 20 anos a lagoa amostrada apresentou um aumento da temperatura.
## Teste-t pareado
Aplicamos este teste quando as duas amostras de uma variável categórica são independentes e desejamos verificar se elas são similares entre si. Contudo cada observação de ambas as amostras devem de alguma forma estar associadas para podermos dizer que ocorrem em pares. Neste caso as hipóteses são as seguintes:
H0: Não há diferença entre os pares de observações;
HA: Há diferença entre os pares de observações;
Matematicamente pode ser dita da seguinte forma:
H0: A diferença na média dos pares de observações é igual a 0;
HA: A diferença na média dos pares de observações é diferente de 0;
Vejamos um exemplo de como conduzir essa análise no R
Imagine que dois pesquisadores embarcaram com objetivo de fazer contagem de aves em alto mar. Após 20 dias de observações independentes entre os observadores obtivemos os dados abaixo.
Começaremos gerando os dados e a modificando se necessário.
```r
observadores <- c(rep(x = "Observador 1", 20), rep(x = "Observador 2", 20))
set.seed(2328)
aves.1 <- rnorm(n = 20, mean = 20, sd = 1) + runif(n = 20)
set.seed(3230)
aves.2 <- rnorm(n = 20, mean = 21, sd = 2) + runif(n = 20)
dia <- c("Dia 1", "Dia 2", "Dia 3", "Dia 4", "Dia 5", "Dia 6", "Dia 7", "Dia 8", "Dia 9", "Dia 10", "Dia 11", "Dia 12", "Dia 13", "Dia 14", "Dia 15", "Dia 16", "Dia 17", "Dia 18", "Dia 19", "Dia 20")
aves <- c(aves.1, aves.2)
aves <- as.data.frame(cbind(dia, round(aves.1, 0), round(aves.2, 0)))
colnames(aves) <- c("Dia", "Observador 1", "Observador 2")
rm(list = "observadores", "aves.1", "aves.2", "dia")
```
```r
head(aves)
```
```
## Dia Observador 1 Observador 2
## 1 Dia 1 19 20
## 2 Dia 2 20 22
## 3 Dia 3 18 23
## 4 Dia 4 22 18
## 5 Dia 5 22 22
## 6 Dia 6 22 23
```
```r
str(aves)
```
```
## 'data.frame': 20 obs. of 3 variables:
## $ Dia : chr "Dia 1" "Dia 2" "Dia 3" "Dia 4" ...
## $ Observador 1: chr "19" "20" "18" "22" ...
## $ Observador 2: chr "20" "22" "23" "18" ...
```
```r
aves$Dia <- as.factor(aves$Dia)
aves$`Observador 1` <- as.numeric(aves$`Observador 1`)
aves$`Observador 2` <- as.numeric(aves$`Observador 2`)
str(aves)
```
```
## 'data.frame': 20 obs. of 3 variables:
## $ Dia : Factor w/ 20 levels "Dia 1","Dia 10",..: 1 12 14 15 16 17 18 19 20 2 ...
## $ Observador 1: num 19 20 18 22 22 22 21 20 22 21 ...
## $ Observador 2: num 20 22 23 18 22 23 20 24 22 24 ...
```
Agora definimos nossas hipóteses
H0: Não há diferença entre os pares de observações dos pesquisadores;
HA: Há diferença entre os pares de observações dos pesquisadores;
Vamos sumarizar os dados grafica e estatitiscamente
```r
## par(mfrow = c(2, 1))
hist(aves$`Observador 1`,
xlab = "Observações",
ylab = "Frequência",
main = "Observador 1",
ylim = c(0, 10),
xlim = c(18, 25))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-94-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
```r
hist(aves$`Observador 2`,
xlab = "Observações",
ylab = "Frequência",
main = "Observador 2",
ylim = c(0, 10),
xlim = c(18, 25))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-94-2.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
```r
boxplot(aves$`Observador 1`,
aves$`Observador 2`,
names = c("Observador 1", "Observador 2"),
ylab = "Frequência de Observações")
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-95-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Repare que devido a mudança na forma da planilha tivemos que escrever o boxplot de maneira diferente, onde não mais utilizamos o til (~), mas inserimos o nome da planilha mais o operador matemático $ (cifrão) mais o nome da variável quantitativa que queremos representar, inserimos também outros 2 argumentos que são "names" com dois nomes concatenados pela função c() que representam as variáveis quantitativas na ordem em que foram inseridas e o argumento "ylab" que dá nome ao eixo y.
```r
summary(aves)
```
```
## Dia Observador 1 Observador 2
## Dia 1 : 1 Min. :18.00 Min. :18.00
## Dia 10 : 1 1st Qu.:20.00 1st Qu.:20.00
## Dia 11 : 1 Median :21.00 Median :22.00
## Dia 12 : 1 Mean :20.70 Mean :21.90
## Dia 13 : 1 3rd Qu.:21.25 3rd Qu.:23.25
## Dia 14 : 1 Max. :22.00 Max. :25.00
## (Other):14
```
Como podemos notar, devido a organização dos dados na planilha a função *summary()* já sumariza de maneira adequada nossos dados.
Em relação ao resumo dos nossos dados podemos observar que o observador 2 contabilizou um número maior de aves que o observador 1, mas será que a diferença no número de observações é nulo (0) ou é diferente. ou seja será que a média de observação entre os observadores é similar?
O teste-t pareado não aparesenta pressuposto quanto aos dados, porém como ele avalia a diferença entre dois grupos o pressuposto requerido é a normalidade da diferença dos dados. Vamos a nossa avaliação do pressuposto.
Primeiro vamos criar um objeto que consiste na diferença entre observadores
```r
diferenca <- aves$`Observador 1` - aves$`Observador 2`
```
Agora vamos realizar o teste de normalidade da diferença.
```r
shapiro.test(diferenca)
```
```
##
## Shapiro-Wilk normality test
##
## data: diferenca
## W = 0.98173, p-value = 0.9544
```
De acordo com o teste de Shapiro os dados são normais. Vamos a nossa avaliação pelo teste-t
```r
t.test(aves$`Observador 1`,
aves$`Observador 2`,
paired = TRUE,
conf.level = 0.95)
```
```
##
## Paired t-test
##
## data: aves$`Observador 1` and aves$`Observador 2`
## t = -2.1608, df = 19, p-value = 0.04369
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -2.36237491 -0.03762509
## sample estimates:
## mean of the differences
## -1.2
```
Para a execução do teste-t pareado 2 diferenças podem ser notadas na escrita da função. A primeira consiste no fato de que não utilizamos o til (~), mas sim as variáveis referentes as observações e a segunda é o argumento paired que tem valor lógico (ou seja, verdadeiro ou falso) e indicamos ele como "TRUE" (verdadeiro).
Quanto ao resultado podemos notar que nos é informado que o teste consiste num teste-t pareado e que a diferença entre os observadores é ligeiramente diferente a um nível de confiança de 95%, visto que o "p-value" é próximo à 0,05 e na última linha nos é indicado que a média da diferença das observações é de -1,2. Em outras palavras o teste nos diz que a média das diferenças é diferente de 0, portanto rejeitamos a hipótese nula.
Assim como fizemos anteriormente vamos olhar o resultado em relação a distribuição função de densidade do teste-t. Só devemos lembrar de carregar o pacote "webr" se ainda não foi carregado.
```r
library(webr)
plot(t.test(aves$`Observador 1`,
aves$`Observador 2`,
paired = TRUE,
conf.level = 0.95))
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-100-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Neste teste em particular como trabalhamos com a diferença entre as observações vamos usar o gráfico de barras para graficar essa diferença.
```r
barplot(diferenca,
xlab = "Dias",
ylab = "Diferença entre observadores (Observador 1 - Observador 2)",
main = "Meu gráfico",
names.arg = aves$Dia,
las = 2,
ylim = c(-7.3, 7.3),
cex.names = 0.9)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-101-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
No comando gráficos acima estamos indicando que faremos um gráfico de barras, onde o que será plotado é a diferença no número de observação de aves entre observadores, o argumento "xlab" indica o nome do eixo x, "ylab" o nome do eixo y, "main" indica o título do gráfico, "names.arg" indica a coluna referente aos nomes das barras (que são os dias), "las" indica se os nomes das barras serão plotados na horizontal ou vertical (o valor 2 indica vertical), "ylim" indica os limites do eixo y e "cex.names" indica o tamanho da letra dos nomes das barras.
As barras para o lado positivo do eixo y indica uma maior observação de aves pelo observador 1 e as barras para baixo indicam um maior número de observações de aves pelo observador 2. Vamos indicar isso no gráfico por meio da função mtext().
```r
barplot(diferenca,
xlab = "Dias",
ylab = "Diferença entre observadores (Observador 1 - Observador 2)",
main = "Meu gráfico",
names.arg = aves$Dia,
las = 2,
ylim = c(-7.3, 7.3),
cex.names = 0.9)
mtext(at = 4,
line = -2,
text = "Observador 1",
side = 3)
mtext(at = 4,
line = -2,
text = "Observador 2",
side = 1)
```
```{=openxml}
<w:p><w:pPr><w:jc w:val="center"/><w:pStyle w:val="Figure"/></w:pPr><w:r><w:rPr/><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="4572000" cy="3657600"/><wp:docPr id="" name=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="" name=""/><pic:cNvPicPr><a:picLocks noChangeAspect="1" noChangeArrowheads="1"/></pic:cNvPicPr></pic:nvPicPr><pic:blipFill><a:blip r:embed="livroR-1.0_files/figure-docx/unnamed-chunk-102-1.png"/><a:srcRect/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr bwMode="auto"><a:xfrm><a:off x="0" y="0"/><a:ext cx="63500" cy="50800"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:noFill/></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>
```
Como podem ver a função *mtext()* indicou os nomes Observador 1 e Observador 2 no lado do gráfico que os representa. O argumento "at" indica a posição em relação ao eixo x, "line" indica a posição em relação ao eixo y, text indica o que será plotado e side indica o lado da janela gráfica onde o texto será plotado (3 é na parte superior e 1 na inferior).
<!--chapter:end:04-application.Rmd-->
# Final Words
We have finished a nice book.
<!--chapter:end:05-summary.Rmd-->
<!--chapter:end:06-references.Rmd-->
|
Java
|
UTF-8
| 3,800
| 4.375
| 4
|
[] |
no_license
|
/*
* #19. Remove Nth Node From End of List
*
* Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
1st Approach: Two pass
Using dummy node to avoid edge cases error
1. One pass to find the length of a LL
2. Second pass to go till (L-N)th node and update its next pointer (delete Nth node from end of a LL)
2nd Approach: One pass
Using two pointers p1 and p2 in one pass
Using dummy node to avoid edge cases error (e.g: [1] input will fail at p1.next = p1.next.next)
*/
/*
* Time Complexity in two pass: O (n + n) -> O (2N) -> O (N) // One pass for finding length of LL
* // Another pass for going till (L-N)th node and updating its next pointer
*
* Time Complexity in one pass: O (N) -> just one pass to delete the Nth node from end of a LL
*
* Space Complexity: O (1) -> No extra space used
*
* Did this code successfully run on leetcode: Yes
*
* Any problem you faced while coding this: No
*
*/
package com.s30.edu.linkedlist1;
public class DeleteNodeFromEnd {
public ListNode removeNthFromEnd(ListNode head, int n) {
/************* Two Pass Approach ****************/
// Base condition
/*if(head == null){
return null;
}*/
/*
* Two Pass Approach
*/
// Find the length of a LL
// First pass
// We will use the dummy node to avoid any outofbounds/nullpointer exceptions
// e.g: [1] -> expected output = []. In this case we will get error at curr.next = curr.next.next since it will go out of bounds w/o using dummy node
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode curr = head;
int length = 0;
// Find the length of LL
while(curr != null){
length++;
curr = curr.next;
}
// Second pass
// Traverse till (length-N)th node and update its next pointer(delete Nth node from end)
// Reset the current node to dummy node
curr = dummy;
// Traverse till (l-n)th node
length -= n;
while(length > 0){
length--;
curr = curr.next;
}
// Update the next pointer of current node (delete the nth node from end)
curr.next = curr.next.next;
/************* One Pass Approach **************/
// 1. Base condition
if(head == null){
return null;
}
// 2. Initialize the dummy node to avoid edge cases error
ListNode dummyNode = new ListNode(-1);
// 3. Connect dummy node to head node
dummyNode.next = head;
// 4. Initialize P1 and P2 pointers
ListNode p1 = dummyNode;
ListNode p2 = dummyNode;
// 5. Increment the P2 pointer by 'n'
while(n > 0){ // Check for p2 != null in case if 'n' is invalid
p2 = p2.next;
n -= 1;
}
// 6. Increment P1 and P2 both pointers simultaneously until P2 is the last element in LL (P2.next != null)
while(p2.next != null){
p1 = p1.next;
p2 = p2.next;
}
// 7. Update the next of P1 to P1.next.next
p1.next = p1.next.next;
// 8. Return the dummy.next as head node
// If we return head then will get error as first node is dummy node
return dummyNode.next;
}
}
|
Markdown
|
UTF-8
| 9,130
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
# Deuteronomy 32
[[Deut-31|← Deuteronomy 31]] | [[Deuteronomy]] | [[Deut-33|Deuteronomy 33 →]]
***
###### v1
Hỡi trời, hãy nghe ta nói. Hỡi đất, hãy lắng tai nghe lời ta.
###### v2
Lời giáo huấn của ta rơi xuống như mưa; lời ta rớt xuống như sương. Chúng giống như mưa rào trên cỏ; và đổ xuống như mưa trên cây non.
###### v3
Ta sẽ loan báo danh của CHÚA. Hãy ca ngợi Thượng Đế vì Ngài cao cả!
###### v4
Ngài như khối đá; mọi điều Ngài làm đều hoàn hảo, Ngài luôn luôn công bằng. Ngài là Thượng Đế thành tín, không bao giờ làm quấy, Ngài là Đấng chính trực công bình.
###### v5
Chúng đã làm điều ác chống nghịch Ngài. Chúng không trung thành với Ngài; Chúng quanh quẹo và dối trá.
###### v6
Các ngươi trả ơn CHÚA như thế sao, hỡi dân ngu dại và thiếu hiểu biết? Ngài là Cha và là Đấng Tạo Hoá ngươi, Đấng đã dựng nên và tạo thành ngươi.
###### v7
Hãy nhớ lại ngày xưa. Hãy suy nghĩ lại những năm qua. Hãy bảo cha ngươi kể cho ngươi nghe; Hỏi các bô lão, họ sẽ thuật cho ngươi biết;
###### v8
Đấng Chí Cao đã ban đất cho các dân tộc, phân chia các chủng tộc. Ngài định ranh giới cho các dân theo số của dân tộc Ít-ra-en.
###### v9
CHÚA chọn dân Ngài làm phần mình, và chọn dân tộc Gia-cốp làm của riêng Ngài.
###### v10
Ngài tìm thấy họ trong một sa mạc đầy giông gió và hoang vu. Ngài đùm bọc họ và nuôi dưỡng họ, Bảo vệ họ như người yêu dấu.
###### v11
Ngài như chim ưng xây tổ và vỗ cánh trên các chim con. Nó giương cánh ra đỡ các chim con và mang chúng trên cánh mình.
###### v12
Chỉ một mình CHÚA dẫn dắt họ, không có thần ngoại quốc nào giúp đỡ Ngài.
###### v13
CHÚA mang họ lên các đỉnh cao của xứ và dùng trái cây trong đồng nuôi dưỡng họ. Ngài cho họ ăn mật ong nơi tảng đá, Lấy dầu ra từ tảng đá cứng.
###### v14
Họ có sữa đông do bò cái sản xuất và sữa ra từ bầy gia súc; có chiên và dê mập béo. Có chiên và dê từ Ba-san cùng lúa mì tốt nhất. Các ngươi uống rượu nho.
###### v15
Ít-ra-en trở nên mập béo và đạp đá lung tung; chúng mập mạp và rắn chắc. Chúng rời bỏ Thượng Đế là Đấng dựng nên mình và từ bỏ Tảng Đá đã cứu mình.
###### v16
Chúng dùng các thần ngoại quốc để khiến Thượng Đế ghen tức và nổi giận với những tượng chạm đáng ghê tởm.
###### v17
Chúng dâng sinh tế cho yêu quỉ, không phải cho Thượng Đế, cho những thần chúng không hề biết, những thần từ các xứ quanh đó, thần mà tổ tiên chúng nó không sợ.
###### v18
Các ngươi đã bỏ Thượng Đế là Khối Đá, Cha các ngươi, và quên Thượng Đế Đấng đã sinh các ngươi ra.
###### v19
CHÚA thấy điều nầy và từ bỏ chúng; các con trai con gái Ngài đã chọc giận Ngài.
###### v20
Ngài bảo, "Ta sẽ quay mặt khỏi chúng nó để xem chúng nó ra sao. Chúng nó là dân gian ác, là con cái phản nghịch.
###### v21
Chúng dùng những vật không phải là thần để làm ta ganh tức, dùng những tượng chạm không ra gì để chọc giận ta. Cho nên ta sẽ dùng những người không phải là dân ta để khiến chúng nó ganh tức; Ta sẽ dùng một dân không hiểu biết đế khiến chúng tức giận.
###### v22
Cơn giận ta đã bốc lửa, cháy phừng xuống đến tận chỗ kẻ chết ở. Ta sẽ thiêu đốt đất đai và mùa màng, Ta sẽ đốt chân núi.
###### v23
Ta sẽ chồng chất khốn khổ lên trên đầu chúng và bắn các mũi tên vào chúng.
###### v24
Chúng sẽ chết đói và bệnh hoạn, bị các dịch lệ tiêu diệt. Ta sẽ sai ác thú đến với chúng và rắn độc cũng lướt tới.
###### v25
Trong phố sẽ có gươm giáo; trong nhà chúng sẽ có sự kinh hoàng. Thanh niên, thiếu nữ sẽ chết, Hài nhi và người già cả cũng đồng chung số phận.
###### v26
Ta sẽ phân tán chúng ra như ta nói, sẽ không còn ai nhớ tới chúng nữa.
###### v27
Nhưng ta không muốn kẻ thù chúng huênh hoang; vì kẻ thù chúng sẽ lầm tưởng và khoe khoang rằng, 'Chúng ta đã thắng rồi! CHÚA không có đóng vai trò gì trong việc nầy cả.'
###### v28
Ít-ra-en không hiểu biết; chúng chẳng có trí hiểu gì.
###### v29
Ta ước gì chúng khôn ngoan và hiểu điều nầy; Ước gì chúng có thể thấy số phận chúng ra sao.
###### v30
Một người không đánh đuổi nổi một ngàn người, hai người không đánh đuổi nổi mười ngàn người vì Khối Đá của chúng bán đứng chúng, và vì CHÚA từ bỏ chúng.
###### v31
Khối đá của các dân đó không phải như Khối Đá của chúng ta; các kẻ thù chúng ta cũng công nhận như thế.
###### v32
Dây nho của chúng là từ Xô-đôm mà ra, và đồng ruộng chúng như Gô-mô-rơ. Trái nho chúng đầy nọc độc; Chùm nho chúng rất đắng.
###### v33
Rượu chúng như nọc rắn, như nọc độc rắn hổ mang.
###### v34
Ta đã để dành điều nầy, và khóa cất trong kho ta.
###### v35
Ta sẽ trừng phạt những kẻ làm quấy, ta sẽ báo trả chúng. Trước sau bước chân chúng sẽ vấp ngã, vì ngày khốn đốn chúng đã gần kề, và sự hình phạt chúng sẽ đến rất nhanh."
###### v36
CHÚA sẽ bênh vực dân Ngài và tỏ lòng nhân ái đối với tôi tớ Ngài. Ngài sẽ khiến cho sức mạnh nó tiêu tan, không còn ai sống sót, từ tôi mọi đến người tự do.
###### v37
Rồi Ngài sẽ hỏi, "Các thần chúng nó đâu? Tảng đá mà chúng ỷ lại đâu rồi?
###### v38
Ai là kẻ ăn mỡ từ các của lễ chúng hoặc uống rượu từ của lễ uống của chúng? Các thần đó hãy đến giúp ngươi đi! Hãy nhờ chúng bảo vệ ngươi đi!
###### v39
Bây giờ ngươi sẽ biết rằng ta là Thượng Đế duy nhất! Không có thần nào khác ngoài ta. Ta sai sự sống và sự chết đến; Ta làm cho bị thương, rồi ta chữa lành. Không ai thoát khỏi tay ta.
###### v40
Ta giơ tay lên trời và thề quyết như sau: Vì rằng ta hằng sống,
###### v41
Ta sẽ mài gươm sáng loáng của ta, ta sẽ cầm gươm trong tay mà phân xử. Ta sẽ trừng phạt kẻ thù ta và báo trả kẻ ghét ta.
###### v42
Máu của chúng sẽ dính đầy các mũi tên ta; gươm ta sẽ ăn thịt chúng. Huyết sẽ chảy từ những kẻ bị giết và kẻ bị bắt làm tù. Các lãnh tụ của kẻ thù sẽ bị chém đầu.
###### v43
Hãy vui lên, hỡi các dân, cùng với dân Ngài vì Ngài sẽ trả thù các ngươi về huyết của các tôi tớ Ngài. Ngài sẽ trừng phạt các kẻ thù mình, và Ngài sẽ cất tội lỗi của đất và của dân Ngài."Mô-se dạy cho dân chúng hát bài nầy
###### v44
Mô-se và Giô-suê con của Nun phổ biến mọi lời của bài ca nầy cho dân chúng nghe.
###### v45
Sau khi Mô-se nói những lời đó cho toàn thể dân Ít-ra-en xong,
###### v46
thì ông bảo họ: "Hãy ghi tạc mọi lời ta nói với các ngươi hôm nay, và dặn con cái các ngươi vâng giữ mọi luật lệ nầy.
###### v47
Đây không phải là những lời tầm thường mà là những lời sống cho các ngươi! Nhờ những lời nầy các ngươi sẽ sống lâu trong xứ mà ngươi sẽ nhận làm sản nghiệp sau khi băng qua sông Giô-đanh."Mô-se lên núi Nê-bô
###### v48
Cùng ngày đó CHÚA lại nói cùng Mô-se như sau,
###### v49
"Hãy lên núi A-ba-rim, đến ngọn núi Nê-bô trong xứ Mô-áp, đối ngang Giê-ri-cô. Hãy nhìn toàn xứ Ca-na-an mà ta sẽ ban cho dân Ít-ra-en làm sản nghiệp.
###### v50
Ngươi sẽ qua đời và về cùng tổ tiên trên ngọn núi mà ngươi sẽ leo lên như anh ngươi là A-rôn đã chết trên núi Hô-rơ và về cùng tổ tiên.
###### v51
Cả hai ngươi đã phạm tội cùng ta trong các suối Mê-ri-ba Ca-đe trong sa mạc Xin, còn ngươi không tôn thánh ta trước mặt dân Ít-ra-en.
###### v52
Bây giờ ngươi chỉ được nhìn xứ đó từ đàng xa mà thôi. Ngươi sẽ không được vào đất mà ta sẽ ban cho dân Ít-ra-en."
***
[[Deut-31|← Deuteronomy 31]] | [[Deuteronomy]] | [[Deut-33|Deuteronomy 33 →]]
|
Java
|
UTF-8
| 5,137
| 3.296875
| 3
|
[] |
no_license
|
package webcrawler;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.jsoup.*;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
*
* @author atindramardikar
*/
public class WebCrawler {
static int level = 1; // To check the depth of the crawler
static int totalUrl = 1000;
static int noofUrl; // to check number of unique URLs
static int globalFlag = 0; // Ensures that all the links of a level are visited and no new level file is created before that
static Set<String> finallist = new HashSet<>(1000); // Contains the final list of URLs
public static void main(String[] args) throws IOException {
File file = new File("level1.txt");
// remove the keyphrase and provide blank to implement normal crawler
crawler("http://en.wikipedia.org/wiki/Hugh_of_Saint-Cher", "level1.txt", "concordance"); //passsing first arguments to the crawler function
finalList();
}
// This is the actual crawler implementation
static void crawler(String url, String filename, String keyphrase) throws IOException {
org.jsoup.nodes.Document doc = null;
org.jsoup.nodes.Document doc1 = null;
FileWriter fw = new FileWriter(filename, true);
try {
Thread.sleep(100);// delay of 1 sec between request to web servers
doc = Jsoup.connect(url).get(); // fetching the web page contents
if (doc != null) // validating the existence of web page and checking its contents for keyphrase
{
String str;
Elements tags = doc.select("a[href]"); // Selecting links from web page content
for (Element link : tags) {
int count = 0;
char Check = ':';
str = link.attr("abs:href").toString();
//checking if colon is not present in rest of URL
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == Check) {
count++;
}
}
// checking for english pages and that crawler does visits the wiki main page
if (str.contains("en.wikipedia.org") && !str.contains("Main_Page")) {
if (count == 1 && noofUrl < totalUrl) {
org.jsoup.nodes.Document doc11 = Jsoup.connect(str).get();
//Checking for key phrase in the content of the web page
if (doc11.body().text().contains(keyphrase)) {
//checks if no duplicate entry is added
fw.write(str);
fw.write("\n");
if (finallist.add(str)) {
noofUrl++; //Increment the number of URLs if the non-duplicate entry gets added
//to keep track of number of URLs so as to stop ater 1000 unique URLS
}
}
}
}
}
fw.close();
}
} catch (Exception ex) {
}
if (globalFlag == 0) {
newLevel(filename, keyphrase);
}
}
//Function that creates a new level file after all links from a particular level are visited
static void newLevel(String filename, String keyphrase) throws FileNotFoundException, IOException {
level++;
// building the file name according to the level
StringBuilder sb = new StringBuilder();
sb.append("level");
sb.append(level);
sb.append(".txt");
String newfile = sb.toString();
File file = new File(newfile);
parsing(filename, newfile, keyphrase);
}
//Funtion to parse a file of paarticular level
static void parsing(String filename, String newfile, String keyphrase) throws FileNotFoundException, IOException {
String str;
if (level <= 5 && noofUrl < totalUrl) {
globalFlag = 1;
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
//Parser
while ((str = br.readLine()) != null) {
crawler(str, newfile, keyphrase); // Calls the crawler function for every link in the file of a particular level
}
globalFlag = 0;
newLevel(newfile, keyphrase);
}
}
//Funtion to crate a final.txt file containing 1000 unique URLs or Unique urls after level 5 is reached
static void finalList() throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("final.txt"));
for (String urls : finallist) {
bw.write(urls);
bw.newLine();
}
bw.close();
}
}
|
Python
|
UTF-8
| 1,752
| 3.296875
| 3
|
[] |
no_license
|
# This file was used as a tool to help find a projectively primitive polynomial.
# These polynomials are useful for generating full cycle pseudo random number generators.
poly = [-1,0,2]
import math
N = 5
inv = [0,1,3,2,4]
sqrs = set([1,4])
def printp(p):
print p[0],
for i in range(1,len(p)):
if p[i] != 0:
print str(p[i])+ "x^" +str(i),
print
def polyadd(p1,p2,n):
ret = []
for i in range(0, max(len(p1),len(p2))):
ret.append(0)
p1.append(0)
p2.append(0)
ret[i] = (p1[i]+ p2[i]) % n
return ret
def polymult(p1,p2,n):
ret = []
for i in range(0, len(p1)+len(p2)-1):
ret.append(0)
for i in range(0, len(p1)):
for j in range(0, len(p2)):
ret[i+j] += (p1[i] * p2[j]) % n
return ret
def irreducible2(p):
val = p[1] - 4*p[2]*p[0] % N
return val not in sqrs
def simplify(p,ref):
if(p[2] == 0):
return p
else:
a = ref[2]
d = p[2]
ratio = -1 * d * inv[a]
replace = polymult([ratio],ref,N)
replace[2] = 0
p[2] = 0
return polyadd(p,replace,N)
def primpoly(p):
if not irreducible2(p):
print "reducible"
return False
check = [0,1]
printp(check)
for x in xrange(0,4):
check = polymult(check,[0,1],N)
check = simplify(check,p)
printp(check)
if(check[1] == 0):
return False
return True
# for c in xrange(0,5):
# for b in xrange(0,5):
# for a in xrange(1,5):
# if primpoly([a,b,c]):
# print "*****", a,b,c, "*****"
# else:
# print "////", a,b,c, "////"
# primpoly([1,4,4])
print simplify([0,0,1],[3,1,4])
|
Java
|
UTF-8
| 2,049
| 2.375
| 2
|
[
"MIT"
] |
permissive
|
package com.zcwfeng.fastdev.ui.fragment.image.glide;
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.module.GlideModule;
public class CustomCachingGlideModule implements GlideModule {
@Override
public void applyOptions(Context context, GlideBuilder builder) {
// 第一种 如果你认为你的应用程序需要缓存比滑翔的默认值大20%,计算使用上面的变量
// MemorySizeCalculator calculator = new MemorySizeCalculator(context);
// int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
// int defaultBitmapPoolSize = calculator.getBitmapPoolSize();
//
// int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
// int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);
//
// builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
// builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));
// 第二种 Customize Disk Cache
// set size & external vs. internal
int cacheSize100MegaBytes = 104857600;
builder.setDiskCache(
new InternalCacheDiskCacheFactory(context, cacheSize100MegaBytes)
);
//builder.setDiskCache(
//new ExternalCacheDiskCacheFactory(context, cacheSize100MegaBytes));
}
@Override
public void registerComponents(Context context, Glide glide) {
// nothing to do here
}
// use demo
/*
// or any other path
String downloadDirectoryPath = Environment.getDownloadCacheDirectory().getPath();
builder.setDiskCache(
new DiskLruCacheFactory( downloadDirectoryPath, cacheSize100MegaBytes )
);
// In case you want to specify a cache sub folder (i.e. "glidecache"):
//builder.setDiskCache(
// new DiskLruCacheFactory( downloadDirectoryPath, "glidecache", cacheSize100MegaBytes )
//);
*/
}
|
Swift
|
UTF-8
| 584
| 2.703125
| 3
|
[] |
no_license
|
//
// FullProductCell.swift
// CollectionViewApp2
//
// Created by Кирилл on 21.08.2021.
//
import UIKit
class FullProductCell: UICollectionViewCell {
@IBOutlet var productImage: UIImageView!
@IBOutlet var productName: UILabel!
@IBOutlet var productPrice: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setupCell(product:Product){
self.productImage.image = product.image
self.productName.text = product.name
self.productPrice.text = "\(product.price)"
}
}
|
JavaScript
|
UTF-8
| 2,259
| 2.515625
| 3
|
[] |
no_license
|
import React from "react";
import Product from "./product";
import { connect } from "react-redux";
import * as actionCreator from "./store/action/action"
class ListItem extends React.Component {
constructor(props) {
super(props);
this.query = `query products {
products {
id
name
description
rating
price
images {
url
alt
}
}
}`;
}
componentDidMount() {
this.props.onfetchData('https://graph-api-shopingcart.herokuapp.com/',this.query)
}
render() {
const arData = this.props.products;
const arrayCart = this.props.productQuality
let thisQuality;
const onCheckQuality = (id,quality) => {
this.props.onCheckQuality(id,quality)
}
return (
<div>
<div className="listProduct" >
{Object.keys(arData).map(function (key, index) {
return (
<Product
type="productlist"
key={arData[index].id}
productID={arData[index].id}
productName={arData[index].name}
productImage={arData[index].images[0].url}
productPrice={arData[index].price}
btnAddToCart={(id,quality) => onCheckQuality(id,quality)}
producQuality={thisQuality}
/>
)
})}
</div>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
products: state.productRD.products,
productQuality: state.cartRD.cartList,
}
}
const mapDispatchToProps = dispatch => {
return {
onfetchData: (url,query) => dispatch(actionCreator.fetchData(url,query)),
onCheckQuality: (idProduct,quality) => dispatch(actionCreator.checkQuality(idProduct,quality))
}
}
export default connect(mapStateToProps,mapDispatchToProps)(ListItem);
|
TypeScript
|
UTF-8
| 664
| 4
| 4
|
[] |
no_license
|
// // 1.
// const announcement = "Hello World!";
// // How quickly can you spot the typos?
// // announcement.toLocaleLowercase();
// // announcement.toLocalLowerCase();
// // We probably meant to write this...
// console.log(announcement.toLocaleLowerCase());
// // 2.
// function greet(person: string, date: Date) {
// console.log(`Hello ${person}, today is ${date.toDateString()}!`);
// }
// //greet("Maddison", Date());
// greet("Maddison", new Date());
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
}
|
Java
|
UTF-8
| 1,609
| 2.28125
| 2
|
[] |
no_license
|
package com.ai.eis.common;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* <p>****************************************************************************</p>
* <p><b>Copyright © 2010-2017 soho team All Rights Reserved<b></p>
* <ul style="margin:15px;">
* <li>Description : cn.gson.crm.common</li>
* <li>Version : 1.0</li>
* <li>Creation : 2017年07月04日</li>
* <li>Author : 郭华</li>
* </ul>
* <p>****************************************************************************</p>
*/
public class ImUser {
private long uid;
private String realName;
public ImUser() {
}
public ImUser(long uid, String realName) {
this.uid = uid;
this.realName = realName;
}
public void setUid(long uid) {
this.uid = uid;
}
public long getUid() {
return uid;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getRealName() {
return realName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImUser user = (ImUser) o;
return new EqualsBuilder()
.append(uid, user.uid)
.append(realName, user.realName)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(uid)
.append(realName)
.toHashCode();
}
}
|
JavaScript
|
UTF-8
| 1,170
| 3.734375
| 4
|
[] |
no_license
|
function Complex(real, imaginary) {
if (isNaN(real) || isNaN(imaginary)) // Ensure that both args are numbers.
throw new TypeError();
this.r = real;
this.i = imaginary;
}
Complex.prototype.add = function(that) {
return new Complex(this.r + that.r, this.i + that.i);
};
Complex.prototype.mul = function(that) {
return new Complex(this.r * that.r - this.i * that.i, this.r * that.i + this.i * that.r);
};
Complex.prototype.mag = function() {
return Math.sqrt(this.r*this.r + this.i*this.i);
};
Complex.prototype.neg = function() {
return new Complex(-this.r, -this.i);
};
Complex.prototype.toString = function() {
return "{" + this.r + "," + this.i + "}";
};
Complex.prototype.equals = function(that) {
return that != null && that.constructor === Complex && this.r === that.r && this.i === that.i;
};
Complex.ZERO = new Complex(0,0);
Complex.ONE = new Complex(1,1);
// ---------------------------------------------------
var c1 = new Complex(3, 4);
var c2 = new Complex(c1.r, c1.i);
console.log(c1.add(c2).toString());
console.log(c1.equals(c2));
console.log(c1.mag());
console.log(c1.add(Complex.ONE).toString());
|
Go
|
UTF-8
| 3,109
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package command
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/openebs/maya/pkg/util"
"github.com/openebs/maya/types/v1"
)
type Client interface {
GetVolAnnotations(string) (*Annotations, error)
}
// Annotations describes volume struct
type Annotations struct {
TargetPortal string `json:"vsm.openebs.io/targetportals"`
ClusterIP string `json:"vsm.openebs.io/cluster-ips"`
Iqn string `json:"vsm.openebs.io/iqn"`
ReplicaCount string `json:"vsm.openebs.io/replica-count"`
ControllerStatus string `json:"vsm.openebs.io/controller-status"`
ReplicaStatus string `json:"vsm.openebs.io/replica-status"`
VolSize string `json:"vsm.openebs.io/volume-size"`
ControllerIP string `json:"vsm.openebs.io/controller-ips"`
Replicas string `json:"vsm.openebs.io/replica-ips"`
}
const (
timeout = 5 * time.Second
)
// getVolDetails gets response in json format of a volume from m-apiserver
func GetVolDetails(volName string, obj interface{}) error {
addr := os.Getenv("MAPI_ADDR")
if addr == "" {
err := util.MAPIADDRNotSet
fmt.Printf("error getting env variable: %v", err)
return err
}
url := addr + "/latest/volumes/info/" + volName
client := &http.Client{
Timeout: timeout,
}
resp, err := client.Get(url)
if err != nil {
fmt.Printf("Could not get response, found error: %v", err)
return err
}
if resp != nil {
if resp.StatusCode == 500 {
fmt.Printf("Volume: %s not found at M_API server\n", volName)
return errors.New("Internal Server Error")
} else if resp.StatusCode == 503 {
fmt.Println("M_API server not reachable")
return errors.New("Service Unavailable")
} else if resp.StatusCode == 404 {
fmt.Printf("Volume: %s not found at M_API server\n", volName)
return errors.New("Page Not Found")
}
} else {
fmt.Println("M_API server not reachable")
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(obj)
}
// GetVolAnnotations maps annotations of volume to Annotations structure.
func (annotations *Annotations) GetVolAnnotations(volName string) error {
var volume v1.Volume
err := GetVolDetails(volName, &volume)
if err != nil || volume.ObjectMeta.Annotations == nil {
if volume.Status.Reason == "pending" {
fmt.Println("VOLUME status Unknown to M_API server")
}
return err
}
for key, value := range volume.ObjectMeta.Annotations {
switch key {
case "vsm.openebs.io/volume-size":
annotations.VolSize = value
case "vsm.openebs.io/iqn":
annotations.Iqn = value
case "vsm.openebs.io/replica-count":
annotations.ReplicaCount = value
case "vsm.openebs.io/cluster-ips":
annotations.ClusterIP = value
case "vsm.openebs.io/replica-ips":
annotations.Replicas = value
case "vsm.openebs.io/targetportals":
annotations.TargetPortal = value
case "vsm.openebs.io/controller-status":
annotations.ControllerStatus = value
case "vsm.openebs.io/replica-status":
annotations.ReplicaStatus = value
case "vsm.openebs.io/controller-ips":
annotations.ControllerIP = value
}
}
return nil
}
|
Markdown
|
UTF-8
| 3,805
| 2.6875
| 3
|
[] |
no_license
|
## If a Maine Coon Could Write a Dissertation, Evidence Suggests He Would Do So in Russian
* Originally posted at http://acephalous.typepad.com/acephalous/2008/05/if-a-maine-coon.html
* Monday, May 05, 2008
From my Twain chapter:
êéèêéèęŗřśŝşşşşşşşşşşşşşşşşşš ōõôğĝĝĝĝĝĝĝĝĝĝĝĝĝĝġ ььььььььььęŗřś ğĝōõôôôôôôôôôôôôôôô
What is he trying to tell me, [Mikhail](http://pervegalit.wordpress.com/)?
* * *
### 4 Comments
[]()

I didn't know you had a Maine coon. We picked up a lovely fellow in Ohio who we think is part Maine coon. He started visiting us in the dead of winter, hanging outside the back door, visiting our two cats. His nose was bloody, we took him in, and it's been love and tumbleweeds of lose fur since.
Thing is, he's not much of a typer. His two brothers, on the other hand, are Microsoft Word experts. They've managed to learn all sorts of shortcuts for deleting entire pages, for setting the margins at 1000 inches, for changing the font language, and for communicating such things as, "asdsdsddasdsdasd" and "jnjnkjjkjnjjknjnkjjk." Even Joyce's cat could only muster a measely "Mrkgnao." Then again, that was by longhand.
But my impression is that Maine coons are full of Christ love. Ours is the living embodiment of non-violence (except to toy birds and insects) and cosmic sweetness. He is full of Buddha Nature, even when his brothers leap on his back and try to ride him through the living room.
Posted by:
Luther Blissett |
[Monday, 05 May 2008 at 09:52 AM](http://acephalous.typepad.com/acephalous/2008/05/if-a-maine-coon.html?cid=113362512#comment-6a00d8341c2df453ef00e5522694168834)
[]()

i'm glad you asked, Scott! unfortunately i can only help you out with a part of this clearly mysterious and significant message:
ьььььььььь
this letter is a so-called "soft mark" that is added to a consonant to make the sounds, well, soft. taking that there are 10 soft marks here - something that is grammatically impossible yet strangely awesome - i think it means something like: "In light of the harsh realities of life, consider a softer, much softer, approach to it..."
Posted by:
[Mikhail Emelianov](http://pervegalit.wordpress.com) |
[Monday, 05 May 2008 at 10:44 AM](http://acephalous.typepad.com/acephalous/2008/05/if-a-maine-coon.html?cid=113368638#comment-6a00d8341c2df453ef00e55226b1e48834)
[]()

Ten soft marks are two cat paws
Parking punctuated without claws
Posted by:
Rich Puchalsky |
[Monday, 05 May 2008 at 12:43 PM](http://acephalous.typepad.com/acephalous/2008/05/if-a-maine-coon.html?cid=113384002#comment-6a00d8341c2df453ef00e55226e3828834)
[]()

Luther, sadly, my sweet Virgil's not full of Buddha Nature. [In fact](http://acephalous.typepad.com/dadevil.jpg) ...
Mikhail! Bless you for answering my quasi-insulting insinuation! That said, yes, he is all about the sort, terroristic softness. He lulls us into unthought with his silky softness, then suicide-bombs the medicine cabinet! (Which he opens and ransacks himself!)
Posted by:
[SEK](http://acephalous.typepad.com/) |
[Monday, 05 May 2008 at 08:28 PM](http://acephalous.typepad.com/acephalous/2008/05/if-a-maine-coon.html?cid=113444976#comment-6a00d8341c2df453ef00e5521085a08833)
|
C#
|
UTF-8
| 2,231
| 2.84375
| 3
|
[] |
no_license
|
using Petrol_Pump_Point_Of_Sale_System.Core.Repositories;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Petrol_Pump_Point_Of_Sale_System.Models;
namespace Petrol_Pump_Point_Of_Sale_System.Persistence.Repositories
{
public class UserRepository : Repository<User> , IUserRepository
{
public UserRepository(DatabaseContext context)
: base(context)
{
}
public IEnumerable<User> SearchUsers(string searchValue)
{
return DatabaseContext.Users.Where(u => u.Username.Contains(searchValue)).ToList();
}
public IEnumerable<dynamic> GetAllUsers(bool status = true)
{
return DatabaseContext.Users
.Where(u => u.IsActive == status)
.Select(u => new
{
u.Id,
u.Username,
u.Name,
Role = u.Role.UserRoleName
}).ToList();
}
public bool Login(string username, string password)
{
return DatabaseContext.Users
.Count(u => u.Username == username &&
u.Password == password &&
u.IsActive) == 1;
}
public async Task<User> CheckLoginUser(string username, string password)
{
return await
DatabaseContext.Users
.Where(u => u.Username == username &&
u.Password == password &&
u.IsActive).SingleOrDefaultAsync();
}
public bool UserNameAlreadyUsed(string userName)
{
return DatabaseContext.Users
.Count(u => u.Username == userName) == 1;
}
public bool UserNameAlreadyUsed(string userName, int id)
{
return DatabaseContext.Users
.Count(u => u.Username == userName && u.Id != id) == 1;
}
public DatabaseContext DatabaseContext
{
get { return Context; }
}
}
}
|
Python
|
UTF-8
| 4,197
| 2.640625
| 3
|
[] |
no_license
|
import argparse, socket, os, select, time
from threading import Thread
def create_srv_socket(address):
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(address)
listener.listen(64)
print('Listening at {}'.format(address))
return listener
def all_events_forever(poll_object):
while True:
for fd, event in poll_object.poll():
yield fd, event
def async_server(listener):
#fileno()返回文件描述符
sockets = {listener.fileno(): listener}
addresses = {}
bytes_received = {}#在等待某个请求完成时,会将受到的数据存储在bytes_received字典中。
bytes_to_send = {}#在等待操作系统安排发送数据时,会将要发送的字节存储在bytes_to_send字典中。
poll_object = select.poll()
poll_object.register(listener, select.POLLIN)
#fd数字代表连接的不同客户端
#event代表不同的事件
for fd, event in all_events_forever(poll_object):
sock = sockets[fd]
if event & (select.POLLHUP | select.POLLERR | select.POLLNVAL):
print("挂起|出错|无法读取\n")
address = addresses.pop(sock)#移除地址
rb = bytes_received.pop(sock, b'')#
sb = bytes_to_send.pop(sock, b'')
if rb:
print('Client {} sent {} but then closed'.format(address, rb))
elif sb:
print('Client {} closed before we sent {}'.format(address, sb))
else:
print('Client {} closed socket normally'.format(address))
print('-*' * 25 ," END ",'*-' * 25)
poll_object.unregister(fd)
del sockets[fd]
# New socket: add it to our data structures.
elif sock is listener:
print('-*' * 25 ,"START",'*-' * 25)
print("新套接字注册进poll\n")
time.sleep(15)
sock, address = sock.accept()
print('Accepted connection from {}'.format(address))
sock.setblocking(False) # force socket.timeout if we blunder
sockets[sock.fileno()] = sock
addresses[sock] = address
poll_object.register(sock, select.POLLIN)
# Incoming data: keep receiving until we see the suffix.
elif event & select.POLLIN:
print("读取数据\n")
time.sleep(15)
more_data = sock.recv(4096)
if not more_data: # end-of-file
sock.close() # next poll() will POLLNVAL, and thus clean up
continue
file = bytes_received.pop(sock, b'') + more_data
#此时data为文件名
if os.path.isfile(file):
fileSize = (os.stat(file)).st_size#文件大小
packageNum = int(fileSize / 4096) + 1#包个数
sock.sendall(str(packageNum).encode('utf8'))#先发送包的个数
#读取文件,放入字典bytes_to_send[sock]
GetRunS = open(file, "rb")
RunS = GetRunS.read()
bytes_to_send[sock] = RunS
GetRunS.close()
poll_object.modify(sock, select.POLLOUT)
else:
bytes_to_send[sock] = b'0'
poll_object.modify(sock, select.POLLOUT)
# Socket ready to send: keep sending until all bytes are delivered.
elif event & select.POLLOUT:
print("发送数据\n")
time.sleep(15)
data = bytes_to_send.pop(sock)
n = sock.send(data)
if n < len(data):
bytes_to_send[sock] = data[n:]
else:
poll_object.modify(sock, select.POLLIN)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="a description")
parser.add_argument('host', help='IP or hostname')
parser.add_argument('-p', metavar='port', type=int, default=1060,
help='TCP port (default 1060)')
args = parser.parse_args()
address = (args.host, args.p)
listener = create_srv_socket(address)
async_server(listener)
|
C++
|
UTF-8
| 979
| 3.8125
| 4
|
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
bool isSameStack(stack<string> stack1, stack<string> stack2)
{
bool flag = true;
if (stack1.size() != stack2.size())
{
flag = false;
return flag;
}
while (stack1.empty() == false)
{
if (stack1.top() == stack2.top())
{
stack1.pop();
stack2.pop();
}
else
{
flag = false;
break;
}
}
return flag;
}
int main()
{
stack<string> stack1;
stack<string> stack2;
stack1.push("Geeks");
stack1.push("4");
stack1.push("Geeks");
stack1.push("Welcomes");
stack1.push("You");
stack2.push("Geeks");
stack2.push("4");
stack2.push("Geeks");
stack2.push("Welcomes");
stack2.push("You");
if (isSameStack(stack1, stack2))
{
cout << "Stack are same";
}
else
{
cout << "Stack are not same";
}
return 0;
}
|
C++
|
UTF-8
| 905
| 3.234375
| 3
|
[] |
no_license
|
#include "CycleSort.hh"
#include "Ultility.hh"
CycleSort::CycleSort(int arr[], int size) {
CycleSorting(arr, size);
}
void CycleSort::CycleSorting(int arr[], int size) {
for(int i = 0; i < size - 1; i++) {
int checkVal = arr[i];
int checkIdx = i;
for (int j = i + 1; j < size; j++)
if (arr[j] < checkVal)
checkIdx++;
if (checkIdx == i) continue;
while (arr[checkIdx] == checkVal)
checkIdx++;
Ultility::Swap(arr[checkIdx], checkVal);
while (checkIdx != i) {
checkIdx = i;
for (int j = i + 1; j < size; j++)
if (arr[j] < checkVal)
checkIdx++;
while (arr[checkIdx] == checkVal)
checkIdx++;
Ultility::Swap(arr[checkIdx], checkVal);
}
}
}
|
TypeScript
|
UTF-8
| 605
| 2.859375
| 3
|
[] |
no_license
|
import * as app from "../app"
const command: app.Command = {
name: "turn",
botOwner: true,
description: "Turn on/off command handling",
positional: [
{
name: "mode",
description: "Power mode of bot. on/off",
default: () => (app.cache.ensure("turn", true) ? "off" : "on"),
checkValue: /^on|off$/,
required: true,
},
],
async run(message) {
const turn = message.positional.mode === "on"
app.cache.set("turn", turn)
return message.channel.send(
`Command handling ${turn ? "activated" : "disabled"} `
)
},
}
module.exports = command
|
PHP
|
UTF-8
| 708
| 2.65625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
<?php namespace SeatGeek\Sixpack\Response;
class Base
{
protected $response = null;
protected $meta = null;
public function __construct($jsonResponse, $meta)
{
$this->response = json_decode($jsonResponse);
$this->meta = $meta;
}
public function getSuccess()
{
return ($this->meta['http_code'] === 200);
}
public function getStatus()
{
return $this->meta['http_code'];
}
public function getCalledUrl()
{
return $this->meta['url'];
}
public function getClientId()
{
if (is_object($this->response)) {
+ return $this->response->client_id;
+ }
+ return null;
}
}
|
JavaScript
|
UTF-8
| 834
| 3.484375
| 3
|
[] |
no_license
|
let re;
re = /hello/;
re = /hello/i; // i = case insensitive
re = /hello/g; // Global search
console.log(re);
console.log(re.source);
// exec() - Return result in an array or null
const result = re.exec('hello world')
console.log(result)
console.log(result[0])
console.log(result.index)
console.log(result.input)
// test() - Returns true or false
const result = re.test('Hello')
console.log(result)
// match() Return result array or null
const str = 'Hello There';
const result = str.match(re)
console.log(result)
// search() - Returns index of the first match if not found returns -1
const str = 'John Hello There';
const result = str.search(re);
console.log(result)
// replace() - Return new string with some or all matches of a pattern
const str = 'Hello There';
const newStr = str.replace(re, 'Hi')
console.log(newStr)
|
JavaScript
|
UTF-8
| 3,334
| 2.8125
| 3
|
[] |
no_license
|
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function nextAction() {
$(".nextBtn").click(function(){
alert(window.localStorage.lockNum);
})
}
function load() {
var num = Number(window.localStorage.lockNum);//地锁个数
var statu = Number(window.localStorage.lockStatu);//地锁状态
creatLockView(num);
if (statu == 1) { //当为立起时 添加点击事件 控制地锁放下(解锁)
//1个地锁的情况
$('.LockSingle').bind("click", function(){
//这里发送放下地锁命令
$('.LockSingle .lockImgA').attr('src',lockStatus(2));
$('.LockSingle').unbind('click');//放下了地锁 取消点击绑定
})
//2个地锁的情况
$('.LockA').bind("click", function(){
//这里发送放下地锁命令
$('.LockA .lockImgA').attr('src',lockStatus(2));
$('.LockA').unbind('click');//放下了地锁 取消点击绑定
})
$('.LockB').bind("click", function(){
//这里发送放下地锁命令
$('.LockB .lockImgB').attr('src',lockStatus(2));
$('.LockB').unbind('click');//放下了地锁 取消点击绑定
})
}
}
addLoadEvent(load);
// 根据传入地锁个数groundLockNum 动态生成显示2个或者1个地锁的界面 如果地锁个数为0则跳过直接进入枪口选择状态
function creatLockView(num){
var html_LockView = "";
var statu = Number(window.localStorage.lockStatu);//地锁状态
var lockImgPathA = lockStatus(statu);
var lockImgPathB = lockStatus(statu);
if (num==2) {
html_LockView = "<div class=\"groundLock\">"+"<p style=\"text-align:center\">当前电桩支持地锁功能,<br/>请选择合适的地锁停车充电:</p>"
+"<ul class=\"lockBg\" style=\"list-style:none;\">"+
"<li class=\"LockA lock\">"+
"<div>"+
"<h5>地锁A</h5>"+
"<img class=\"lockImgA lockImg\" src=\""+lockImgPathA+"\">"+
"</div>"+
"</li>"+
"<li class=\"LockB lock\">"+
"<div>"+
"<h5>地锁B</h5>"+
"<img class=\"lockImgB lockImg\" src=\""+lockImgPathB+"\">"+
"</div>"+
"</li>"+
"</ul>"+
"</div>";
}
if (num == 1) {
html_LockView = "<div class=\"groundLock\">"+"<p style=\"text-align:center\">当前电桩支持地锁功能,<br/>请选择合适的地锁停车充电:</p>"
+"<ul class=\"lockBg\" style=\"list-style:none;\">"+
"<li class=\"LockSingle lock\">"+
"<div>"+
"<h5>地锁</h5>"+
"<img class=\"lockImgA lockImg\" src=\""+lockImgPathA+"\">"+
"</div>"+
"</li>"+
"</ul>"+
"</div>";
}
$('.nextBtn').before(html_LockView);
}
//lock1 lock2 地锁的状态选择不同的图片显示和交互,0:表示离线,1:地锁上锁(立起状态),2:地锁下放状态,5:表示地锁状态未知,8:表示无地锁
function lockStatus(lock) {
var lockImage = "";
switch(lock) {
case 0:
lockImage = "img/charge/ico_Charging_packing-lock_disabled_@3x.png";
break;
case 1:
lockImage = "img/charge/ico_Charging_packing-lock_up_@3x.png";
break;
case 2:
lockImage = "img/charge/ico_Charging_packing-lock_down_@3x.png";
break;
case 5:
lockImage = "img/charge/ico_Charging_packing-lock_unknown_@3x.png";
default:
break;
}
return lockImage;
}
|
Java
|
UTF-8
| 434
| 3.46875
| 3
|
[] |
no_license
|
// Exam 100
public class SuperCalc {
protected static int multiply(int a, int b){return a * b;}
}
public class SubCalc extends SuperCalc{
public static int multiply(int a, int b){
int c = super.multiply(a, b);
// int c = SuperCalc.multiply(a, b);
return c;
}
public static void main(String[] args){
SubCalc sc = new SubCalc();
System.out.println(sc.multiply(3, 4));
System.out.println(SubCalc.multiply(2, 2));
}
}
|
Java
|
UTF-8
| 988
| 3.625
| 4
|
[] |
no_license
|
package chap015;
import java.util.ArrayList;
import java.util.List;
public class FindAllOccurrences {
public static List<Integer> findAllOccurrences(String string, String substring) {
if(string == null || substring == null) {
throw new IllegalArgumentException("Provided parameters shouldn't be null");
}
if(string.isEmpty() || substring.isEmpty()) {
throw new IllegalArgumentException("Provided parameters shouldn't be empty");
}
List<Integer> list = new ArrayList<Integer>();
// our variable to track the position of the characters
int lastMatchingIndex = 0;
// na vrh brda vrba mrda
do {
lastMatchingIndex = string.indexOf(substring, lastMatchingIndex);
if (lastMatchingIndex != -1) {
list.add(lastMatchingIndex);
lastMatchingIndex++;
}
} while (lastMatchingIndex != -1);
return list;
}
}
|
Markdown
|
UTF-8
| 559
| 2.875
| 3
|
[] |
no_license
|
# 容器源码分析
## ArrayList
### 存储方式
对象数组 Object[]
### add 原理
1. 判断容量是否足够,如果不足增长容量
2. 增长容量就是用新计算出的容量创建新数组,再把旧数组的数据复制到新数组中
3. 添加新数据
### remove(Object o) 原理
1. 查找 o 对应的下标
2. 将下标后面的数据所在位置,复制到前一个下标的位置,将最后一个数据设置为null
3. 将 size - 1
## HashMap
### 存储方式
Object Node 链表
### put 原理
1. 用 Key 计算 hash 值
|
Java
|
UTF-8
| 1,144
| 2.734375
| 3
|
[] |
no_license
|
package com.example.springModel.model;
import javax.persistence.*;
@Entity
@Table(name = "fish")
public class Fish {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Long id;
@Column
private String species;
@Column
private String color;
@Column
private Boolean saltWater;
@Column
private Boolean freshWater;
public Fish() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Boolean getSaltWater() {
return saltWater;
}
public void setSaltWater(Boolean saltWater) {
this.saltWater = saltWater;
}
public Boolean getFreshWater() {
return freshWater;
}
public void setFreshWater(Boolean freshWater) {
this.freshWater = freshWater;
}
}
|
C
|
UTF-8
| 592
| 3.171875
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <conio.h>
#include <math.h>
int f(float x)
{
return x*x*x+x*x+x+7;
}
void main()
{
float x0,x1,x2;
float f1,err;
int i=0;
clrscr();
one:
printf("enter the values of x0 and x1 and acceptable error\n");
scanf("%f %f %f",&x0,&x1,&err);
if(f(x0)*f(x1)>0)
{
printf("the entered values of x0 and x1 will not give root value\n");
goto one;
}
do
{
x2=(x0+x1)/2;
if(f(x0)*f(x1)<0)
x1=x2;
else
x0=x2;
i++;
printf("number of iterations=%d",i);
printf("root=%f",x2);
printf("value of function=%f\n",f(x2));
}while(fabs(x1-x0)>err);
getch();
}
|
PHP
|
UTF-8
| 1,079
| 2.53125
| 3
|
[] |
no_license
|
<?php
namespace App\Mail;
use App\Models\Proposal;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use App\Auth;
class InternshipProposalMail extends Mailable
{
use Queueable, SerializesModels;
private $student;
private $proposal;
/**
* Create a new message instance.
*
* @param $student
* @param Proposal $proposal
*/
public function __construct($student, Proposal $proposal)
{
$this->student = $student;
$this->proposal = $proposal;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
$user = Auth::user();
$title = 'Vaga de estágio';
$from = 'informatica@cti.feb.unesp.br';
return $this->from($from)
->view('emails.internshipProposal')
->subject($title)
->with([
'user' => $user,
'title' => $title,
'student' => $this->student,
'proposal' => $this->proposal,
]);
}
}
|
Markdown
|
UTF-8
| 4,794
| 2.640625
| 3
|
[] |
no_license
|
WARNING
=======
This repository is no longer actively managed.
Please migrate to [Linuxserver's GitHub repository](https://github.com/linuxserver/docker-sabnzbd), respectively use [Linuxserver's Docker(Hub) image](https://hub.docker.com/r/linuxserver/sabnzbd).
## About
This is a Docker image for [SABnzbd](http://sabnzbd.org/) - the Open Source Binary Newsreader written in Python.
The Docker image currently supports:
* running SABnzbd under its __own user__ (not `root`)
* changing of the __UID and GID__ for the SABnzbd user
* changing the `host_whitelist` setting for compatibility with [hostname verification](https://sabnzbd.org/hostname-check)
* support for OpenSSL / HTTPS encryption
* support for __RAR archives__
* support for __ZIP archives__
* support for __7Zip archives__ ([with SABnzbd version >= 0.8](#improvements-for-sabnzbd-version--08))
* support for the latest `par2` repair utility ([improved with SABnzbd version >= 0.8](#improvements-for-sabnzbd-version--08))
## Run
### Run via Docker CLI client
To run the SABnzbd container you can execute:
```bash
docker run --name sabnzbd -v <datadir path>:/datadir -v <media path>:/media -p 8080:8080 sabnzbd/sabnzbd
```
Open a browser and point it to [http://my-docker-host:8080](http://my-docker-host:8080)
### Run via Docker Compose
You can also run the SABnzbd container by using [Docker Compose](https://www.docker.com/docker-compose).
If you've cloned the [git repository](https://github.com/domibarton/docker-sabnzbd) you can build and run the Docker container locally (without the Docker Hub):
```bash
docker-compose up -d
```
If you want to use the Docker Hub image within your existing Docker Compose file you can use the following YAML snippet:
```yaml
sabnzbd:
image: "sabnzbd/sabnzbd"
container_name: "sabnzbd"
volumes:
- "<datadir path>:/datadir"
- "<media path>:/media"
ports:
- "8080:8080"
restart: always
```
## Configuration
### Volumes
Please mount the following volumes inside your SABnzbd container:
* `/datadir`: Holds all the SABnzbd data files (e.g. config, postProcessing)
* `/media`: Directory for media (downloaded files)
### Configuration file
By default the SABnzbd configuration is located on `/datadir/config.ini`.
If you want to change this you've to set the `CONFIG` environment variable, for example:
```
CONFIG=/datadir/sabnzbd.ini
```
### UID and GID
By default SABnzbd runs with user ID and group ID `666`.
If you want to run SABnzbd with different ID's you've to set the `SABNZBD_UID` and/or `SABNZBD_GID` environment variables, for example:
```
SABNZBD_UID=1234
SABNZBD_GID=1234
```
### GID List
When mounted volumes use different groups to manage access permission, set the `SABNZBD_GID_LIST` environment variable to create groups in the container. The container user will be automatically added to these groups. The variable can take multiple GIDs seperated with comma, for example:
```
SABNZBD_GID_LIST=123,124,125
```
### Hostname verification and updating `host_whitelist`
Starting with version 2.3.3 SABnzbd implements [hostname verification](https://sabnzbd.org/hostname-check)
to protect against DNS hijacking attacks. Thus by default SABnzbd allows access
to the web interface only by either accessing it directly by IP address or by
the hostname of the machine on which it runs. But the IP address or hostname of
the running Docker instance is not always available or accessible from the
outside (especially when running in Kubernetes).
You can work around this by setting the container hostname with
`docker create -h sabnzbd.example.com ...` when creating the container. This
will allow you to access SABnzbd by `http://sabnzbd.example.com:8080` by
default.
You can also use set the environment variable `HOST_WHITELIST_ENTRIES` to a
string of comma-separated values of hostnames and FQDNs under which SABnzbd
should be accessible. This will update the [`host_whitelist` special setting](https://sabnzbd.org/wiki/configuration/2.3/special)
with those values. Note that the container's hostname is always included in
this whitelist. For example:
```
HOST_WHITELIST_ENTRIES="sabnzbd.example.com, sabnzbd.other.example.net"
```
## Improvements for SABnzbd version > 0.8
SABnzbd brings a lot of improvements in version `0.8` and greater. This image is built to use those improvements, which means:
* you can use the latest `par2` utility and set _Extra PAR2 Parameters_ in your SABnzbd config switches
* `-t` for using `par` with multi-core CPUs (see also [this wiki page](http://wiki.sabnzbd.org/configure-switches#multi-core))
* `-N` to improve failed repairs (see also [this forum thread](http://forums.sabnzbd.org/viewtopic.php?f=2&t=19913#p103827))
* you can use 7Zip to unpack `.7z` archives
|
C#
|
UTF-8
| 690
| 3.1875
| 3
|
[] |
no_license
|
public static ElementDefinitionImpl[] RemoveElementDefAt(
ElementDefinition[] oldList,
int removeIndex
)
{
ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];
int offset = 0;
for ( int index = 0; index < oldList.Length; index++ )
{
ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
if ( index == removeIndex )
{
// This is the one we want to remove, so we won't copy it. But
// every subsequent elementDef will by shifted down by one.
offset = -1;
}
else
{
newElementDefList[ index + offset ] = elementDef;
}
}
return newElementDefList;
}
|
JavaScript
|
UTF-8
| 2,127
| 3.390625
| 3
|
[] |
no_license
|
let mainspr; //Declaring sprite variables
let sprtw;
let sprthr;
// var win
// var lose
// function preload (){
// win = loadSound("win.wav");
// lose = loadSound("lose.wav");
// }
function setup() {
createCanvas (500, 500);
mainspr = createSprite(windowWidth-(windowWidth-50), windowHeight/3, 40, 40); //defining main sprite
mainspr.shapeColor = color(255);
sprtw = createSprite(random(50,500),random(60,450),30,30); //defining winning sprite
sprtw.shapeColor = color (random(255),random(255), random(255));
sprtw.mouseActive = true;
sprthr = createSprite (random(50,500),random(60,450),30,30); //defining loosing sprite
sprthr.shapeColor = color (random(255),random(255), random(255));
sprthr.mouseActive = true;
}
function draw() {
background(50);
textSize(0);
if(sprtw.mouseIsOver) { //Clue #1 (winning)
textSize(32);
fill(255);
textAlign(CENTER, TOP);
text('This is the right choice',250,50);
}
if(sprthr.mouseIsOver) { //Clue #2 (loosing)
textSize(32);
fill(255);
textAlign(CENTER, TOP);
text('This is the wrong choice',250,50);
}
if(mainspr.overlap(sprtw)){ //what happens when you win, the background changes, and "Correct" appears)
// win.play();
background (sprtw.shapeColor);
mainspr.setSpeed(0, 0);
textSize(32);
fill(255);
textAlign(CENTER, TOP);
text('CORRECT',250,50);
}
else if (mainspr.overlap (sprthr)){ //what happens when you lose, the sprite changes, and "Game Over" appears"
// lose.play();
mainspr.setSpeed(0, 0);
mainspr.shapeColor = (sprthr.shapeColor);
textSize(32);
fill(255);
textAlign(CENTER, TOP);
text('GAME OVER',250,50);
}
drawSprites();
}
function keyPressed() { //controls to move the main sprite
if (keyCode == RIGHT_ARROW) {
mainspr.setSpeed(1.5, 0);
}
else if (keyCode == LEFT_ARROW) {
mainspr.setSpeed(1.5, 180);
}
else if (keyCode == DOWN_ARROW) {
mainspr.setSpeed(1.5, 90);
}
else if (keyCode == UP_ARROW) {
mainspr.setSpeed(1.5, 270);
}
else if (key == ' ') {
mainspr.setSpeed(0, 0);
}
return false;
}
|
Markdown
|
UTF-8
| 2,708
| 2.65625
| 3
|
[] |
no_license
|
---
authors: ["Bill Hennessy"]
date: 2016-04-20 20:14:05+00:00
draft: false
title: Safe Sex for Alcohol and a Condom for Your Liver - Podcast
layout: blog
url: /2016/04/20/safe-sex-alcohol-condom-liver/
categories:
- Living
tags:
- Chigurupati
- NTX
type: "post"
---
Let's regress in time to the 1980s.
Remember C. Everett Koop, the Surgeon-General who launched the Safe Sex movement? Koop wanted to curtail the spread of AIDS. The Safe Sex movement started slowly and originally focused on non-monogamous gay men. By 1987, though, everyone was doing it. (Or not doing "it" as the case may be.) A February 17, 1987 New York Times headline declared "Safe Sex Movement Gains Favor Among Heterosexuals." The story said, "Caution is in. The one-night stand is out." And a woman in a condom ad said, "I'd do a lot for love, but I won't die for it."
**Think of the [Coalition for Safer Drinking ](https://saferalcohol.com/blog/)as the Safe Sex movement for alcohol.** Chigurupati Technologies' **NTX is like a condom for your liver and DNA**. [NTX prevents 93 percent of the liver damage ](https://billhennessy.com/simple-strategies?tag=NTX)caused by drinking and about half of the DNA damage. (Yes, even one drink damages your DNA.)
[LEARN MORE ABOUT NTX](https://amzn.to/1QnRvVW)
In other words, **we're facing reality on reality's terms**. We know people drink, and we're not encouraging them to do so. We also know **people care more and more about their health**. Part of concern for health involves the stuff we put into our bodies, including alcohol.
So the Coalition for Safer Drinking wants you to know that regular alcohol is bad for your liver and your DNA, but **alcohol made with NTX is nearly harmless to the liver** and significantly safer for DNA. Right now, only [Bellion Vodka contains NTX.](https://www.bellionvodka.com/welcome#bellionvodka) Bellion will be available throughout the United States this summer, so look for it. If you live in Texas, New York, or Connecticut, you can get Bellion right now.
[soundcloud url="https://api.soundcloud.com/tracks/260082105" params="auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true" width="100%" height="450" iframe="true" /]
I am the national spokesman for the Coalition for Safer Drinking and author of the book on NTX, [Fight to Evolve, which is available for Kindle](https://amzn.to/1QnRvVW) now and will be available in hardbound very soon. Look for it on Amazon.com. Contact me at bill-at-billhennessy.com. I'd be happy to schedule an interview for your radio program, blog, or podcast.
Cross-posted from [billhennessy.com](https://billhennessy.com)
|
Markdown
|
UTF-8
| 2,801
| 2.625
| 3
|
[] |
no_license
|
---
title: Microsoft Translator Text API による不適切な表現のフィルター処理 | Microsoft Docs
description: Microsoft Translator Text API で不適切な表現のフィルター処理を使用します。
services: cognitive-services
author: Jann-Skotdal
manager: chriswendt1
ms.service: cognitive-services
ms.component: translator-text
ms.topic: article
ms.date: 12/14/2017
ms.author: v-jansko
ms.openlocfilehash: a7172e1e8aa336c011fb06e93fc5c4b54d26a3cd
ms.sourcegitcommit: 95d9a6acf29405a533db943b1688612980374272
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 06/23/2018
ms.locfileid: "35374349"
---
# <a name="how-to-add-profanity-filtering-with-the-microsoft-translator-text-api"></a>Microsoft Translator Text API による不適切な表現のフィルター処理を追加する方法
通常、Translator サービスでは、ソースに存在する不適切な表現は翻訳でも保たれます。 不適切な表現の程度と、単語を不適切にしているコンテキストは、文化により異なります。 その結果、対象言語における不適切な表現の程度は、増幅されたり低減されることがあります。
翻訳で不適切な表現が表示されるのを防ぐには (ソース テキスト内での不適切な表現の有無に関係なく)、Translate() メソッドで不適切な表現のフィルター処理オプションを使用できます。 このオプションを使用すれば、不適切な表現を削除したり適切なタグでマークされていることを確認するか、アクションを行わないかを選択できます。
Translate() メソッドは "options" パラメーターを取り、ここには "ProfanityAction" の新しい要素が含まれます。 ProfanityAction の値は、"NoAction"、"Marked"、および "Deleted" です。
## <a name="accepted-values-of-profanityaction-and-examples"></a>ProfanityAction に指定できる値と例
|ProfanityAction 値 | アクションを表示します。 | 例: ソース - 日本語 | 例: ターゲット - 英語|
| :---|:---|:---|:---|
| NoAction | [既定]。 オプションを設定しない場合と同じです。 不適切な表現はソースからターゲットに渡されます。 | 彼は変態です。 | He is a jerk. |
| Marked | 不適切な表現は XML タグ \<profanity> … \</profanity> で囲まれます。 | 彼は変態です。 | He is a \<profanity>jerk\</profanity>. |
| Deleted | 不適切な単語は、置換されずに出力から削除されます。 | 彼は。 | He is a. |
## <a name="next-steps"></a>次の手順
> [!div class="nextstepaction"]
> [Translator API 呼び出しで不適切な表現のフィルター処理を適用する](reference/v3-0-translate.md)
|
C
|
UTF-8
| 2,839
| 3.21875
| 3
|
[] |
no_license
|
#include "Alumno-Cursos.h"
void mostrarAlumnosConSuCurso(eAlumno listaDeAlumnos[], int sizeAlumnos, eCurso listaDeCursos[], int sizeCursos)
{
int i;//alumnos
int j;//cursos
//Tener en cuenta que hay alumnos que pueden estar dados de baja
//Tener en cuenta que hay cursos que pueden estar dados de baja
for(i=0; i<sizeAlumnos; i++)
{
for(j=0; j<sizeCursos; j++)
{
if(listaDeAlumnos[i].idCurso /*FK*/ == listaDeCursos[j].idCurso /*PK*/)
{
printf("%4d %15s %15s %4d\n", listaDeAlumnos[i].legajo, listaDeAlumnos[i].nombre, listaDeCursos[j].descripcion, listaDeCursos[j].duracion);
break;
}
}
}
}
void mostrarCursosConSusAlumnos(eAlumno listaDeAlumnos[], int sizeAlumnos, eCurso listaDeCursos[], int sizeCursos)
{
int i;//Cursos
int j;//Alumnos
for(i=0; i<sizeCursos; i++)
{
printf("CURSO: %s\n", listaDeCursos[i].descripcion);
for(j=0; j<sizeAlumnos; j++)
{
//Preguntar si el alumno esta disponible
if(listaDeAlumnos[j].idCurso /*FK*/ == listaDeCursos[i].idCurso /*PK*/)
{
mostrarUnAlumno(listaDeAlumnos[j]);
}
}
}
}
void mostrarCursoConMasAlumnos(eAlumno listaDeAlumnos[], int sizeAlumnos, eCurso listaDeCursos[], int sizeCursos)
{
Alumno_Curso auxAlumnoCurso[sizeCursos];
int i;
int j;
int maximo;
//Inicializar el array alumno-curso
for(i=0; i<sizeCursos; i++)
{
auxAlumnoCurso[i].idCurso = listaDeCursos[i].idCurso;
auxAlumnoCurso[i].cantidadAlumnos = 0;
}
/********************************************/
for(i=0; i<sizeCursos; i++)
{
for(j=0; j<sizeAlumnos; j++)
{
if(listaDeAlumnos[j].estado==OCUPADO && auxAlumnoCurso[i].idCurso == listaDeAlumnos[j].idCurso)
{
auxAlumnoCurso[i].cantidadAlumnos++;
}
}
}
/********************************************/
for(i=0; i<sizeCursos; i++)
{
if(i==0 || auxAlumnoCurso[i].cantidadAlumnos>maximo)
{
maximo = auxAlumnoCurso[i].cantidadAlumnos;
}
}
/********************************************/
printf("\nMAXIMO: %d\n", maximo);
for(i=0;i<sizeCursos;i++)
{
if(auxAlumnoCurso[i].cantidadAlumnos == maximo)
{
for(j=0;j<sizeCursos; j++)
{
if(auxAlumnoCurso[i].idCurso == listaDeCursos[j].idCurso)
{
printf("%s\n", listaDeCursos[j].descripcion);
}
}
}
}
/*for(i=0; i<sizeCursos; i++)
{
printf("%d - %d\n", auxAlumnoCurso[i].idCurso, auxAlumnoCurso[i].cantidadAlumnos);
}
*/
}
|
Markdown
|
UTF-8
| 5,797
| 3
| 3
|
[] |
no_license
|
# Article 220 quinquies
I. Par dérogation aux dispositions du troisième alinéa du I de l'article 209, le déficit constaté au titre d'un exercice
ouvert à compter du 1er janvier 1984 par une entreprise soumise à l'impôt sur les sociétés peut, sur option, être considéré
comme une charge déductible du bénéfice de l'exercice précédent, dans la limite de la fraction non distribuée de ce bénéfice
et à l'exclusion du bénéfice exonéré en application des articles 44 sexies, 44 sexies A, 44 septies, 44 octies, 44 octies A,
44 terdecies, 44 quaterdecies, 44 quindecies, 44 sexdecies, 44 septdecies et 207 à 208 sexies ou qui a bénéficié des
dispositions du premier alinéa du f du I de l'article 219 ou qui a ouvert droit au crédit d'impôt prévu aux articles 220
quater et 220 quater A ou qui a donné lieu à un impôt payé au moyen de crédits d'impôts.
Le déficit imputé dans les conditions prévues au premier alinéa cesse d'être reportable sur les résultats des exercices
suivant celui au titre duquel il a été constaté.
L'option mentionnée au premier alinéa n'est admise qu'à la condition qu'elle porte sur le déficit constaté au titre de
l'exercice, dans la limite du montant le plus faible entre le bénéfice déclaré au titre de l'exercice précédent et un montant
de 1 000 000 €.
L'excédent d'impôt sur les sociétés résultant de l'application du premier alinéa fait naître au profit de l'entreprise une
créance non imposable d'égal montant.
La créance est remboursée au terme des cinq années suivant celle de la clôture de l'exercice au titre duquel l'option visée
au premier alinéa a été exercée. Toutefois, l'entreprise peut utiliser la créance pour le paiement de l'impôt sur les
sociétés dû au titre des exercices clos au cours de ces cinq années. Dans ce cas, la créance n'est remboursée qu'à hauteur de
la fraction qui n'a pas été utilisée dans ces conditions.
Par exception aux dispositions du cinquième alinéa, les entreprises ayant fait l'objet d'une procédure de sauvegarde, d'un
redressement ou d'une liquidation judiciaires peuvent demander le remboursement de leur créance non utilisée à compter de la
date du jugement qui a ouvert ces procédures. Ce remboursement est effectué sous déduction d'un intérêt appliqué à la créance
restant à imputer. Cet intérêt, dont le taux est celui de l'intérêt légal applicable le mois suivant la demande de
l'entreprise, est calculé à compter du premier jour du mois suivant cette demande jusqu'au terme des cinq années suivant
celle de la clôture de l'exercice au titre duquel l'option a été exercée.
La créance est inaliénable et incessible, sauf dans les conditions prévues par les articles L. 313-23 à L. 313-35 du code
monétaire et financier, ou dans des conditions fixées par décret.
II. L'option visée au I est exercée au titre de l'exercice au cours duquel le déficit est constaté et dans les mêmes délais
que ceux prévus pour le dépôt de la déclaration de résultats de cet exercice. Elle ne peut pas être exercée au titre d'un
exercice au cours duquel intervient une cession ou une cessation totale d'entreprise, une fusion de sociétés ou une opération
assimilée, ou un jugement prononçant la liquidation judiciaire de la société.
En cas de fusion, de scission ou d'opération assimilée intervenant au cours des cinq années suivant celle de la clôture de
l'exercice au titre duquel l'option visée au I a été exercée, la créance de la société absorbée, scindée ou apporteuse peut
être transférée à la ou les sociétés bénéficiaires des apports. Le transfert de la créance est effectué pour sa valeur
nominale.
En cas de scission ou d'apport partiel d'actif, la créance est transmise au prorata du montant de l'actif net réel apporté à
la ou aux sociétés bénéficiaires des apports apprécié à la date d'effet de l'opération.
(Alinéa disjoint).
III. (Abrogé).
IV. Un décret fixe les conditions d'application du présent article, notamment les obligations déclaratives des entreprises.
**Nota:**
Au premier alinéa du I, la référence : , 44 undecies est périmée.
**Liens relatifs à cet article**
_Cité par_:
- Loi n°2008-1443 du 30 décembre 2008 - art. 94 (V)
- Ordonnance n°2013-837 du 19 septembre 2013 - art. 11 (V)
- Code général des impôts, CGI. - art. 209 (V)
- Code général des impôts, CGI. - art. 210-0 A (V)
- Code général des impôts, CGI. - art. 223 G (V)
- Code général des impôts, CGI. - art. 223 K (V)
- Code général des impôts, CGI. - art. 234 duodecies (VT)
- Code général des impôts, CGI. - art. 235 ter ZAA (V)
- Code général des impôts, CGI. - art. 235 ter ZC (V)
- Code général des impôts, CGI. - art. 235 ter ZCA (Ab)
- Code général des impôts, CGI. - art. 235 ter ZF (V)
- Code général des impôts, annexe 3, CGIAN3. - art. 46 quater-0 S (V)
- Code général des impôts, annexe 3, CGIAN3. - art. 46 quater-0 W (V)
- Livre des procédures fiscales - art. L171 A (V)
_Modifié par_:
- Loi n°2017-1775 du 28 décembre 2017 - art. 17 (VD)
- Loi n°2018-1317 du 28 décembre 2018 - art. 135 (VD)
_Cite_:
- Code général des impôts, CGI. - art. 207
- Code général des impôts, CGI. - art. 219
- Code général des impôts, CGI. - art. 220 quater
- Code général des impôts, CGI. - art. 44 octies
- Code général des impôts, CGI. - art. 44 quaterdecies
- Code général des impôts, CGI. - art. 44 septies
- Code général des impôts, CGI. - art. 44 sexies
- Code général des impôts, CGI. - art. 44 sexies A
- Code général des impôts, CGI. - art. 44 terdecies
- Code monétaire et financier - art. L313-23
|
Markdown
|
UTF-8
| 1,189
| 2.765625
| 3
|
[] |
no_license
|
java 代码
```java
byte raw = (byte) 0b11101010;
System.out.println("init raw: " + raw+", binary: "+Integer.toBinaryString(raw & 0xff));
byte head = (byte) (raw >>> 4 & 0x0f);
byte tail = (byte) (raw & 0b00001111);
System.out.println("\nsplit: ");
System.out.println("head: " + head + ", " + Integer.toBinaryString(head));
System.out.println("tail: " + tail + ", " + Integer.toBinaryString(tail));
System.out.println("\nmerge: ");
System.out.println((byte)((head<<4 | tail) & 0xff));
System.out.println((byte)((head<<4 | tail)));
System.out.println("\nbit show: ");
System.out.println(Integer.toBinaryString((head<<4 | tail)));
System.out.println(-1 >>> 8); // 无符号位移对int类型才有效。对byte无效
System.out.println(Integer.toBinaryString(-1 & 0xff));
System.out.println(Integer.toBinaryString(-2 & 0xff));
System.out.println(Integer.toBinaryString(-3));
System.out.println(Integer.toBinaryString(-127));
System.out.println((char)0b11101010);
```
输出
```
init raw: -22, binary: 11101010
split:
head: 14, 1110
tail: 10, 1010
merge:
-22
-22
bit show:
11101010
16777215
11111111
11111110
11111111111111111111111111111101
11111111111111111111111110000001
ê
```
|
Python
|
UTF-8
| 1,844
| 3.25
| 3
|
[] |
no_license
|
from menu import *
from file_work import *
from AES import AES
def str_to_ascii(symbols):
res = []
for i in symbols:
res.append(ord(i))
return res
def ascii_to_str(ascii_lst):
res = []
for i in ascii_lst:
res.append(chr(i))
return res
if __name__ == '__main__':
while True:
print_aes_menu()
choice = int(input())
if choice == 1:
aes = AES(128)
print_menu()
choice = int(input())
if choice == 1:
symbols_str = str(input("Введите строку: "))
symbols = str_to_ascii(symbols_str)
encode = aes.encrypt_str(symbols)
encode_str = ascii_to_str(encode)
print(f"Строка \'{symbols_str}\' перекодирована в \'{encode_str}\'")
decode = aes.decrypt_str(encode)
decode_str = ascii_to_str(decode)
print(f"Строка \'{encode_str}\' расшифрована в \'{decode_str}\'")
elif choice == 2:
load_file = str(input("Ввведите имя файла: "))
symbols = get_symbols_from_file(load_file)
encode = aes.encrypt_str(symbols)
encode_file = str(input("Введите, куда записать зашифрованный файл: "))
write_symbols_in_file(encode_file, encode)
decode = aes.decrypt_str(encode)
decode_file = str(input("Введите, куда записать расшифрованный файл: "))
write_symbols_in_file(decode_file, decode)
else:
break
elif choice == 2:
break
elif choice == 3:
break
else:
break
|
PHP
|
UTF-8
| 1,626
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
<?php
// Use this to implement a minimal front controller to use instead
// of WordPress' index.php
//
// it works like this: rename WordPress' index.php to something
// else, e.g. wp-index.php. create a new index.php that looks about
// so:
//
// ```php
// <?php
//
// require_once __DIR__ . '/wp-content/themes/testtheme/vendor/autoload.php';
//
// Em4nl\Unplug\front_controller(__DIR__ . '/wp-index.php');
// ```
//
// Also, you'll need an additional unplug-config.php file in your
// WordPress root dir with these two definitions in it:
//
// ```php
// <?php
//
// define('UNPLUG_CACHE_DIR', __DIR__ . '/_unplug_cache');
// define('UNPLUG_CACHE_ON', TRUE);
// ```
//
// Note that this bypasses WordPress completely
//
// (Instead of renaming index.php, you might also e.g. change the
// default redirect rule in your .htaccess)
//
namespace Em4nl\Unplug;
if (!function_exists('Em4nl\Unplug\front_controller')) {
function front_controller($wp_index_php, $invalidate=NULL) {
define('UNPLUG_FRONT_CONTROLLER', TRUE);
if (UNPLUG_CACHE_ON) {
global $_unplug_cache;
$_unplug_cache = new \Em4nl\U\Cache(UNPLUG_CACHE_DIR);
if ($invalidate) {
$_unplug_cache->invalidate($invalidate);
}
$served_from_cache = $_unplug_cache->serve();
if (!$served_from_cache) {
$_unplug_cache->start();
include_once $wp_index_php;
$_unplug_cache->end(!defined('UNPLUG_DO_CACHE') || UNPLUG_DO_CACHE);
}
} else {
include_once $wp_index_php;
}
}
}
|
Python
|
UTF-8
| 615
| 2.546875
| 3
|
[] |
no_license
|
from urllib import urlopen
from xml.dom.minidom import parseString
fp = urlopen( "http://thehubway.com/data/stations/bikeStations.xml" )
dom = parseString( fp.read() )
fpout = open( "hubway.csv", "w" )
fpout.write( "id,name,latitude,longitude\n")
for station in dom.getElementsByTagName("station"):
id = station.getElementsByTagName("id")[0].firstChild.data
name = station.getElementsByTagName("name")[0].firstChild.data
lat = station.getElementsByTagName("lat")[0].firstChild.data
lon = station.getElementsByTagName("long")[0].firstChild.data
fpout.write("%s,%s,%s,%s\n"%(id,name,lat,lon))
|
Python
|
UTF-8
| 1,877
| 3.484375
| 3
|
[] |
no_license
|
import sys
def checkFileFormat(fname):
if fname == "exit" : sys.exit()
#check file is fname or not.
ret = True
if fname.split('.')[-1] != "tet":
ans = raw_input("it is not .tet file. Are you OK? (Y/N):")
if ans not in ["Y","y","Yes","yes","YES"]:
ret = False
return ret
def readFile():
while True:
try:
# input file name
fname = str(raw_input("Please .tet file name:"))
# check .tet file or not
if not checkFileFormat(fname): continue
#file open
f = open(fname,'r')
except SystemExit: sys.exit()
except:
#error
print "Sorry, file open failed. Try again."
print sys.exc_info()
else:
#success
print "file open successed."
break
# read first line
f.readline()
# reading file
readed = []
for l in f:
buf = l.split()
readed.append(buf)
print str(len(readed)) + " lines read completed."
return readed
def main():
# file read. readed is list.
readed = readFile()
# calculation
for l in readed:
l[-1] = str(float(l[-1]) - 1000)
# open output file.
while True:
try:
outfname = raw_input("Please output file name: ")
if not checkFileFormat(outfname): continue
fout = open(outfname,"w")
except SystemExit: sys.exit()
except:
print "file open failed. please try again."
print sys.exc_info()
else:
break
#writing to output file
print "Writing file..."
fout.write(str(len(readed)))
fout.write("\n")
for l in readed:
fout.write(" ".join(l))
fout.write("\n")
print "Write complete. GOOD BYE!"
if __name__ == "__main__":
main()
|
Python
|
UTF-8
| 8,904
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
# --------------------------------------
# @Time : 2020/11/01
# @Author : Oscar Chen
# @Email : 530824679@qq.com
# @File : augmentation.py
# Description : data augmentation
# --------------------------------------
import cv2
import random
import numpy as np
def random_horizontal_flip(image, bboxes):
"""
Randomly horizontal flip the image and correct the box
:param image: BGR image data shape is [height, width, channel]
:param bboxes: bounding box shape is [num, 4]
:return: result
"""
if random.random() < 0.5:
_, w, _ = image.shape
image = image[:, ::-1, :]
bboxes[:, [0, 2]] = w - bboxes[:, [2, 0]]
return image, bboxes
def random_vertical_flip(image, bboxes):
"""
Randomly vertical flip the image and correct the box
:param image: BGR image data shape is [height, width, channel]
:param bboxes: bounding box shape is [num, 4]
:return: result
"""
if random.random() < 0.5:
h, _, _ = image.shape
image = image[::-1, :, :]
bboxes[:, [1, 3]] = h - bboxes[:, [3, 1]]
return image, bboxes
def random_expand(image, bboxes, max_ratio=3, fill=0, keep_ratio=True):
"""
Random expand original image with borders, this is identical to placing
the original image on a larger canvas.
:param image: BGR image data shape is [height, width, channel]
:param bboxes: bounding box shape is [num, 4]
:param max_ratio: Maximum ratio of the output image on both direction(vertical and horizontal)
:param fill: The value(s) for padded borders.
:param keep_ratio: If `True`, will keep output image the same aspect ratio as input.
:return: result
"""
h, w, c = image.shape
ratio_x = random.uniform(1, max_ratio)
if keep_ratio:
ratio_y = ratio_x
else:
ratio_y = random.uniform(1, max_ratio)
oh, ow = int(h * ratio_y), int(w * ratio_x)
off_y = random.randint(0, oh - h)
off_x = random.randint(0, ow - w)
dst = np.full(shape=(oh, ow, c), fill_value=fill, dtype=image.dtype)
dst[off_y:off_y + h, off_x:off_x + w, :] = image
# correct bbox
bboxes[:, :2] += (off_x, off_y)
bboxes[:, 2:4] += (off_x, off_y)
return dst, bboxes
def letterbox_resize(image, bboxes, new_height, new_width, interp=0):
"""
Resize the image and correct the bbox accordingly.
:param image: BGR image data shape is [height, width, channel]
:param bboxes: bounding box shape is [num, 4]
:param new_height: new image height
:param new_width: new image width
:param interp:
:return: result
"""
origin_height, origin_width = image.shape[:2]
resize_ratio = min(new_width / origin_width, new_height / origin_height)
resize_width = int(resize_ratio * origin_width)
resize_height = int(resize_ratio * origin_height)
image = cv2.resize(image, (resize_width, resize_height), interpolation=interp)
image_padded = np.full((new_height, new_width, 3), 128, np.uint8)
dw = int((new_width - resize_width) / 2)
dh = int((new_height - resize_height) / 2)
image_padded[dh:resize_height + dh, dw:resize_width + dw, :] = image
# xmin, xmax, ymin, ymax
bboxes[:, [0, 2]] = bboxes[:, [0, 2]] * resize_ratio + dw
bboxes[:, [1, 3]] = bboxes[:, [1, 3]] * resize_ratio + dh
return image_padded, bboxes
def random_color_distort(image, brightness=32, hue=18, saturation=0.5, value=0.5):
"""
randomly distort image color include brightness, hue, saturation, value.
:param image: BGR image data shape is [height, width, channel]
:param brightness:
:param hue:
:param saturation:
:param value:
:return: result
"""
def random_hue(image_hsv, hue):
if random.random() < 0.5:
hue_delta = np.random.randint(-hue, hue)
image_hsv[:, :, 0] = (image_hsv[:, :, 0] + hue_delta) % 180
return image_hsv
def random_saturation(image_hsv, saturation):
if random.random() < 0.5:
saturation_mult = 1 + np.random.uniform(-saturation, saturation)
image_hsv[:, :, 1] *= saturation_mult
return image_hsv
def random_value(image_hsv, value):
if random.random() < 0.5:
value_mult = 1 + np.random.uniform(-value, value)
image_hsv[:, :, 2] *= value_mult
return image_hsv
def random_brightness(image, brightness):
if random.random() < 0.5:
image = image.astype(np.float32)
brightness_delta = int(np.random.uniform(-brightness, brightness))
image = image + brightness_delta
return np.clip(image, 0, 255)
# brightness
image = random_brightness(image, brightness)
image = image.astype(np.uint8)
# color jitter
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV).astype(np.float32)
if np.random.randint(0, 2):
image_hsv = random_value(image_hsv, value)
image_hsv = random_saturation(image_hsv, saturation)
image_hsv = random_hue(image_hsv, hue)
else:
image_hsv = random_saturation(image_hsv, saturation)
image_hsv = random_hue(image_hsv, hue)
image_hsv = random_value(image_hsv, value)
image_hsv = np.clip(image_hsv, 0, 255)
image = cv2.cvtColor(image_hsv.astype(np.uint8), cv2.COLOR_HSV2BGR)
return image
def mix_up(image_1, image_2, bbox_1, bbox_2):
"""
Overlay images and tags
:param image_1: BGR image_1 data shape is [height, width, channel]
:param image_2: BGR image_2 data shape is [height, width, channel]
:param bbox_1: bounding box_1 shape is [num, 4]
:param bbox_2: bounding box_2 shape is [num, 4]
:return:
"""
height = max(image_1.shape[0], image_2.shape[0])
width = max(image_1.shape[1], image_2.shape[1])
mix_image = np.zeros(shape=(height, width, 3), dtype='float32')
rand_num = np.random.beta(1.5, 1.5)
rand_num = max(0, min(1, rand_num))
mix_image[:image_1.shape[0], :image_1.shape[1], :] = image_1.astype('float32') * rand_num
mix_image[:image_2.shape[0], :image_2.shape[1], :] += image_2.astype('float32') * (1. - rand_num)
mix_image = mix_image.astype('uint8')
# the last element of the 2nd dimention is the mix up weight
bbox_1 = np.concatenate((bbox_1, np.full(shape=(bbox_1.shape[0], 1), fill_value=rand_num)), axis=-1)
bbox_2 = np.concatenate((bbox_2, np.full(shape=(bbox_2.shape[0], 1), fill_value=1. - rand_num)), axis=-1)
mix_bbox = np.concatenate((bbox_1, bbox_2), axis=0)
mix_bbox = mix_bbox.astype(np.int32)
return mix_image, mix_bbox
def random_crop(image, bboxes):
if random.random() < 0.5:
h, w, _ = image.shape
max_bbox = np.concatenate([np.min(bboxes[:, 0:2], axis=0), np.max(bboxes[:, 2:4], axis=0)], axis=-1)
max_l_trans = max_bbox[0]
max_u_trans = max_bbox[1]
max_r_trans = w - max_bbox[2]
max_d_trans = h - max_bbox[3]
crop_xmin = max(0, int(max_bbox[0] - random.uniform(0, max_l_trans)))
crop_ymin = max(0, int(max_bbox[1] - random.uniform(0, max_u_trans)))
crop_xmax = max(w, int(max_bbox[2] + random.uniform(0, max_r_trans)))
crop_ymax = max(h, int(max_bbox[3] + random.uniform(0, max_d_trans)))
image = image[crop_ymin: crop_ymax, crop_xmin: crop_xmax]
bboxes[:, [0, 2]] = bboxes[:, [0, 2]] - crop_xmin
bboxes[:, [1, 3]] = bboxes[:, [1, 3]] - crop_ymin
return image, bboxes
def random_translate(image, bboxes):
"""
translation image and bboxes
:param image: BGR image data shape is [height, width, channel]
:param bbox: bounding box_1 shape is [num, 4]
:return: result
"""
if random.random() < 0.5:
h, w, _ = image.shape
max_bbox = np.concatenate([np.min(bboxes[:, 0:2], axis=0), np.max(bboxes[:, 2:4], axis=0)], axis=-1)
max_l_trans = max_bbox[0]
max_u_trans = max_bbox[1]
max_r_trans = w - max_bbox[2]
max_d_trans = h - max_bbox[3]
tx = random.uniform(-(max_l_trans - 1), (max_r_trans - 1))
ty = random.uniform(-(max_u_trans - 1), (max_d_trans - 1))
M = np.array([[1, 0, tx], [0, 1, ty]])
image = cv2.warpAffine(image, M, (w, h))
bboxes[:, [0, 2]] = bboxes[:, [0, 2]] + tx
bboxes[:, [1, 3]] = bboxes[:, [1, 3]] + ty
return image, bboxes
if __name__ == '__main__':
image_1 = cv2.imread("C:\\Users\\chenw\\Desktop\\test.jpg")
bboxes_1 = np.array([[355, 66, 484, 301], [425, 296, 502, 320]])
image_2 = cv2.imread("C:\\Users\\chenw\\Desktop\\test1.jpg")
bboxes_2 = np.array([[266, 196, 353, 333]])
image, bboxes = random_translate(image_1, bboxes_1)
#image = image.copy()
for i, box in enumerate(bboxes):
cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (255, 0, 0), 2)
cv2.imshow('test', image)
cv2.waitKey(0)
|
Java
|
UTF-8
| 563
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.erlin;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile(
"^\\w+(\\.\\w+)?" +//邮件登录名
"\\@\\w+" + //主机名
"\\.(\\w+){2,4}"//域名
);
Matcher matcher = pattern.matcher("javatianxia@163.com");
if (matcher.matches()) {
System.out.println("合法");
} else {
System.out.println("不合法");
}
}
}
|
C++
|
UTF-8
| 3,813
| 2.671875
| 3
|
[] |
no_license
|
#pragma once
#include <Eigen/Eigen>
#include <memory>
#include <exception>
#ifndef DEBUG
#define DEBUG
#endif
#ifdef DEBUG
#include <iostream>
using namespace std;
using namespace Eigen;
#endif
namespace egl
{
typedef Eigen::Matrix<size_t, -1, -1> mati_t;
typedef Eigen::Matrix<double, -1, -1> matd_t;
typedef Eigen::SparseMatrix<double> spmat_t;
template <typename T>
class Functional
{
public:
virtual ~Functional() {}
virtual size_t Dof() const = 0; // how many nodes/particles in the system
virtual int Val(const T *x, T *val) const = 0; // value
virtual int Gra(const T *x, T *gra) const = 0;
virtual int Hes(const T *x, std::vector<Eigen::Triplet<T>> *hes) const = 0;
};
typedef std::shared_ptr<Functional<double>> pfunc;
template <typename T>
class energy_t : public Functional<T>
{
public:
class null_input_exception : public std::exception
{
public:
const char *what() const throw()
{
return "null input exception";
}
};
class compatibility_exception : public std::exception
{
public:
const char *what() const throw()
{
return "compatibility exception";
}
};
energy_t(const std::vector<std::shared_ptr<Functional<T>>> &buffer)
: buffer_(buffer), dof_(-1)
{
for (auto &e : buffer_)
{
if (e.get())
{
dof_ = e->Dof();
break;
}
}
if (dof_ == -1)
{
throw null_input_exception();
}
for (auto &e : buffer_)
{
if (e.get() && e->Dof() != dof_)
{
throw compatibility_exception();
}
}
}
size_t Dof() const { return dof_; }
int Val(const T *x, T *val) const
{
// double oval = 0;
// int i = 0;
for (auto &e : buffer_)
{
if (e.get())
{
e->Val(x, val);
// cout << i++ << ": val=" << *val << " curVal=" << *val - oval << endl;
// oval = *val;
}
}
return 0;
}
int Gra(const T *x, T *gra) const
{
// cout << "Grad" << endl;
// double ograd = 0;
// int i = 0;
for (auto &e : buffer_)
{
if (e.get())
{
e->Gra(x, gra);
// Eigen::Map<VectorXd> G(gra, dof_);
// double g = G.norm();
// cout << i++ << " g:" << g << " curG:" << g - ograd << endl;
// ograd = g;
}
}
return 0;
}
int Hes(const T *x, std::vector<Eigen::Triplet<T>> *hes) const
{
// cout << "Hes:" << endl;
// double ohes = 0;
// int i = 0;
for (auto &e : buffer_)
{
if (e.get())
{
e->Hes(x, hes);
// Eigen::SparseMatrix<double> H(dof_, dof_);
// H.setFromTriplets(hes->begin(), hes->end());
// double hnorm = H.norm();
// cout << i++ << " hnorm=" << hnorm << " curH=" << hnorm - ohes << endl;
// ohes = hnorm;
}
}
return 0;
}
protected:
const std::vector<pfunc> &buffer_;
size_t dof_;
};
}
|
Python
|
UTF-8
| 2,382
| 3.125
| 3
|
[] |
no_license
|
import types
import numpy as np
import pandas as pd
dot = np.dot
def ijv2mat(df):
ilist = df["i"]
jlist = df["j"]
n = max(ilist)
m = max(jlist)
if("val" in df):
vlist = df["val"]
dtype = float
elif("re" in df and "im" in df):
vlist = df["re"] + 1.0j * df["im"]
dtype = complex
mat = np.zeros((n,m), dtype=dtype)
for (i,j,v) in zip(ilist,jlist,vlist):
mat[i-1,j-1]=v
return mat
def mat2ijv(x, eps=None):
(n,m) = np.shape(x)
ilist = []
jlist = []
vlist = []
idx = 0
for i in range(n):
for j in range(m):
if(eps==None):
non0 = True
else:
non0 = (abs(x[i,j])>eps)
if(non0):
ilist.append(i+1)
jlist.append(j+1)
vlist.append(x[i,j])
i = np.array(ilist)
j = np.array(jlist)
v = np.array(vlist)
if(isinstance(x[0,0], complex)):
df = pd.DataFrame({"i":i, "j":j, "re":v.real, "im":v.imag},
columns=["i","j","re","im"])
else:
df = pd.DataFrame({"i":i, "j":j, "val":v},
columns=["i","j","val"])
return df
def iv2vec(df):
ilist = df["i"]
n = max(ilist)
if("val" in df):
vlist = df["val"]
vec = np.zeros(n,dtype=float)
elif("re" in df and "im" in df):
vlist = df["re"] + 1.0j * df["im"]
vec = np.zeros(n,dtype=complex)
for (i,v) in zip(ilist, vlist):
vec[i-1] = v
return vec
def vec2iv(vec):
n = len(vec)
ilist = []
vlist = []
for i in range(n):
ilist.append(i+1)
vlist.append(vec[i])
if(isinstance(vec[0], complex)):
val = np.array(vlist)
re = val.real
im = val.imag
i = np.array(ilist)
df = pd.DataFrame({"i":i, "re":re, "im":im},
columns=["i","re","im"])
else:
val = np.array(vlist)
df = pd.DataFrame({ "i": np.array(ilist), "val": val})
return df
if __name__ == '__main__':
x = np.array([[2.0, 1.1],
[2.1, 1.2],
[3.2, 1.3]])
df = mat2ijv(x)
y = ijv2mat(df)
print sum(abs(y-x))
def hdot(x, y):
return dot(x.conj(), y)
def norm(x):
return np.sqrt(hdot(x,x).real)
|
JavaScript
|
UTF-8
| 2,670
| 2.71875
| 3
|
[] |
no_license
|
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get("color");
const q = urlParams.get("q");
//kea21-4d62.restdb.io/rest/silfenproducts??q={"colors": {"name" : {"$in": ["green"]}}}
// kea21-4d62.restdb.io/rest/silfenproducts?q={"category": "bags"}
fetch("https://kea21-4d62.restdb.io/rest/silfenproducts?q={}&filter=" + q, {
method: "GET",
headers: {
"x-apikey": "602e36c15ad3610fb5bb62b8",
},
})
.then((res) => res.json())
.then((response) => {
console.log(response);
showProducts(response);
})
.catch((err) => {
console.error(err);
});
function showProducts(data) {
document.querySelector("#catalogue-title h2").textContent = q;
document.querySelector("a.cataloguepage").textContent = q;
data.forEach((product) => {
console.log(product);
showProduct(product);
});
}
function showProduct(product) {
const tempProd = document.querySelector("template").content;
const clone = tempProd.cloneNode(true);
clone.querySelector(".product-name").textContent = product.name;
clone.querySelector(".product-image").src = product.images[1];
// clone.querySelector(".colors").textContent = product.colors[0].name;
clone.querySelector(".product-price").textContent = `${product.price} DKK`;
clone.querySelector(
".product-card a"
).href = `product-page.html?_id=${product._id}`;
// if (product.colors.length > 1) {
// clone.querySelector(".color2").textContent = product.colors[1].name;
// clone.querySelector(".color")
// }
var color_list = clone.querySelector(".product-colors");
var ul = document.createElement("ul");
product.colors.forEach(function (color) {
var li = document.createElement("li");
// li.textContent = color.name;
li.style.backgroundColor = color.value;
ul.appendChild(li);
});
color_list.appendChild(ul);
// btnEl = clone.querySelector("button");
// // btnEl.dataset.id += product._id;
// btnEl.addEventListener("click", () => {
// cart.add(product);
// });
const prod = document.querySelector("#catalogue-products");
prod.appendChild(clone);
}
// document.querySelector("#loadMore").addEventListener("click", showMore());
// function showMore() {
// }
// var currentindex = 0;
// var items = Object.values(data);
// function loadmore() {
// var maxresult = 2;
// for (var i = 0; i < maxresult.length; i++) {
// if (currentindex >= items.length) {
// $("#lmbutton").hide();
// return;
// }
// $("#catalogue-products").append(
// "<section>" + items[i + currentindex] + "</section"
// );
// }
// currentindex += maxresult;
// }
|
JavaScript
|
UTF-8
| 13,093
| 2.984375
| 3
|
[
"Apache-2.0"
] |
permissive
|
Math.degrees = function(rad)
{
return rad*(180/Math.PI);
}
Math.radians = function(deg)
{
return deg * (Math.PI/180);
}
var eucl_distance = function(p1,p2) {
return Math.sqrt(Math.pow(p1[0]-p2[0],2)+Math.pow(p1[1]-p2[1],2)+Math.pow(p1[2]-p2[2],2));
}
function car_genome() {
var num_segs = 5;
var genome;
// var genomeDescription = 0;
// Initialize a genome for this robot, handled by HillClimber
this.initGenome = function() {
var gen = [];
// Start with a randomized genome.
//Randomize the length, width, and height for each box.
for (var i = 0; i < num_segs; ++i) {
if (Math.random() > 0.1 || i == 0) {
gen.push(1); // Chassis Segment Expressed (0:No, 1:Yes)
} else {
gen.push(0); // Chassis Segment Expressed (0:No, 1:Yes)
}
gen.push((1.+(3. * Math.random()).toFixed(4))/2.); // Chassis Length
gen.push((0.4 + 5. * Math.random()).toFixed(4)); // Chassis Height
gen.push((0.4 + 10. * Math.random()).toFixed(4)); // Chassis Width
if (Math.random() > 0.5) {
gen.push(1); // Wheels (0:No, 1:Yes)
} else {
gen.push(0); // Wheels (0:No, 1:Yes)
}
gen.push((5. * Math.random()).toFixed(4)); // Wheel Diameter
gen.push((0.2 + 1. * Math.random()).toFixed(4)); // Wheel Width
}
genome = gen;
}
var genomeDescriptor = function() {
var genomeDescription = [];
for (var i = 0; i < num_segs; ++i) {
genomeDescription.push("Chassis Segment "+i.toString()+" Expressed");
genomeDescription.push("Chassis Segment "+i.toString()+" Length");
genomeDescription.push("Chassis Segment "+i.toString()+" Height");
genomeDescription.push("Chassis Segment "+i.toString()+" Width");
genomeDescription.push("Wheels "+i.toString()+" Expressed");
genomeDescription.push("Wheels "+i.toString()+" Diameter");
genomeDescription.push("Wheels "+i.toString()+" Width");
}
return genomeDescription;
}
this.genomeLength = function() {
return genome.length;
}
// Mutate a genome for this robot, handled by HillClimber
// TODO: Reimplement this for the new genome.
this.mutateGenome = function(mut_type, mut_perc) {
if (mut_type == 'random') {
for (var index = 1; index < genome.length; ++index) {
if (Math.random() < mut_perc) {
// Turn chassis segment on or off.
if (index % (genome.length/num_segs) == 0) {
if (Math.random() < 0.15) {
genome[index] = 0;
} else {
genome[index] = 1;
}
} else if (index % (genome.length/num_segs) == 1) {
genome[index] = (1.+(3. * Math.random()).toFixed(4)/2.); // Chassis Length
} else if (index % (genome.length/num_segs) == 2) {
genome[index] = (0.2 + 5. * Math.random()).toFixed(4); // Chassis Height
} else if (index % (genome.length/num_segs) == 3) {
genome[index] = (0.2 + 10. * Math.random()).toFixed(4); // Chassis Width
} else if (index % (genome.length/num_segs) == 4) {
if (Math.random() < 0.15) {
genome[index] = (genome[index]+1)%2
}
} else if (index % (genome.length/num_segs) == 5) {
genome[index] = (5. * Math.random()).toFixed(4); // Wheel Diameter
} else if (index % (genome.length/num_segs) == 6) {
genome[index] = (0.2 + 1. * Math.random()).toFixed(4); // Wheel Width
}
}
}
} else {
for (var index = 1; index < genome.length; ++index) {
if (Math.random() < mut_perc) {
// Turn chassis segment on or off.
if (index % (genome.length/num_segs) == 0) {
if (Math.random() < 0.15) {
genome[index] = 0;
} else {
genome[index] = 1;
}
} else if (index % (genome.length/num_segs) == 1) {
genome[index] = (1.+(3. * Math.randomGaussian(genome[index],0.25)).toFixed(4)/2.); // Chassis Length
if (genome[index] < 1.) {
genome[index] = 1.;
} else if (genome[index] > 4.) {
genome[index] = 4.;
}
} else if (index % (genome.length/num_segs) == 2) {
genome[index] = (0.2 + 5. * Math.randomGaussian(genome[index],0.25)).toFixed(4); // Chassis Height
if (genome[index] < 0.2) {
genome[index] = 0.2;
} else if (genome[index] > 5.2) {
genome[index] = 5.2;
}
} else if (index % (genome.length/num_segs) == 3) {
genome[index] = (0.2 + 10. * Math.randomGaussian(genome[index],0.25)).toFixed(4); // Chassis Width
if (genome[index] < 0.2) {
genome[index] = 0.2;
} else if (genome[index] > 10.2) {
genome[index] = 10.2;
}
} else if (index % (genome.length/num_segs) == 4) {
if (Math.random() < 0.15) {
genome[index] = (genome[index]+1)%2
}
} else if (index % (genome.length/num_segs) == 5) {
genome[index] = (0.2 + 4.8 * Math.randomGaussian(genome[index],0.25)).toFixed(4); // Wheel Diameter
if (genome[index] < 0.2) {
genome[index] = 0.2;
} else if (genome[index] > 5.) {
genome[index] = 5.;
}
} else if (index % (genome.length/num_segs) == 6) {
genome[index] = (0.2 + 1. * Math.randomGaussian(genome[index],0.25)).toFixed(4); // Wheel Width
if (genome[index] < 0.2) {
genome[index] = 0.2;
} else if (genome[index] > 1.2) {
genome[index] = 1.2;
}
}
}
}
}
}
this.getGenome = function() {
return genome;
}
this.setGenome = function(gen) {
genome = gen.slice();
}
}
car_genome.genomeDescr = function() {
var genomeDescription = []
for (var i = 0; i < 5; ++i) {
genomeDescription.push("Chassis Segment "+i.toString()+" Expressed");
genomeDescription.push("Chassis Segment "+i.toString()+" Length");
genomeDescription.push("Chassis Segment "+i.toString()+" Height");
genomeDescription.push("Chassis Segment "+i.toString()+" Width");
genomeDescription.push("Wheels "+i.toString()+" Expressed");
genomeDescription.push("Wheels "+i.toString()+" Diameter");
genomeDescription.push("Wheels "+i.toString()+" Width");
}
return genomeDescription;
}
function car() {
var car_chassis = [], car_wheels = [], constraints = [], wheel_motors = [], main_chassis = "", num_segs = 5;
// Simsy constants for materials, don't need to be creating and deleting these all the time.
var box_material = Physijs.createMaterial(
new THREE.MeshLambertMaterial(),
.8, // low friction
.6 // high restitution
);
var wheel_material = Physijs.createMaterial(
new THREE.MeshLambertMaterial({map: THREE.ImageUtils.loadTexture("assets/amiga.jpg")}),
.99, // low friction
.6 // high restitution
);
// box_material.color = new THREE.Color("rgb(255,0,0)");
var bodies = [];
for (var i = 0; i < num_segs; ++i) {
bodies.push(new THREE.CubeGeometry( 1, 1, 1 ));
bodies.push(new THREE.CylinderGeometry( 1,1,1,32 ));
bodies.push(new THREE.CylinderGeometry( 1,1,1,32 ));
}
var evo_color = new THREE.Color("rgb(255,0,0)");
var evo_wheel_color = new THREE.Color("rgb(255,255,255)");
var val_color = new THREE.Color("rgb(0,255,0)");
var val_wheel_color = new THREE.Color("rgb(56,56,56)");
var genome;
// Keep track of the robot's position for stalled purposes.
var current_pos = 0, prev_position_best = {x:0,y:0,z:0};
this.cameraFollow = function() {
return null;
}
this.setGenome = function(gen) {
prev_position_best.x = 0;
current_pos.x = 0;
genome = gen.slice();
}
this.update = function(steps) {
// Move the wheels.
for(var i = 0; i < wheel_motors.length; ++i) {
if (i % 2 == 0) {
wheel_motors[i].configureAngularMotor( 2, 1, 0, -10, 10000 );
} else {
wheel_motors[i].configureAngularMotor( 2, 1, 0, 10, 10000 );
}
wheel_motors[i].enableAngularMotor( 2 );
}
}
// Get the position of the main chassis.
this.position = function() {
prev_position_best.x = current_pos.x < prev_position_best.x ? current_pos.x : prev_position_best.x;
current_pos = car_chassis[0].position;
return current_pos;
}
// Check and see if the robot has stalled.
this.is_stalled = function() {
if (prev_position_best != 0) {
if (prev_position_best.x <= current_pos.x + 0.001) {
return true;
}
}
return false;
}
this.createRobot = function(validate) {
// Color body based on whether or not we're validating.
if (validate) {
box_material.color = val_color;
wheel_material.color = val_wheel_color;
} else {
box_material.color = evo_color;
wheel_material.color = evo_wheel_color;
}
// Constants for the robot.
var body_height = 4.0;
var bias = 0.5, relaxation = 0.0;
var pos = [0,body_height,0];
var num_genome_elem = genome.length/num_segs;
for ( var i = 0; i < num_segs; ++i) {
// Check to make sure the body segment is expressed.
if (genome[i*num_genome_elem] == 1) {
// Front body segment
box = new Physijs.BoxMesh(
bodies[i*3],
box_material,
genome[i*num_genome_elem+1]*genome[i*num_genome_elem+2]*genome[i*num_genome_elem+3]
);
box._physijs.collision_type = 4;
box._physijs.collision_masks = 1;
// Setup the position based on half the x length of the body.
if (i > 0) {
pos[0] -= genome[i*num_genome_elem+1]/2.;
}
box.position.set(pos[0],pos[1],pos[2]);
box.scale.set(1,1,1);
box.scale.set(genome[i*num_genome_elem+1],genome[i*num_genome_elem+2],genome[i*num_genome_elem+3])
box.castShadow = true;
Simulator.scene().add( box );
car_chassis.push( box );
// Check to see if the wheels are expressed.
if (genome[i*num_genome_elem+4] == 1) {
// Create two wheels to connect to the chassis.
var left_wheel = new Physijs.CylinderMesh(
bodies[i*3+1],
wheel_material,
genome[i*num_genome_elem+5]*genome[i*num_genome_elem+6]
);
left_wheel._physijs.collision_type = 4;
left_wheel._physijs.collision_masks = 1;
left_wheel.rotation.x = 1.57;
left_wheel.scale.set(genome[i*num_genome_elem+5],genome[i*num_genome_elem+6],genome[i*num_genome_elem+5]);
left_wheel.position.set(pos[0],pos[1],pos[2]-(genome[i*num_genome_elem+3]/2.+genome[i*num_genome_elem+6]/2.));
left_wheel.castShadow = true;
Simulator.scene().add( left_wheel );
car_wheels.push(left_wheel);
var right_wheel = new Physijs.CylinderMesh(
bodies[i*3+1],
wheel_material,
genome[i*num_genome_elem+5]*genome[i*num_genome_elem+6]
);
right_wheel._physijs.collision_type = 4;
right_wheel._physijs.collision_masks = 1;
right_wheel.position.set(pos[0],pos[1],pos[2]+(genome[i*num_genome_elem+3]/2.+genome[i*num_genome_elem+6]/2.));
right_wheel.rotation.x = 1.57;
right_wheel.scale.set(genome[i*num_genome_elem+5],genome[i*num_genome_elem+6],genome[i*num_genome_elem+5]);
right_wheel.castShadow = true;
Simulator.scene().add( right_wheel );
car_wheels.push(right_wheel);
// Add a hinge between the chassis and each wheel.
var wheel_joint = new Physijs.DOFConstraint(
box,left_wheel,
new THREE.Vector3( pos[0],pos[1],pos[2]-(genome[i*num_genome_elem+3]/2.) )
);
Simulator.scene().addConstraint(wheel_joint);
constraints.push(wheel_joint);
wheel_joint.setAngularLowerLimit({ x: 0, y: 0, z: 0 });
wheel_joint.setAngularUpperLimit({ x: 0, y: 0, z: 0 });
wheel_motors.push(wheel_joint);
// Add a hinge between the chassis and each wheel.
wheel_joint = new Physijs.DOFConstraint(
right_wheel,box,
new THREE.Vector3( pos[0],pos[1],pos[2]+(genome[i*num_genome_elem+3]/2.) )
);
Simulator.scene().addConstraint(wheel_joint);
constraints.push(wheel_joint);
wheel_joint.setAngularLowerLimit({ x: 0, y: 0, z: 0 });
wheel_joint.setAngularUpperLimit({ x: 0, y: 0, z: 0 });
wheel_motors.push(wheel_joint);
}
// Add the rest of the current box to position.
pos[0] -= genome[i*num_genome_elem+1]/2.;
if (i > 0 && car_chassis.length >= 2) {
// Add a constraint between the current body and previous one.
var hinge = new Physijs.HingeConstraint(car_chassis[car_chassis.length-1],car_chassis[car_chassis.length-2],
new THREE.Vector3(pos[0]+(genome[i*num_genome_elem+1]-0.0001),body_height,0), // Position of Hinge
new THREE.Vector3(1,0,0) // Axis of Rotation
);
Simulator.scene().addConstraint(hinge);
constraints.push(hinge);
hinge.setLimits(-0.17,0.17,bias,relaxation);
}
}
}
}
this.removeRobot = function() {
// Remove the hinges
for (var i = 0; i < constraints.length; ++i) {
Simulator.scene().removeConstraint(constraints[i]);
}
// Remove the bodies
for (var i = 0; i < car_chassis.length; ++i) {
Simulator.scene().remove(car_chassis[i]);
}
// Remove the bodies
for (var i = 0; i < car_wheels.length; ++i) {
Simulator.scene().remove(car_wheels[i]);
}
// Clear the arrays.
for (var i = 0; i < constraints.length; ++i) {
constraints[i] = null;
}
for (var i = 0; i < car_chassis.length; ++i) {
car_chassis[i] = null;
}
for (var i = 0; i < car_wheels.length; ++i) {
car_wheels[i] = null;
}
constraints = [];
car_chassis = [];
car_wheels = [];
wheel_motors = [];
}
};
|
Python
|
UTF-8
| 204
| 3.890625
| 4
|
[] |
no_license
|
# Problem Set 0
# Name: Austin Canada
# Time: 11:15
#
first_name = raw_input('What is your first name? ')
last_name = raw_input('What is your last name? ')
print 'Your name is ' + first_name + ' ' + last_name
|
Java
|
UTF-8
| 10,045
| 1.601563
| 2
|
[] |
no_license
|
package org.tmdd._303.messages;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;
/**
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><objectClass xmlns="http://www.tmdd.org/303/messages" xmlns:c2c="http://www.ntcip.org/c2c-message-administration" xmlns:itis="http://www.ITIS-Adopted-03-00-02" xmlns:lrms="http://www.LRMS-Adopted-02-00-00" xmlns:ntcip="http://www.ntcip.org/c2f-object-references" xmlns:xs="http://www.w3.org/2001/XMLSchema">Event</objectClass>
* </pre>
*
*
* <p>Java class for EventQualifier complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="EventQualifier">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice>
* <element name="qualifier-generic" type="{http://www.ITIS-Adopted-03-00-02}Qualifiers"/>
* <element name="location-generic" type="{http://www.ITIS-Adopted-03-00-02}GenericLocations"/>
* <element name="lane-roadway" type="{http://www.ITIS-Adopted-03-00-02}LaneRoadway"/>
* <element name="transit-mode" type="{http://www.ITIS-Adopted-03-00-02}TransitMode"/>
* <element name="vehicle-group-affected" type="{http://www.ITIS-Adopted-03-00-02}VehicleGroupAffected"/>
* <element name="traveler-group-affected" type="{http://www.ITIS-Adopted-03-00-02}TravelerGroupAffected"/>
* <element name="responder-group-affected" type="{http://www.ITIS-Adopted-03-00-02}ResponderGroupAffected"/>
* <element name="incident-response-equipment" type="{http://www.ITIS-Adopted-03-00-02}IncidentResponseEquipment"/>
* <element name="transit-locations" type="{http://www.ITIS-Adopted-03-00-02}GenericLocations"/>
* <element name="incident-response-status" type="{http://www.ITIS-Adopted-03-00-02}IncidentResponseStatus"/>
* <any processContents='lax' namespace='##other' minOccurs="0"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EventQualifier", propOrder = {
"qualifierGeneric",
"locationGeneric",
"laneRoadway",
"transitMode",
"vehicleGroupAffected",
"travelerGroupAffected",
"responderGroupAffected",
"incidentResponseEquipment",
"transitLocations",
"incidentResponseStatus",
"any"
})
public class EventQualifier
implements Serializable
{
private final static long serialVersionUID = -1L;
@XmlElement(name = "qualifier-generic")
@XmlSchemaType(name = "anySimpleType")
protected String qualifierGeneric;
@XmlElement(name = "location-generic")
@XmlSchemaType(name = "anySimpleType")
protected String locationGeneric;
@XmlElement(name = "lane-roadway")
@XmlSchemaType(name = "anySimpleType")
protected String laneRoadway;
@XmlElement(name = "transit-mode")
@XmlSchemaType(name = "anySimpleType")
protected String transitMode;
@XmlElement(name = "vehicle-group-affected")
@XmlSchemaType(name = "anySimpleType")
protected String vehicleGroupAffected;
@XmlElement(name = "traveler-group-affected")
@XmlSchemaType(name = "anySimpleType")
protected String travelerGroupAffected;
@XmlElement(name = "responder-group-affected")
@XmlSchemaType(name = "anySimpleType")
protected String responderGroupAffected;
@XmlElement(name = "incident-response-equipment")
@XmlSchemaType(name = "anySimpleType")
protected String incidentResponseEquipment;
@XmlElement(name = "transit-locations")
@XmlSchemaType(name = "anySimpleType")
protected String transitLocations;
@XmlElement(name = "incident-response-status")
@XmlSchemaType(name = "anySimpleType")
protected String incidentResponseStatus;
@XmlAnyElement(lax = true)
protected Object any;
/**
* Gets the value of the qualifierGeneric property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQualifierGeneric() {
return qualifierGeneric;
}
/**
* Sets the value of the qualifierGeneric property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQualifierGeneric(String value) {
this.qualifierGeneric = value;
}
/**
* Gets the value of the locationGeneric property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLocationGeneric() {
return locationGeneric;
}
/**
* Sets the value of the locationGeneric property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLocationGeneric(String value) {
this.locationGeneric = value;
}
/**
* Gets the value of the laneRoadway property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLaneRoadway() {
return laneRoadway;
}
/**
* Sets the value of the laneRoadway property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLaneRoadway(String value) {
this.laneRoadway = value;
}
/**
* Gets the value of the transitMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransitMode() {
return transitMode;
}
/**
* Sets the value of the transitMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransitMode(String value) {
this.transitMode = value;
}
/**
* Gets the value of the vehicleGroupAffected property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVehicleGroupAffected() {
return vehicleGroupAffected;
}
/**
* Sets the value of the vehicleGroupAffected property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVehicleGroupAffected(String value) {
this.vehicleGroupAffected = value;
}
/**
* Gets the value of the travelerGroupAffected property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTravelerGroupAffected() {
return travelerGroupAffected;
}
/**
* Sets the value of the travelerGroupAffected property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTravelerGroupAffected(String value) {
this.travelerGroupAffected = value;
}
/**
* Gets the value of the responderGroupAffected property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getResponderGroupAffected() {
return responderGroupAffected;
}
/**
* Sets the value of the responderGroupAffected property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setResponderGroupAffected(String value) {
this.responderGroupAffected = value;
}
/**
* Gets the value of the incidentResponseEquipment property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIncidentResponseEquipment() {
return incidentResponseEquipment;
}
/**
* Sets the value of the incidentResponseEquipment property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIncidentResponseEquipment(String value) {
this.incidentResponseEquipment = value;
}
/**
* Gets the value of the transitLocations property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransitLocations() {
return transitLocations;
}
/**
* Sets the value of the transitLocations property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransitLocations(String value) {
this.transitLocations = value;
}
/**
* Gets the value of the incidentResponseStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIncidentResponseStatus() {
return incidentResponseStatus;
}
/**
* Sets the value of the incidentResponseStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIncidentResponseStatus(String value) {
this.incidentResponseStatus = value;
}
/**
* Gets the value of the any property.
*
* @return
* possible object is
* {@link Object }
* {@link Element }
*
*/
public Object getAny() {
return any;
}
/**
* Sets the value of the any property.
*
* @param value
* allowed object is
* {@link Object }
* {@link Element }
*
*/
public void setAny(Object value) {
this.any = value;
}
}
|
Java
|
UTF-8
| 410
| 1.679688
| 2
|
[] |
no_license
|
package org.zywx.wbpalmstar.plugin.uexweixin.vo;
import java.io.Serializable;
public class CallbackWindowNameVO implements Serializable{
private static final long serialVersionUID = -5879823128452414511L;
private String windowName;
public String getWindowName() {
return windowName;
}
public void setWindowName(String windowName) {
this.windowName = windowName;
}
}
|
TypeScript
|
UTF-8
| 2,066
| 2.8125
| 3
|
[] |
no_license
|
import { HashGenerator } from "../middleware/HashManager";
import { TokenGenerator } from "../middleware/TokenGenerator";
import { IdGenerator } from "../middleware/IdGenerator";
import { InvalidInputError } from "../Error/InvalidInputError";
import { BandDatabase } from "../data/BandDatabase";
import { Unauthorized } from "../Error/Unauthorized";
import { NotFound } from "../Error/NotFound";
export class BandBusiness {
constructor(
private bandDatabase: BandDatabase,
private hashGenerator: HashGenerator,
private tokenGenerator: TokenGenerator,
private idGenerator: IdGenerator
) {}
public async fetchBands(token: string) {
const auth = await this.tokenGenerator.verify(token);
if (auth !== "ADMIN") {
throw new Unauthorized("You do not have access to this function.");
}
const bands = await this.bandDatabase.fetchBands();
return bands;
}
public async login(nickname: string, password: string) {
if (!nickname || !password) {
throw new InvalidInputError("You need both parameters to log in!");
}
const user = await this.bandDatabase.login(nickname);
if (!user) {
throw new NotFound("User not found");
}
const validatePassword = await this.hashGenerator.compareHash(
password,
user.getPassword()
);
if (!validatePassword) {
throw new InvalidInputError("Invalid password");
}
if (user.getIsApproved === 0) {
throw new Unauthorized(
"Your band still needs to be approved by an admin before you can log in"
);
}
const token = this.tokenGenerator.generate({
id: user.getId(),
type: user.getType(),
});
return token;
}
public async approve(name: string, token: string) {
const auth = await this.tokenGenerator.verify(token);
if (auth !== "ADMIN") {
throw new Unauthorized("You do not have permission to do that.");
}
if (!name) {
throw new NotFound("There is no such band in our database.");
}
await this.bandDatabase.approveBand(name);
}
}
|
Shell
|
UTF-8
| 492
| 3.03125
| 3
|
[] |
no_license
|
#!/bin/bash
files="./incorrect_user_list_add_multiple_no_passwd.txt ./incorrect_user_list_remove_non_existing_user.txt ./incorrect_user_list_add_3_fields.txt ./correct_user_list.txt ./incorrect_user_list_add_no_passwd.txt"
for file in ${files}
do
while read LINE
do
user=$(echo "$LINE" | cut -d',' -f1)
sudo -i -- /bin/bash -c "id ${user} > /dev/null 2>&1 && /usr/sbin/userdel -r -f ${user} > /dev/null 2>&1"
done < "$file"
done
# ensure return 0 status
exit 0
|
Java
|
UTF-8
| 1,228
| 1.734375
| 2
|
[] |
no_license
|
package com.myinfosysprogram.repository;
import java.lang.System;
@kotlin.Metadata(mv = {1, 4, 2}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000\u0014\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0005\b\u0016\u0018\u00002\u00020\u0001B\u0005\u00a2\u0006\u0002\u0010\u0002R\u001a\u0010\u0003\u001a\u00020\u0004X\u0086\u000e\u00a2\u0006\u000e\n\u0000\u001a\u0004\b\u0005\u0010\u0006\"\u0004\b\u0007\u0010\b\u00a8\u0006\t"}, d2 = {"Lcom/myinfosysprogram/repository/BaseRepository;", "", "()V", "appExecutor", "Lcom/myinfosysprogram/retrofit/AppExecutors;", "getAppExecutor", "()Lcom/myinfosysprogram/retrofit/AppExecutors;", "setAppExecutor", "(Lcom/myinfosysprogram/retrofit/AppExecutors;)V", "app_debug"})
public class BaseRepository {
@org.jetbrains.annotations.NotNull()
private com.myinfosysprogram.retrofit.AppExecutors appExecutor;
@org.jetbrains.annotations.NotNull()
public final com.myinfosysprogram.retrofit.AppExecutors getAppExecutor() {
return null;
}
public final void setAppExecutor(@org.jetbrains.annotations.NotNull()
com.myinfosysprogram.retrofit.AppExecutors p0) {
}
public BaseRepository() {
super();
}
}
|
Java
|
UTF-8
| 8,276
| 2.1875
| 2
|
[] |
no_license
|
package com.example.pixelgame.Views;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import com.example.pixelgame.Bluetooth;
import com.example.pixelgame.R;
import com.example.pixelgame.Views.Game.GameActivity;
import com.example.pixelgame.Views.ListAdapter.MobileDeviceListAdapter;
import java.io.Closeable;
import java.io.IOException;
public class ConnectionActivity extends BaseView {
private static final String TAG = "CONNECTION";
private MobileDeviceListAdapter devices;
ListView listView;
AcceptThread acceptThread;
ConnectThread connectThread;
// Broadcasting Variables
private static final IntentFilter DEVICE_FOUND = new IntentFilter(BluetoothDevice.ACTION_FOUND);
private final BroadcastReceiver discoveringReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connection);
Bluetooth.enable();
initViews();
registerReceiver(Bluetooth.statusReceiver, Bluetooth.statusChanged);
}
private void initViews() {
initListView();
initListAdapter();
initButtons();
}
private void initListAdapter() {
Log.i(TAG, "reset List");
devices = new MobileDeviceListAdapter(this);
listView.setAdapter(devices);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
devices.addAll(Bluetooth.getBonded());
Bluetooth.discover();
}
private void initButtons() {
Button discover = findViewById(R.id.btn_discover);
discover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bluetooth.discover();
}
});
Button reset = findViewById(R.id.btn_reset);
reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initListAdapter();
}
});
}
private void initListView() {
listView = findViewById(R.id.list_mobile_device);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final BluetoothDevice device = devices.getItem(position);
if (acceptThread == null || !acceptThread.allowed.equals(device)) {
killThreads();
tryConnection(device);
} else if (acceptThread.allowed.equals(device)) {
Log.i(TAG, "Started new connection try to " + device.getName());
killConnectThread();
connectTo(device);
}
}
});
}
private void tryConnection(BluetoothDevice device) {
if (device != null) {
Bluetooth.cancelDiscovery();
awaitConnection(device);
connectTo(device);
}
}
private void awaitConnection(BluetoothDevice pairingDevice) {
if (acceptThread == null) {
Log.i(TAG, "await connection of " + pairingDevice.getName());
acceptThread = new AcceptThread(pairingDevice);
acceptThread.start();
}
}
private void connectTo(BluetoothDevice pairingDevice) {
if (connectThread == null) {
Log.i(TAG, "connect to " + pairingDevice.getName());
connectThread = new ConnectThread(pairingDevice);
connectThread.start();
}
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(discoveringReceiver, DEVICE_FOUND);
}
@Override
protected void onPause() {
unregisterReceiver(discoveringReceiver);
killThreads();
super.onPause();
}
@Override
protected void onDestroy() {
unregisterReceiver(Bluetooth.statusReceiver);
super.onDestroy();
}
private synchronized void launchWaitingArea(BluetoothSocket socket) {
killThreads();
Bluetooth.setConnection(socket);
launchActivity(GameActivity.class);
}
private synchronized void enable() {
killThreads();
Bluetooth.discover();
}
private synchronized void killThreads() {
killAcceptThread();
killConnectThread();
}
private void killAcceptThread() {
if (acceptThread != null) {
acceptThread.close();
acceptThread = null;
}
}
private void killConnectThread() {
if (connectThread != null) {
connectThread.close();
connectThread = null;
}
}
private static abstract class BluetoothThread<Socket extends Closeable> extends Thread implements Closeable {
Socket socket = null;
@Override
public void close() {
try {
socket.close();
} catch (IOException e) {
Log.d(TAG, "closing socket failed");
e.printStackTrace();
}
}
}
private class AcceptThread extends BluetoothThread<BluetoothServerSocket> {
final BluetoothDevice allowed;
AcceptThread(BluetoothDevice allowed) {
this.allowed = allowed;
}
@Override
public void run() {
initServerSocket();
listen();
enable();
}
private void initServerSocket() {
try {
socket = Bluetooth.getServerSocket();
} catch (IOException e) {
showMessage(R.string.errM_missingSocket);
}
}
private void listen() {
BluetoothSocket connectedSocket;
try {
Log.i(TAG, "socket accept");
connectedSocket = socket.accept();
if (connectedSocket != null) {
final BluetoothDevice remote = connectedSocket.getRemoteDevice();
if (remote.equals(allowed)) {
launchWaitingArea(connectedSocket);
} else {
Log.d(TAG, "found illegal device: " + remote.getName());
}
} else {
Log.d(TAG, "could not find device in time");
}
} catch (IOException e) {
close();
Log.d(TAG, "unknown error");
e.printStackTrace();
}
}
}
private class ConnectThread extends BluetoothThread<BluetoothSocket> {
ConnectThread(BluetoothDevice toConnect) {
BluetoothSocket test = null;
try {
test = Bluetooth.getConnectionSocket(toConnect);
} catch (IOException e) {
Log.d(TAG, "Did not receive bluetooth socket.");
}
socket = test;
}
@Override
public void run() {
if (socket != null) {
try {
Log.i(TAG, "socket connect");
socket.connect();
launchWaitingArea(socket);
} catch (IOException e) {
close();
e.printStackTrace();
Log.d(TAG, "Could not connect to device");
}
}
}
}
}
|
Shell
|
UTF-8
| 756
| 4.375
| 4
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/sh
#
# Show each commit from an object.
#
# $1 - Optional name of the object to show commits from. Values can be a ref, a
# branch name, a tag, etc. Default is master.
# $2 - Optional number of lines of context to use in the diff. Default is 20.
#
# Examples
#
# git show-commits
# git show-commits master 5
#
if [[ -z $1 ]]; then
branch='master'
else
branch=$1
fi
if [[ -z $2 ]]; then
context=20
else
context=$2
fi
for ref in $(git log $branch.. | grep 'commit ' | cut -d\ -f2 | tail -r); do
echo 'About to show' $ref
git show -U$context --color=always $ref | less -r
done
if [[ -z $ref ]]; then
echo 'Well, maybe you should provide a starting point. Ex.:'
echo 'git show-commits HEAD~5'
exit 1
fi
|
Java
|
UTF-8
| 2,330
| 2.28125
| 2
|
[] |
no_license
|
package clientcore.external.controller;
import java.util.List;
import org.pmw.tinylog.Logger;
import clientcore.command.CommandOutputVo;
import clientcore.command.CommandPocesser;
import clientcore.command.CommandVO;
import clientcore.constants.GlobalConstants;
import clientcore.constants.QueueNames;
import clientcore.output.processor.JobProcesser;
import clientcore.output.processor.OutputConverter;
import clientcore.staticobjects.GlobalQueues;
import common.database.io.DBFileHandler;
import common.exceptions.SqQueueException;
import common.logger.config.LoggerConfiguration;
import common.util.queue.SqQueue;
public class Loader {
private static JobProcesser jobProcesser = null;
private static DBFileHandler dbFileHandler = null;
private static CommandPocesser commandPocesser = null;
public static void main(String[] args) {
initiateEnvironment();
while( true ) {
try {
jobProcesser.startProcessingJobs();
commandPocesser.processInputQueue();
processOutput();
Thread.sleep(1 * 60 * 1000);
} catch (Exception e) {
Logger.error(e);
}
}
}
private static void initiateEnvironment() {
try {
GlobalQueues.commandQueue = new SqQueue<CommandVO>();
LoggerConfiguration.init();
dbFileHandler = new DBFileHandler();
commandPocesser = new CommandPocesser();
List<Object> cronJobs = dbFileHandler.readObjects(GlobalConstants.JOBS_PERSISTANCE_LOCATION);
jobProcesser = new JobProcesser(cronJobs);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List<CommandOutputVo> processOutput() {
List<CommandVO> commandResult = null;
OutputConverter outputConverter = null;
List<CommandOutputVo> commandOutputs = null;
try {
outputConverter = new OutputConverter();
commandResult = GlobalQueues.commandQueue.getAllMessages(QueueNames.COMMAND_OUT.toString());
commandOutputs = outputConverter.convertCommandOutputs(commandResult);
for(CommandOutputVo commandOutput : commandOutputs) {
System.out.println(commandOutput.toJSON());
}
} catch (SqQueueException e) {
Logger.info("Queue is not available");
}
return commandOutputs;
}
}
|
Java
|
UTF-8
| 2,407
| 2.375
| 2
|
[] |
no_license
|
package com.datastax.enterprise.controller;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.datastax.enterprise.iot.CSV;
import com.datastax.enterprise.iot.IoTDocumentAPIRepository;
import com.datastax.enterprise.iot.Power;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
public class IoTController {
@Autowired
private IoTDocumentAPIRepository iotRepository;
String IOT_DATA_FILEPATH = "household-power-consumption-QueryResult.csv";
@GetMapping("/simulateIoT")
public String simulateIoT(Model model) throws FileNotFoundException, IOException {
System.out.println("Simulating IoT Data ....");
List<Power> iotsensors = convertCSV2JSON(IOT_DATA_FILEPATH);
int i=0;
for(Power power : iotsensors) {
iotRepository.createIoTDocument(power);
i++;
if(i==100) break; // if its a large file, upload is restricted to first 100 records
}
System.out.println("IoT Simulation Complete with "+i+" documents");
model.addAttribute("iotsensor", iotsensors);
return "iot";
}
public List<Power> convertCSV2JSON(String csvFile) throws FileNotFoundException, IOException{
List<Power> iotList = new ArrayList<Power>();
ObjectMapper mapper = new ObjectMapper();
try (InputStream in = new FileInputStream(csvFile);) {
CSV csv = new CSV(true, ',', in );
List < String > fieldNames = null;
if (csv.hasNext()) fieldNames = new ArrayList < > (csv.next());
List < Map < String, String >> list = new ArrayList < > ();
while (csv.hasNext()) {
List < String > x = csv.next();
Map < String, String > obj = new LinkedHashMap < > ();
for (int i = 0; i < fieldNames.size(); i++) {
obj.put(fieldNames.get(i), x.get(i));
}
Power power = mapper.convertValue(obj, Power.class);
iotList.add(power);
}
}
return iotList;
}
}
|
Java
|
UTF-8
| 930
| 2.140625
| 2
|
[] |
no_license
|
package ch.hsr.traildevil.util;
public class Constants {
/** The log tag in order to filter the log output */
public static final String TAG = "traildevil";
/** The location of the DB */
public static String DB_LOCATION = "/data/data/ch.hsr.traildevil/files";
/** productive URL */
public static final String TRAILS_URL = "http://152.96.80.18:8080/api/trails?$orderby=favorits%20desc";
/** test URL. Make sure that it points to your test server (not localhost, since we'are on the device)! */
public static final String TEST_TRAILS_URL = "http://172.30.51.223:8080/TrailDevilsServer/trails";
/** How many stars can be maximum filled in the Trail List */
public static final int MAX_FAVORITE_STARS = 5;
/** The last modified timestamp of all trail. This key could be used to lookup the value from shared preferences.*/
public static final String LAST_MODIFIED_TIMESTAMP_KEY = "LAST_MODIFIED_TIMESTAMP";
}
|
Markdown
|
UTF-8
| 1,525
| 2.53125
| 3
|
[] |
no_license
|
# ORGA PROYECTO 1 : PLOTTER SERIAL 📌
## Explicación de Puerto Serial 🔧
El puerto serial funciona para la comunicación entre dispositivos electrónicos.
Quién realiza esta comunicación de datos, es conocido como
**UART**
-Universal
-Asynchronous
-Receiver
-Transmitter
La comunicación se realiza por medio de paquetes de bits, conocidos como tramas.
El primer bit de envío, será el bit menos significativo del paquete.
Para reconocer una trama, primero se ingresa un bit de inicio por un periodo de tiempo llamado, *tiempo de bit.*
Este tiempo de bit es el tiempo en que una señal *se mantiene por el transmisor* de información del puerto serie de igual forma se puede decir que es la velocidad de envío (**BAUD-RATE**)
Y cada dato de envío se tardará este tiempo de bit en salir del transmisor de datos.
Por ultimo se le enviará un **bit de stop** que terminará la trama (paquete) de envio, provisionalmente se identificará con un 1 lógico.
## Construido con 🛠️
* [Visual Studio] - Entorno de Desarrollo Integrado (IDE) utilizado.
* [C#] - Lenguaje de Programación utilizado.
## Autores ✒️
* **Cristian Suy** - *[Coordinador] 201700918* - [CSuy](https://github.com/CSuy)
* **Yelstin de León** - *201602836* - [airton47](https://github.com/airton47)
* **Ricardo Pérez** - *201700524* - [Ricardo16X](https://github.com/Ricardo16X)
* **Byron Gómez** - *201700544* - [ByrCas](https://github.com/ByrCas)
* **Diego Méndez** - *201712680* - [DiegoALbert6799](https://github.com/DiegoALbert6799)
|
Java
|
UTF-8
| 4,056
| 2.515625
| 3
|
[] |
no_license
|
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class UserlistServlet extends HttpServlet {
private String _hostname = null;
private String _dbname = null;
private String _username = null;
private String _password = null;
public void init() throws ServletException {
// iniファイルから自分のデータベース情報を読み込む
String iniFilePath = getServletConfig().getServletContext()
.getRealPath("WEB-INF/le4db.ini");
try {
FileInputStream fis = new FileInputStream(iniFilePath);
Properties prop = new Properties();
prop.load(fis);
_hostname = prop.getProperty("hostname");
_dbname = prop.getProperty("dbname");
_username = prop.getProperty("username");
_password = prop.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h3>ユーザリスト</h3>");
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://" + _hostname
+ ":5432/" + _dbname, _username, _password);
stmt = conn.createStatement();
out.println("<table border=\"1\">");
out.println("<tr><th>読者ID</th><th>ユーザ名</th><th>パスワード</th></tr>");
ResultSet rs = stmt.executeQuery("SELECT reader_nickname.readerid, readername, password FROM reader_nickname, reader_pass WHERE reader_nickname.readerid = reader_pass.readerid");
while (rs.next()) {
int readerID = rs.getInt("readerid");
String readerName = rs.getString("readername");
String readerPassword = rs.getString("password");
out.println("<tr>");
/*out.println("<td><a href=\"item?readerid=" + readerID + "\">" + readerID
+ "</a></td>");
今後拡張する際に, 管理者からユーザごとの読書歴や評価を見られるようにするためには,
ここの"item"を別のページにする必要がある
*/
//out.println("<td>" + readerID + "</td>");
out.println("<td><a href=\"readers?readerid=" + readerID + "\">" + readerID
+ "</a></td>");
out.println("<td>" + readerName + "</td>");
out.println("<td>" + readerPassword + "</td>");
out.println("</tr>");
}
rs.close();
out.println("</table>");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
out.println("<h3>新規登録</h3>");
out.println("<form action=\"useradd\" method=\"GET\">");
//useraddページに飛ばす
out.println("ユーザ名: ");
out.println("<input type=\"text\" name=\"add_nickname\"/>");
out.println("<br/>");
out.println("パスワード: ");
out.println("<input type=\"text\" name=\"add_password\"/>");
out.println("<br/>");
out.println("<input type=\"submit\" value=\"登録\"/>");
out.println("</form>");
out.println("<br/>");
out.println("<a href=\"list\">管理者用ページに戻る</a>");
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void destroy() {
}
}
|
JavaScript
|
UTF-8
| 247
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
import Deck from './deck';
import Card from './card';
const firstCard = new Card('Ace', 'Spade');
console.log('Duy\'s first card is the ' + firstCard.rank + ' of ' + firstCard.suit + 's!');
const firstDeck = new Deck();
console.log(firstDeck);
|
JavaScript
|
UTF-8
| 1,293
| 3.734375
| 4
|
[] |
no_license
|
// var name = "Umar"
// alert("Thanks" + " " + name)
var userName = "Umar"
// var greeting = "Thanks"
// var shoped = "Pants"
// var finalRes = greeting + " " + userName + " " + "for Shopping" + " " + shoped
// // alert(greeting + " " + userName + " " + "for Shopping" + " " + shoped)
// alert(finalRes)
// alert("78" + "3")
// alert("2 plus 2 equals " + 2 + 2); //(2+2)
// alert(userName)
// console.log(userName)
// document.write(userName)
// var question = "What is your name?"
// var myPrompt = prompt( question , userName)
// console.log(myPrompt)
// var myQues = "What is your age"
// var defAns = 18
// var ageThisYear = +prompt(myQues , defAns) // "20" //20 //"Twenty"
// var newAge = ageThisYear + 1 //
// console.log(newAge)
// var a = 10
// document.write("The value of a is " + a + "<br>")
// document.write("The value of ++a is " + ++a + "<br>")
// document.write("The value of a++ is " + a++ + "<br>") //11 ==> 12
// document.write("Now the value of a is " + a + "<br>")
var subName = prompt("Enter your sub name?")
var subMarks = prompt("Enter your " + subName +" Marks?")
var totalMarks = 100
document.write("SUBJECT : "+ subName + " " + "TOTAL MARKS: " +totalMarks + " " + "OBTAINED MARKS: " +subMarks + " " + "PERCENTAGE" + (subMarks*100)/100 + "%")
|
Python
|
UTF-8
| 1,303
| 3.015625
| 3
|
[] |
no_license
|
import time
class Tour:
""" Round class"""
def __init__(self, number):
self.nom = f"Round {number}"
self.date_debut = None
self.heure_debut = None
self.date_fin = None
self.heure_fin = None
self.matchs = []
self.matchs_id = []
self.en_cours = False
self.fini = False
def __repr__(self):
return f"{self.nom}"
def enregistrer_matchs_tour(self, binomes):
"""
Logging of matches in a round
:param binomes: list of pairs
"""
for binome in binomes:
match = ([binome[0], binome[0].points],
[binome[1], binome[1].points])
match_id = ([binome[0].id, binome[0].points],
[binome[1].id, binome[1].points])
self.matchs.append(match)
self.matchs_id.append(match_id)
def enregistrer_temps_debut(self):
""" Method which collect time at the start of a round"""
self.date_debut = time.strftime("%d/%m/%Y")
self.heure_debut = time.strftime("%I:%M:%S %p")
def enregistrer_temps_fin(self):
""" Method which collect time at the end of a round"""
self.date_fin = time.strftime("%d/%m/%Y")
self.heure_fin = time.strftime("%I:%M:%S %p")
|
Python
|
UTF-8
| 2,729
| 2.625
| 3
|
[] |
no_license
|
"""
** coded by shibinmak on 7/9/18 **
** I pledge to do my best **
** May all beings be Happy,Peaceful,Liberated **
"""
from config import config
from tfannotation import tfAnnotation
import os
import tensorflow as tf
from sklearn.model_selection import train_test_split
from xml_to_csv import xml2csv
def main(_):
xml2csv()
f = open(config.CLASSES_FILE, 'w')
for (k, v) in config.CLASSES.items():
item = ("item{\n""\t id: " + str(v) + "\n"
"\tname: '" + k + "'\n""}\n")
f.write(item)
f.close()
D = {}
rows = open(config.ANNOT_PATH).read().strip().split('\n')
for row in rows[1:]:
row = (row.split(','))
(imagepath, width, height, label, xmin, ymin, xmax, ymax) = row
(xmin, ymin) = (float(xmin), float(ymin))
(xmax, ymax) = (float(xmax), float(ymax))
(width, height) = (int(width), int(height))
b = D.get(imagepath, [])
b.append((label, (width, height), (xmin, ymin, xmax, ymax)))
D[imagepath] = b
(trainKeys, testKeys) = train_test_split(list(D.keys()), test_size=config.TEST_SIZE)
dataset = [('train', trainKeys, config.TRAIN_RECORD),
('test', testKeys, config.TEST_RECORD)]
for (dtype, keys, output) in dataset:
print('[INFO] processing {}'.format(dtype))
writer = tf.python_io.TFRecordWriter(output)
total = 0
for k in keys:
encoded = tf.gfile.GFile(k, 'rb').read()
encoded = bytes(encoded)
tfAnnot = tfAnnotation()
filename = os.path.basename(k)
encoding = filename[filename.rfind('.') + 1:]
(width, height) = D[k][0][1]
tfAnnot.filename = filename
tfAnnot.image = encoded
tfAnnot.encoding = encoding
tfAnnot.width = width
tfAnnot.height = height
for (label, (w, h), (xmin, ymin, xmax, ymax)) in D[k]:
xmin /= w
xmax /= w
ymin /= h
ymax /= h
tfAnnot.xmins.append(xmin)
tfAnnot.ymins.append(ymin)
tfAnnot.xmaxs.append(xmax)
tfAnnot.ymaxs.append(ymax)
tfAnnot.textLabels.append(label.encode('utf8'))
tfAnnot.classes.append(config.CLASSES[label])
total += 1
features = tf.train.Features(feature=tfAnnot.build())
example = tf.train.Example(features=features)
writer.write(example.SerializeToString())
writer.close()
print('[INFO] {} examples saved for {}'.format(total, dtype))
if __name__ == '__main__':
tf.app.run()
|
PHP
|
UTF-8
| 2,176
| 2.890625
| 3
|
[] |
no_license
|
<?php
declare(strict_types = 1);
namespace Atelir\ReadFrontPage;
use Atelir\Utility\CanRenderPost;
use Atelir\Utility\HasPostUri;
use Atelir\Utility\Postgresql;
final
class FeaturedPost
{
use CanRenderPost;
use HasPostUri;
public string $userSlug;
public string $userName;
public string $projectSlug;
public string $projectName;
public string $postSlug;
public string $title;
public string $content;
/** @psalm-pure */
public
function __construct(
string $userSlug,
string $userName,
string $projectSlug,
string $projectName,
string $postSlug,
string $title,
string $content
)
{
$this->userSlug = $userSlug;
$this->userName = $userName;
$this->projectSlug = $projectSlug;
$this->projectName = $projectName;
$this->postSlug = $postSlug;
$this->title = $title;
$this->content = $content;
}
/**
* @return iterable<int,FeaturedPost>
*/
public static
function fetch(Postgresql $postgresql): iterable
{
$rows = $postgresql->query('
SELECT
user_slug,
users.name,
project_slug,
projects.name,
posts.post_slug,
posts.title,
posts.content
FROM
atelir.posts
JOIN atelir.users USING (user_slug)
JOIN atelir.projects USING (user_slug, project_slug)
WHERE posts.published IS NOT NULL
ORDER BY posts.published DESC
');
foreach ($rows as $row) {
assert($row[0] !== NULL);
assert($row[1] !== NULL);
assert($row[2] !== NULL);
assert($row[3] !== NULL);
assert($row[4] !== NULL);
assert($row[5] !== NULL);
assert($row[6] !== NULL);
yield new FeaturedPost(
$row[0],
$row[1],
$row[2],
$row[3],
$row[4],
$row[5],
$row[6],
);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.