language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 679 | 2.703125 | 3 |
[] |
no_license
|
#ifndef BULLETSMANAGER_H
#define BULLETSMANAGER_H
#include "Bullet.h"
#include "Shooter.h"
#include <iostream>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
class BulletsManager : public Shooter
{
public :
BulletsManager();
inline void addExploser2Bullets(Exploser *exploser) { explosers.push_back(exploser); };
inline void clearBullets() { bullets.clear(); };
void moveBullets();
void drawBullets(sf::RenderWindow &window);
void notifyShoot(sf::Vector2f pos, sf::Vector2f target, bool faction, void *from);
private :
std::vector<Exploser *> explosers;
std::vector<Bullet> bullets;
sf::Texture texture;
};
#endif
|
Python
|
UTF-8
| 1,234 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.offline import offline
import plotly.express as px
class dataGraph():
def __init__(self):
raw_df = pd.read_csv("data.csv")
self.df = raw_df.set_index("time")
def time_graph(self):
'''
This function creates a graph of the data evolution over time,
in the range start_time - end_time.
:param start_time:
:param end_time:
'''
data_by_currency = []
for i, col in enumerate(self.df.columns):
data_by_currency.append(
go.Scatter(
x = self.df.index,
y = self.df[col],
mode = 'lines',
name = col,
)
)
layout = go.Layout(
title = "Currency value over time",
xaxis = dict(
title = "time",
tickmode = 'linear',
tick0 = 0.5,
dtick= 10,
),
yaxis = dict(
title = "Value (EUR)",
),
)
fig = go.Figure(data=data_by_currency, layout=layout)
return fig
|
Markdown
|
UTF-8
| 10,682 | 2.65625 | 3 |
[] |
no_license
|
---
title: Le désir de la grande aventure
author: Pierre Berthomieu
---
# Le désir de la grande aventure
Aventurier de la pellicule, John Huston est l'auteur d'une œuvre hétéroclite et surprenante. S'il sert les genres du cinéma hollywoodien (le film noir en particulier avec *Le Faucon maltais* ou *Quand la Ville dort*), il se lance aussi dans des projets ambitieux d'adaptations littéraires (*Moby Dick*, *Le Malin*, *Au-dessus du volcan*) tout autant que dans d'improbables coproductions internationales. L'hétérogénéité de son cinéma en fait un auteur qui a su singulièrement dépasser les conventions du classicisme.
« L'histoire possède cette ample trajectoire qui, dans nos cœurs, survit même à la vieillesse – le désir perpétuel de la grande aventure. » Longtemps, John Huston songea à son adaptation de Kipling, *L'Homme qui voulut être roi*, finalement tournée en 1975. L'inlassable vibration d'aventure était si justement adéquate à son propre destin – amoureux du souffle plus encore que de l'œuvre achevée. Cette carrière excentrique et vorace laisse une impression d'immense exploration et de résultats étranges, entre œuvres majeures et pièces désinvoltes ou négligées en fin de carrière. John Huston était lui-même le héros de sa propre fiction, créateur rebelle, rabelaisien, séducteur, chasseur et grand buveur, artiste passionné, raconteur de fables et destructeur – tel le portrait qu'en fit Peter Viertel dans son roman *Chasseur blanc, cœur noir*, inspiré par le tournage d'*African Queen* et plus tard filmé par Clint Eastwood.
La saga familiale des Huston commença avec Walter, star de la scène et de l'écran dans les années 30-40, père de John (qui naît en 1906), pour se prolonger avec la carrière d'Angelica et Danny, enfants du cinéaste, et de Jack, son petit-fils. Dès le parlant, John travailla comme scénariste puis comme réalisateur à succès à partir du *Faucon maltais* (1941), mais il fut surtout un cinéaste-écrivain, cultivé, passionné de littérature, soucieux de signer ses propres sujets et avide d'autonomie. Dès ses débuts, il filme avec économie, conçoit le montage au tournage pour maîtriser « son » œuvre. Toute la carrière de Huston semble ensuite répondre à une quête de liberté, marquée par de grandes espérances artistiques et doublée des extravagances d'un fanfaron flamboyant, faussement superficiel, et acteur de personnages souvent démesurés (l'ogre gangster de *Chinatown*). Proche d'intellectuels engagés comme Richard Brooks (sur les thèmes de la rébellion et la tyrannie en Amérique latine, *Les Insurgés* de Huston, sorti en 1949, est parallèle à *Cas de conscience* de Brooks, sorti l'année suivante), ami fidèle de William Wyler et Lewis Milestone, Huston apparaît comme trait d'union majeur entre la fabrique hollywoodienne et le milieu littéraire. Le cinéaste avait ses amis écrivains (Hemingway) et ses coscénaristes préférés (Peter Viertel, Anthony Veiller). Toute sa filmographie est placée sous le signe des grandes ambitions littéraires (une collaboration orageuse avec Sartre sur le scénario de *Freud, passions secrètes*), des adaptations prestigieuses, exigeantes (Kipling, Tennessee Williams, Carson McCullers, Arthur Miller, Romain Gary, Flannery O'Connor) et impossibles (Stephen Crane, Herman Melville, James Joyce, Malcolm Lowry). À partir de 1954, il se libéra d'une forme hollywoodienne pour lui timide, qu'il défiait de ses projets féconds, et préféra des sujets marqués par le goût des romanciers de la modernité.
Devant l'hétérogénéité ou l'arlequinade des sujets, la critique pointa assez vite un fil directeur – un héroïsme en négatif, un goût de l'échec flamboyant, d'une démiurgie qui s'abîme avec lucidité, une fidélité aux récits de la quête finalement vaine, évidente dès *Le Faucon maltais* et l'or dispersé du *Trésor de la Sierra Madre*. Cette alliance entre vision matérialiste de l'existence et odyssée mythique décrit bien l'imaginaire de Huston, avec ses voyages divers et ses animaux chargés de légende (la baleine blanche, l'éléphant des *Racines du ciel*, le cheval fou et l'oiseau-phénix de *Reflets dans un œil d'or*, le reptile érotique de *La Nuit de l'iguane*). En 1958, le chasseur d'éléphants Huston accepte de diriger *Les Racines du ciel* pour la Fox – une aventure sur la préservation des éléphants. Outre l'adrénaline du tournage en Afrique, Huston y est fasciné par le mythe logé dans le sujet – tuer un éléphant n'y est pas un crime, mais un péché – un acte avec une aura d'imaginaire. En 1967, l'extravagant Huston se retrouve à jouer Noé et à diriger *La Bible* pour Dino De Laurentiis, et le cinéaste fort peu orthodoxe y trouve pourtant un intérêt. À ses yeux, l'Ancien Testament regorge de mystères, s'impose comme anthologie mythologique, et ses récits réclament d'inventer des solutions visuelles pour raconter la Création du monde, le Déluge, la tour de Babel ou les généalogies prodigieuses. Il envisage le Déluge comme un conte merveilleux et enfantin (et pense même à Chaplin ou Alec Guinness comme interprètes). Et l'adaptation de *Freud* en 1962 repose au fond sur la même soif d'enquête mythographique – aussi bien dans les séquences oniriques que dans la tapisserie des compositions saturées de formes symboliques. John Huston n'était pas un classique. Il fut en un sens le premier grand cinéaste « international » au fil des contrées de tournage (Irlande, Angleterre, France, Mexique, Congo, Tchad, Japon) et des sujets exotiques. Les œuvres des années 1960-1970 montrent un artiste conscient de l'évolution du réalisme physique, avec un existentialisme cynique et un goût des extérieurs qui lui font passer sans problème le cap de l'ère moderne. Le tempérament de ce cinéaste non lyrique, non romantique, se rapproche du versant prosaïque et dur, ni métaphysique, ni spirituel, du classicisme – proche du pragmatisme d'un Hawks, mais moins populaire, moins enclin à la comédie et davantage à la farce grotesque et au film noir. Chez lui, l'humanité est vue à la lumière de l'existence organique et les stars apparaissent sous le jour de la fatigue, de l'âge, de la décadence ou du malaise physique (Robinson dans *Key Largo*, Bogart dans *African Queen*, Gable et Marilyn dans *Les Désaxés*, Burton dans *La Nuit de l'iguane*, Finney dans *Au-dessous du volcan*, Brando dans *Reflets dans un œil d'or*).
Maniériste, contrebandier de l'absurde ou dilettante de carnaval ? Plusieurs fois ce cinéaste provocateur joua à l'absurde avec le classicisme. En 1953, il se lance dans le tournage de *Plus fort que le diable* avec un scénario en perpétuelle réinvention. Cette comédie noire apparaît comme un pastiche explicite du *Faucon maltais*, comme une intrigue qui se moque de l'action et de l'exotisme. Amateur de cette curieuse forme de gag, Huston en saupoudra son *Juge et hors-la-loi* grâce à l'hyperbole des légendes (la mort du tueur albinos Bad Bob vue par un trou géant à travers le thorax) qui dévoyait le scénario sérieux de John Milius. Avec Veiller, Huston imagina aussi le fameux *Dernier de la liste*, jeu sur l'enquête à l'anglaise, scandé de noms improbables et de stars déguisées à reconnaître par simple facétie visuelle et mise en abyme moderniste.
À la Warner, Huston fit ses gammes de cinéaste. Marqué par le film noir et son âpreté plastique, il en conserva des éléments le long des décennies suivantes – huis-clos des visages, claustrophobie graphique, contre-plongées... Une fois indépendant, Huston devient maître d'œuvre des tournages exotiques et techniquement audacieux. Parfois l'aventure technique, l'achèvement même du sujet donne à l'image son intérêt (les caméras Technicolor en plein Congo pour *African Queen*). Avec l'opérateur anglais Oswald Morris, il se lance dans des recherches esthétisantes. Huston et Morris façonnent pour *Moby Dick* une image sépia, ocre, bleue et grise, un noir et blanc coloré à la fois gravure et parchemin, eau-forte abîmée et texture onirique pour les marines. L'inspiration picturale crée sur *Moulin Rouge* une sensation de peinture en création – les mondes de Lautrec y apparaissent avec des nuages de couleurs que l'on sent tout juste posés sur l'écran, à peine figés. Avec un impact sensoriel, le tirage jaune de *Reflets dans un œil d'or* sert d'atmosphère et d'humeur plastique qui enveloppe cette histoire de perversions dans un vieux fort du Sud, comme les contrastes surexposés des flashbacks dans *Freud* livrent une sensation d'exploration éblouissante et malaisée. Ces plastiques formalistes restent sans doute le pan le plus aisément sidérant de l'œuvre post-1950, le moment où l'inspiration visuelle retrouve quelque chose de l'intimidante impossibilité des œuvres adaptées et des sujets démesurés.
Désordre créatif derrière la passion. Certains grands projets enflamment l'imagination du cinéaste, mais donnent des œuvres finalement décevantes – ces *Racines du ciel* qu'il échoue à traiter, de son propre aveu. D'autres lui paraissent plus banals, et il s'invente alors une méthode ou un style pour les tourner – l'opératique western *Le Vent de la plaine*, finalement puissant. D'autres encore voient converger l'esprit du sujet et le tempérament du cinéaste (*Les Désaxés*, *La Nuit de l'iguane*). Huston est un écrivain de cinéma d'abord déçu par le traitement hollywoodiens des romans, et dépourvu de l'esprit romantique qui lui permettrait d'en saisir l'intérêt. Cette fierté moderne lui fait évoquer le scénario comme une scansion purement poétique et le film comme un monologue de conscience. Avec ces espoirs, Huston chercha moins à adapter qu'à trouver l'équivalent des œuvres qu'il transposait, à trouver une viabilité filmique. Dira-t-on qu'il n'y traitait que ce qui l'intéressait ? Tel est sans doute l'enjeu – et la limite – de cette filmographie hasardeuse et démiurge. Car le paradoxe de nombre d'œuvres réside à la fois dans le succès d'une forme trouvée, mais l'échec d'une forme finalement moins ambitieuse que l'original (*Moby Dick*, *Au-dessous du volcan*). L'inspiration du cinéaste-écrivain lui fait sacrifier maint pan mystique, baroque ou tortueux des sujets, au risque d'un aplatissement prosaïque. L'arlequinade résonne alors comme aveu de timidité et d'une impuissance bien vécue. Avec Huston, l'on touche régulièrement à quelque chose qui serait la nature à la fois vorace, admirable, et profondément limitée du cinéma.
Pierre Berthomieu
|
Java
|
UTF-8
| 923 | 2.375 | 2 |
[] |
no_license
|
package com.sucl.sbjms.core.view;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* @author sucl
* @date 2019/4/9
*/
@Data
public class MenuNode implements TreeNode{
private String id;
private String text;
private String cls;
private String link;
private boolean leaf;
private List<TreeNode> children;
public void add(MenuNode menuNode) {
if(children==null){
this.children = new ArrayList<>();
}
this.children.add(menuNode);
}
public String getLink() {
return link==null?"javascript:;":link;
}
@Override
public String getName() {
return text;
}
@Override
public boolean isSpread() {
return !leaf;
}
@Override
public String getHref() {
return null;
}
@Override
public List<TreeNode> getChildren() {
return children;
}
}
|
Shell
|
UTF-8
| 1,112 | 3.6875 | 4 |
[] |
no_license
|
#!/bin/bash
#post json to solace
#Ramesh Natarajan, Solace PSG
me=start-replay
# read env
[ -f env.sh ] || { echo Missing env file env.sh ; exit 1; }
echo "Reading env.sh"
. env.sh
if [ $# -lt 2 ]; then
echo "ERROR $me: missing arguments"
echo "Usage: $me router-config-file queue1 queue2 ..."
exit 1
fi
# read router config
router_cfg="$1"
shift
[ -f $router_cfg ] || { echo Missing router-cfg $router_cfg; exit 1; }
echo "Reading $router_cfg"
. $router_cfg
tfile=templates/$me.json
stfile=templates/$me-sub.json
[ -f $tfile ] || { echo Missing template file $tfile; exit 1; }
function put_json() {
_jsonfile=$1
_url=$2
curl -X PUT -d @${_jsonfile} -u ${cli_user}:${cli_pass} -H "content-type:application/json" $_url
}
echo "Creating $nqueues $qname_prefix queues"
url=$mgmt_ip/SEMP/v2/action/msgVpns/${vpn}/queues
ts=$(date "+%s")
outfile=out/run-$me-$ts.out
> $outfile || { echo unable to create output file $outfile; exit 1; }
for qname;
do
surl=$url/$qname/startReplay
echo "Putting $tfile to $surl"
put_json $tfile $surl >> $outfile 2>&1
done
echo Check output file $outfile
|
Python
|
UTF-8
| 2,314 | 3.015625 | 3 |
[] |
no_license
|
#!/usr/bin/python
# From: http://www.tedunangst.com/flak/post/sct-set-color-temperature
import argparse
import os
import subprocess
import sys
def convert_input(input):
""" Convert command line argument to sct input """
try:
return int(input)
except ValueError as e:
input = str(input).lower()
return {'s':k_to_p(3000),
'm':k_to_p(3750),
'd':k_to_p(5500),
'n':k_to_p(6500),
'h':k_to_p(7500)
}.get(input[0],100)
# Redshift takes a value in k with 3000 - 4000 being low and 6500 being nutural.
# This function maps 0 - 100 -> 2000 - 6500
def p_to_k(precent):
if precent < 0:
precent = 0
elif precent > 130:
precent = 130
return int(2000 + precent*45)
def k_to_p(k):
if k < 2000:
k = 2000
elif k > 7850:
k = 7850
return (k - 2000) / 45.0
parser = argparse.ArgumentParser(description = "Use Redshift to change temperature")
parser.add_argument('-r','--raw',action='store_true',default=False,help='use raw temperature value')
parser.add_argument('arg',default='normal',
help = "int in range (10 - 100) (s)mok , (m)ars , (d)ay, (n)ormal, (h)igh (g)ray"
)
args = parser.parse_args()
if args.arg.lower()[0] == 'g':
# Get current value of grayscale to toggle
print 'Toggle Grayscale'
kwinrc_file = '/home/tperrier/.config/kwinrc'
cmd_args = '--file {} --group Plugins --key kwin4_effect_grayscaleEnabled'.format(kwinrc_file)
cur_state = subprocess.check_output(['kreadconfig {}'.format(cmd_args)],shell=True).strip()
gray_scale_cmd = 'kwriteconfig {} "{{}}"'.format(cmd_args)
if cur_state == 'true': # turn gray scale off
os.system(gray_scale_cmd.format('false'))
os.system('qdbus org.kde.KWin /KWin reconfigure')
os.system('qdbus org.kde.KWin /Compositor suspend')
os.system('qdbus org.kde.KWin /Compositor resume')
else:
os.system(gray_scale_cmd.format('true'))
os.system('qdbus org.kde.KWin /KWin reconfigure')
sys.exit(0)
if args.raw is True:
args.value = int(args.arg)
else:
args.value = p_to_k( convert_input(args.arg) )
print "Input: {0.arg} Setting Temperature: {0.value}".format(args)
os.system("redshift -O {}".format(args.value))
|
PHP
|
UTF-8
| 1,544 | 2.5625 | 3 |
[] |
no_license
|
<?php
header("Content-type: text/html; charset=utf-8");
include "config.php";
include "mysql.lib.php";
class Token
{
public $wechat_error;
public $wechat_code;
public $wechat_url;
public $token;
public $openid;
public $access_info;
public function __construct($error_code = false)
{
$this->wechat_error = $error_code;
$this->GetWechatAccessToken();
$this->SetOpenID();
}
/****
* 获取 wechat code
*/
public function GetWechatCode()
{
$url = WECHAT_SERVER . '?appid=' . WECHAT_APPID . '&redirect_uri=' . WECHAT_REDIRECT_URL . '&response_type=code&scope=' . WECHAT_SCOPE_BASE . '&state=1#wechat_redirect';
$this->wechat_code = file_get_contents($url);
$this->wechat_url = $url;
return $this->wechat_code;
}
public function GetWechatAccessToken()
{
$this->GetWechatCode();
$url = WECHAT_ACCESSTOKEN_URL . '?appid=' . WECHAT_APPID . '&secret=' . WECHAT_KEY . '&code=' . $this->wechat_code . '&grant_type=authorization_code';
$this->access_info = file_get_contents($url);
return $this->access_info;
}
public function SetOpenID($data)
{
$this->openid = json_decode($data, true)['openid'];
}
}
/*
$token = new Token();
$cc = $token->GetWechatCode();
error_log("code#######" . $cc, '3', 'D:\xampp\htdocs\wechat\log\error.txt');
error_log("wechat_url#######" . $token->wechat_url, '3', 'D:\xampp\htdocs\wechat\log\error.txt');
var_dump($token->wechat_code);*/
|
PHP
|
UTF-8
| 1,204 | 2.5625 | 3 |
[] |
no_license
|
<?php
include('db.php');
function get_posts(){
global $connection;
$query = "SELECT * FROM posts";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
$post = [
];
$post['id'] = $row['post_id'];
$post['title'] = $row['post_title'];
$post['body'] = $row['post_body'];
$post['author'] = $row['post_author'];
$post['date'] = $row['post_date'];
$json = json_encode($post);
var_dump($json);
}
}
get_posts();
function get_by_id(){
global $connection;
$post_id = 2;
$query = "SELECT * FROM posts WHERE post_id = $post_id";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
$post = [
];
$post['id'] = $row['post_id'];
$post['title'] = $row['post_title'];
$post['body'] = $row['post_body'];
$post['author'] = $row['post_author'];
$post['date'] = $row['post_date'];
$json = json_encode($post);
var_dump($json);
}
}
?>
|
C++
|
UTF-8
| 1,010 | 2.65625 | 3 |
[] |
no_license
|
//
// main.cpp
// practice
//
// Created by Mahmud on 04/30/18.
// Copyright © 2018 Mahmud. All rights reserved.
//
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <ctime>
using namespace std;
const int MAX = 100;
int N;
int a[MAX], pos[MAX];
int main() {
int N = 50;
for (int i = 1; i <= N; i ++) cin >> a[i];
int p[8] = {0, 1, 2, 3, 6, 7, 8, 9};
do {
for (int i = 0; i < 8; i ++) {
pos[p[i]] = i;
}
int good = 1;
for (int i = 1; i <= N; i ++) {
int x = a[i] / 100;
int y = a[i] / 10 % 10;
int z = a[i] % 10;
if (pos[x] > pos[y]) good = 0;
if (pos[x] > pos[z]) good = 0;
if (pos[y] > pos[z]) good = 0;
}
if (good) {
for (int i = 0; i < 8; i ++) cout << p[i];
cout << endl;
}
} while (next_permutation(p, p + 8));
return 0;
}
|
Python
|
UTF-8
| 936 | 2.546875 | 3 |
[] |
no_license
|
import scrapy
class FairytalesExtractor(scrapy.Spider):
name = 'fairytales'
def start_requests(self):
url = 'https://deti-online.com/skazki/'
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
for x in response.css('tr'):
try:
if int(x.css('td:nth-child(3)::attr(data-filter)').get()) == 0:
link = x.css('a.dt-a::attr(href)').get()
yield scrapy.Request(link, callback=self.parse_link)
except TypeError:
continue
def parse_link(self, link):
name = ' '.join(str((link.css('h1::text').get())).split()[1:])
text = ' '.join(link.css('div.text p::text').getall())
with open('fairytales.txt', 'a', encoding='utf-8') as outp:
outp.write('<title>{}</title>'.format(name) + '\n' + text.strip() + '\n\n')
|
Markdown
|
UTF-8
| 1,369 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
# REDCap Capture Save Time
## Description
This External Module captures the date/time when a Data Entry Form and/or Survey is saved/submitted. The captured time will be stored in a selected text field, while the format of the date/time will match with the datetime validation of the text field.
<br><br>
There are plenty of options to the user to customize their conditions for capturing the time. Options include:
* Capture time for Data Entry - Save OR Mark Survey as Complete
* Capture time for Survey - Completion
* Capture time for Survey - Save & Return Later, Next Page, and/or Previous Page for **all survey pages**
* Capture time for Survey - Save & Return Later, Next Page, and/or Previous Page only for **the page containing the field**
The user can also choose how often to capture the time, as well as specify email address/addresses to receive error messages if any errors occur.
## Notes
* It is recommended to add make the field READONLY and/or HIDDEN to prevent respondents from interfering with the field.
* If you wish to capture the time **when a particular survey page has been saved**, tick the options with labels '(Only for the page that the field is on)'. Don't forget to put the field on the page that you would like to capture the time for.
* Don't forget to add the time validation for the text field you wish to capture the time.
|
Java
|
UTF-8
| 289 | 2.71875 | 3 |
[] |
no_license
|
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
Calculator calc = new Calculator();
calc.add(4);
calc.subtract(1);
calc.multiply(6);
calc.divide(2);
calc.square_root();
}
}
|
C#
|
UTF-8
| 2,494 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
using System.Windows;
using Navigation.Constants;
using Navigation.Models;
using Navigation.Utils;
using System.Linq;
namespace Navigation.ViewModels
{
public class FoodSelectionViewModel : ViewModelBase, INavigationAware
{
#region Fields
private readonly INavigationManager _navigationManager;
#endregion
#region Ctor
public FoodSelectionViewModel(INavigationManager navigationManager)
{
_navigationManager = navigationManager;
}
#endregion
#region Properties
#region Foods
private Food[] _foods;
public Food[] Foods
{
get { return _foods; }
private set { SetProperty(ref _foods, value); }
}
#endregion
#region SelectedFood
private Food _selectedFood;
public Food SelectedFood
{
get { return _selectedFood; }
set
{
SetProperty(ref _selectedFood, value);
CookFoodCommand.RaiseCanExecuteChanged();
}
}
#endregion
#region CookFoodCommand
private DelegateCommand _cookFoodCommand;
public DelegateCommand CookFoodCommand
{
get { return _cookFoodCommand ?? (_cookFoodCommand = new DelegateCommand(CookFood, CanCookFood)); }
}
private void CookFood(object arg)
{
MessageBox.Show(string.Format("Ваш заказ '{0}' отправлен к шеф-повару", SelectedFood.Name));
_navigationManager.Navigate(NavigationKeys.FoodCooking, SelectedFood);
}
private bool CanCookFood(object obj)
{
return SelectedFood != null;
}
#endregion
#endregion
#region Implementation of INavigationAware
public void OnNavigatingTo(object arg)
{
Foods = new Food[]
{
new Food("Борщ", 70),
new Food("Щи", 60),
new Food("Картофель", 30),
new Food("Рис", 25),
new Food("Макароны", 20),
new Food("Оливье", 45),
new Food("Чай", 15),
new Food("Компот", 20),
};
SelectedFood = Foods.FirstOrDefault();
}
public void OnNavigatingFrom()
{
}
#endregion
}
}
|
C++
|
UTF-8
| 394 | 2.96875 | 3 |
[] |
no_license
|
#include "Person.hpp"
#include "ChatRoom.hpp"
void ChatRoom::broadcast(const std::string &origin, const std::string & message)
{
for(auto p: people)
{
if(p->name ! = origin)
p->receive( origin, message);
}
}
void ChatRoom ::join ( Person * p)
{
std::string join_msg = p->name + " joins the chat " ;
broadcast( "room ", join_msg);
p->room = this;
people.push_back(p);
}
|
Markdown
|
UTF-8
| 5,931 | 2.6875 | 3 |
[
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# Exploring Polybius's syntax with dependency trees
[Neven Jovanović](orcid.org/0000-0002-9119-399X), Department of Classical Philology, Faculty of Humanities and Social Sciences,
University of Zagreb

## Introduction
In Croatia there is relatively little research on Greek and Latin syntax. Views of classicists are traditionally shaped by school grammars such as, for the Greek, [Musić (1887)](http://www.bibsonomy.org/bibtex/2b2ead1c31826bd64b2ce72e2c81ebda1/filologanoga) and [Dukat (1983)](http://www.bibsonomy.org/bibtex/29b4c41cc65c361e7dc185270f2530ca4/filologanoga). Intended as reference books for young Croatian learners, to be supplemented by teacher's intervention and students' understanding of their first language, these works have effectively suppressed different approaches (attempted in e. g. [Macun 1853](http://www.bibsonomy.org/bibtex/20a208a5a02003fd2c84a928713e3960c/filologanoga)). At the same time, both Musić and Dukat display unexpected blind spots, especially in syntax, where little attention has been given to the parts of the sentence (for example, adverbials are almost completely omitted).
On the other hand, contemporary global initiatives led by the [Perseus Project (Tufts University)](http://www.perseus.tufts.edu/hopper/) and the [Open Philology Project (University of Leipzig)](http://www.dh.uni-leipzig.de/wo/open-philology-project/) have brought all classicists a valuable resource for analyzing Greek and Latin syntax from a wholly different linguistic perspective, the one of computational analysis and dependency grammar. The [Ancient Greek and Latin Dependency Treebank (AGLDT)](https://perseusdl.github.io/treebank_data/) is an ongoing project of digital syntactical annotation of ancient texts according to a dependency grammar model following the [Prague Dependency Treebank](https://ufal.mff.cuni.cz/pdt2.0/) principles; in the AGLDT, each sentence “tree” consists of “nodes” connected hierarchically and marked by grammatical relation labels on the basis of their relationship with their governor nodes. Currently the AGLDT collection holds several thousand sentences annotated by over 200 people; it is published as Open Data, which means that anybody can not only use it, but also enhance it, or adapt it to any purpose.
To illustrate possibilities of the AGLDT, which at the moment happens to contain large parts of [Polybius's Histories](http://www.perseids.org/tools/arethusa/app/#/perseids?chunk=1&doc=27694), I will provide an overview of the structure of his sentences in the Book 1. Such an investigation fittingly complements previous interpretations of Polybius' language and linguistic choices, the topics for which, as has been stated recently ([Langslow 2012](http://www.bibsonomy.org/bibtex/283c6fd3b1984fa8969cb6079f8ce00d5/filologanoga)), “further research is needed”.
## How to use
This repository contains scripts needed to build a XML database of Polybius's Book 1 with treebank and morphology annotations, and to analyse the database.
For a live demonstration, follow the topmost links at [www.bibsonomy.org/user/filologanoga/polybius](https://www.bibsonomy.org/user/filologanoga/polybius).
For a visualization of the Polybius's treebank (using the Perseids Arethusa environment), see the [Polybius in Perseids](http://www.perseids.org/tools/arethusa/app/#/perseids?chunk=1&doc=27694).
### Prerequisites
Some working knowledge of command line, Git, XML, XQuery, and BaseX.
+ [Git](https://git-scm.com/), a free and open source distributed version control system
+ [BaseX](http://basex.org/), a (freely available) XML Database engine and XPath/XQuery 3.1 Processor
### Building the database
Install the software as necessary (Git and BaseX).
Using Git, clone this repository. From BaseX, run the [scripts/create-polybius-db.bxs](scripts/create-polybius-db.bxs). The script will pull the latest version of the Polybius treebank XML document from the [Ancient Greek and Latin Dependency Treebank (AGLDT)](https://perseusdl.github.io/treebank_data/) Github repository.
### Exploring the database
+ How many sentences and words are there in Polybius's Book 1? - [Report](http://croala.ffzg.unizg.hr/basex/polybcounts)
+ Which syntactical relations exist in the sentences of Polybius's Book 1? - [Report](http://croala.ffzg.unizg.hr/basex/polybrelations)
+ How many occurrences of each syntactic relation is there? - [Report](http://croala.ffzg.unizg.hr/basex/polybrelations) (the same as above)
+ What is the maximum and minimum number of dependent nodes contained by each syntactic relation? - [Report for the relation **ADV**](http://croala.ffzg.unizg.hr/basex/polyboccur/ADV)
+ Which morphological configurations are used for a certain syntactic relation, and in what frequency? - [Report for the relation **ADV** with two dependent nodes](http://croala.ffzg.unizg.hr/basex/polybmorph/ADV/2)
## Tests
The scripts for this analysis were coded using the [Test-Driven Development](https://en.wikipedia.org/wiki/Test-driven_development) process and the [BaseX Unit test module](http://docs.basex.org/wiki/Unit_Module). Test for the scripts are in the [scripts/testing](scripts/testing) directory. You may want to run the tests to see whether everything works as intended.
## Transforming flat sentence structure into nested trees
Dependencies that we want to analyse are easier to access if the original XML treebank is transformed from a "flat" structure (one sentence with many word nodes as children) into a "tree" (each governor-node word contains all word-nodes dependent on it). This transformation is achieved with the [scripts/transform-flat-into-tree.xq](scripts/transform-flat-into-tree.xq) script.
# Released on Zenodo
[](https://zenodo.org/badge/latestdoi/74203045)
# License
[CC-BY](LICENSE.md)
|
Java
|
UTF-8
| 5,205 | 2.34375 | 2 |
[] |
no_license
|
package de.thwildau.guido;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import de.thwildau.guido.model.Message;
import de.thwildau.guido.model.User;
import de.thwildau.guido.util.Constants;
import de.thwildau.guido.util.DatabaseInteractor;
import de.thwildau.guido.util.GuidoError;
import de.thwildau.guido.util.PreferenceData;
import de.thwildau.guido.util.Response;
import de.thwildau.guido.util.ResponseHandler;
/**
* An Activity displaying the selected Messages details.
* @author GUIDO
* @version 2013-12-16
* @see Activity
*/
public class MessageDetail extends Activity implements Observer {
/**
* The Message which details are displayed
*/
Message displayedMessage;
/**
* Fragment to create a new message.
*/
MessageCreatorFragment createMessageDialog;
/**
* Called when the activity is first created. Sets the content view with layout xml
* and sets the Route which was put as extra to the intent.
* @param savedInstanceState If the activity is being re-initialized after previously
* being shut down then this Bundle contains the data it most recently supplied in
* onSaveInstanceState(Bundle). Note: Otherwise it is null.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_detail);
displayedMessage = (Message) getIntent().getSerializableExtra("message");
setupData();
}
/**
* Initialize the contents of the Activity's standard options menu.
* Shows a dummy settings button and a logout button which logs the user out.
* @param menu The options menu in which the menu items are placed.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.app_menu_messagedetail, menu);
return true;
}
/**
* Called when a menu item was selected. If the logout item was selected,
* the user will be logged out.
* @param item The selected menu item.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
DatabaseInteractor.logout(this, PreferenceData.getUserId(this));
break;
case R.id.action_sendMessagerw:
Log.i("CREATEMESSAGE", "create button clicked");
TextView messageFrom = (TextView) findViewById(R.id.message_from);
TextView messageSubject = (TextView) findViewById(R.id.message_subject);
createMessageDialog = new MessageCreatorFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("toEmail", messageFrom.getText().toString());
args.putString("subject", messageSubject.getText().toString());
args.putBoolean("response", true);
createMessageDialog.setArguments(args);
createMessageDialog.show(getFragmentManager(), "Create Message");
}
return super.onOptionsItemSelected(item);
}
/**
* Sets the Routes properties to the TextViews described in the layout xml.
*/
public void setupData() {
TextView messageSubject = (TextView) findViewById(R.id.message_subject);
TextView messageFrom = (TextView) findViewById(R.id.message_from);
TextView messageContent = (TextView) findViewById(R.id.message_content);
messageSubject.append(displayedMessage.getSubject());
messageFrom.append(displayedMessage.getFromEmail());
messageContent.append(displayedMessage.getMessage());
}
/**
* Called when an observable notifies this class. Evaluates the received response.
* @param observable The observed class.
* @param data The Object passed by notifyObservers(Object)
*/
@Override
public void update(Observable observable, Object data) {
if(DatabaseInteractor.getResponse()==null){
Toast.makeText(this, "Netzwerkprobleme...", Toast.LENGTH_LONG).show();
return;
}
Response resp = ResponseHandler.handleResponse(this, DatabaseInteractor.getResponse());
switch(resp.getId()) {
case Constants.RESP_GET_CONTACTS:
createMessageDialog.updateDropDown((List<User>)resp.getObject());
break;
case Constants.RESP_ERROR:
Builder alert = new AlertDialog.Builder(this);
GuidoError err = (GuidoError)resp.getObject();
alert.setTitle("Error #"+err.getErrorCode());
alert.setMessage(err.getMessage());
alert.setPositiveButton("Ok", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDiag = alert.create();
alertDiag.show();
break;
}
ResponseHandler.handleResponse(this, DatabaseInteractor.getResponse());
}
}
|
PHP
|
UTF-8
| 9,042 | 2.8125 | 3 |
[] |
no_license
|
<?php
/*
* Jscript.php
* intermediate file for every ajax call in application
* which return table grid, add data, inventory data and view inventory page
* very important file for application
*
*/
include_once "classes/manufacturer.php";
include_once "classes/model.php";
if (isset($_POST['action']) && $_POST['action'] != "") {
$action = $_POST['action'];
switch ($action) {
case "add_mfg":
//Add Manufacturer code
$mfg_name = $_POST['mfg_name'];
if (isset($mfg_name) && $mfg_name == "") {
echo "<span class='error' id='errorMsg'>Please Enter Manufacturer Name</span>";
} else {
$arr = array('mfg_name' => $mfg_name, 'created' => date("Y-m-d H:i:s"));
$m = new Manufacturer;
$lastId = $m->add($arr);
if (isset($lastId) && $lastId != 0) {
echo "<span class='success' id='successMsg'>Manufacturer Name Added Successfully</span>";
} else {
echo "<span class='error' id='errorMsg'>Duplicate Manufacturer can not be added.</span>";
}
}
break;
case "show_mfg_json": //Show Manufacturer page data grid by ajax
$m = new Manufacturer;
$arr = $m->getAllData();
$data = array();
if ($arr != 0) {
$j = 0;
foreach ($arr as $a) {
$data[$j]['mfg_id'] = $a['mfg_id'];
$data[$j]['mfg_name'] = $a['mfg_name'];
$data[$j]['created'] = $a['created'];
/* $data[$j]['action']="<button type='button' name='update-mfg[]' class='btn btn-info btn-xs update-mfg' id=".$a['mfg_id']." >Update</button>
<button type='button' name='delete-mfg' class='btn btn-success btn-xs delete-mfg' id=".$a['mfg_id']." >Delete</button>";
*/
$j++;
}
}
echo json_encode($data);
break;
case "add_car_model": //add new Car Model
//print_r($_POST);
//print_r($_FILES);
$arr['model_name'] = $_POST['model_name'];
$arr['mfg_id'] = $_POST['mfg_id'];
$arr['model_color'] = $_POST['model_color'];
$arr['mfg_year'] = $_POST['mfg_year'];
$arr['reg_no'] = $_POST['reg_no'];
$arr['note'] = $_POST['note'];
$arr['created'] = date("Y-m-d H:i:s");
$validextensions = array("jpeg", "jpg", "png");
if (isset($_FILES['pict1']) && $_FILES['pict1'] != "") {
//pictureUpload($_FILES['pict1']);
$arr['pict1'] = $_POST['image1'];
}
if (isset($_FILES['pict2']) && $_FILES['pict2'] != "") {
//pictureUpload($_FILES['pict2']);
$arr['pict2'] = $_POST['image2'];
}
$arr['created'] = date("Y-m-d H:i:s");
$m = new model;
$lastId = $m->add($arr);
if (isset($lastId) && $lastId != 0) {
echo "<span class='success' id='successMsg'>New Car Model Added Successfully</span>";
} else {
echo "<span class='error' id='errorMsg'>Can't add Duplicate Car Model, Duplicate Registration Id .</span>";
}
break;
case "uploadPic": // ajax call to upload pics of car
// print_r($_POST);
// print_r($_FILES);
$arr = $_FILES['file'];
$picarr = pictureUpload($arr);
echo json_encode($picarr);
break;
case "show_mfg_json":// get all the manufacturerdata in Json format
$m = new Manufacturer;
$arr = $m->getAllData();
$data = array();
if ($arr != 0) {
$j = 0;
foreach ($arr as $a) {
$data[$j]['mfg_id'] = $a['mfg_id'];
$data[$j]['mfg_name'] = $a['mfg_name'];
$data[$j]['created'] = $a['created'];
/* $data[$j]['action']="<button type='button' name='update-mfg[]' class='btn btn-info btn-xs update-mfg' id=".$a['mfg_id']." >Update</button>
<button type='button' name='delete-mfg' class='btn btn-success btn-xs delete-mfg' id=".$a['mfg_id']." >Delete</button>";
*/
$j++;
}
echo json_encode($data);
}
break;
case "show_modelcar_json": // all model car grid ajax population
$m = new Model;
$arr = $m->getAllData();
$data = array();
if ($arr != 0) {
$j = 0;
foreach ($arr as $a) {
$data [$j]['model_id'] = $a['model_id'];
$data[$j]['mfg_name'] = $a['mfg_name'];
$data[$j]['model_name'] = $a['model_name'];
$data[$j]['model_color'] = $a['model_color'];
$data[$j]['mfg_year'] = $a['mfg_year'];
$data[$j]['reg_no'] = $a['reg_no'];
$data[$j]['sold'] = $a['sold'];
/* $data[$j]['action']="<button type='button' name='update-mfg[]' class='btn btn-info btn-xs update-mfg' id=".$a['mfg_id']." >Update</button>
<button type='button' name='delete-mfg' class='btn btn-success btn-xs delete-mfg' id=".$a['mfg_id']." >Delete</button>";
*/
$j++;
}
echo json_encode($data);
}
break;
case "show_inventory_json": //Show inventory page json script ajax
$m = new model;
$row = $m->getInventory();
if ($row != 0) {
$i = 0;
foreach ($row as $r) {
$row[$i]['sr_no'] = $i + 1;
$a['mfg_id'] = $r['mfg_id'];
$a['model_id'] = $r['model_id'];
$a['model_name'] = $r['model_name'];
$a['model_count'] = $r['model_count'];
$str = json_encode($a);
$row[$i]['action'] = "<button type='button' name='view[]' data-url='viewcarmodels.php' class='btn btn-info btn-xs view-mfg' id=" . $str . " >View</button>";
$i++;
}
}
//print_r($row);
echo json_encode($row);
break;
case "car_sold": // Car soldstatus Update ajax jquery
//print_r($_POST);
$model_id = $_POST['model_id'];
$m = new model;
$stat = $m->SoldStatusUpdate($model_id);
if ($stat == 1) {
$mm = $m->getModelManufacturer($model_id);
echo "$mm car Sold";
} else
echo $stat;
break;
}
}
//Picture Upload function for both the pictures
function pictureUpload($arr) {
$validextensions = array("jpeg", "jpg", "png");
$filename = $arr['name'];
$temporary = explode(".", $filename);
$file_extension = end($temporary);
$picarr = array();
if ((($arr["type"] == "image/png") || ($arr["type"] == "image/jpg") || ($arr["type"] == "image/jpeg")) && ($arr["size"] < 500000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($arr["error"] > 0) {
$picarr['error'] = 1;
$picarrp['msg'] = "Return Code: " . $arr["error"];
$picarr['filename'] = '';
} else {
$msg = '';
$msg.= "<span class='success'>Your File Uploaded Succesfully...!!</span>";
/* $msg.= "<br/><b>File Name:</b> " . $arr["name"] . "<br>";
$msg.= "<b>Type:</b> " . $arr["type"] . "<br>";
$msg.= "<b>Size:</b> " . ($arr["size"] / 1024) . " kB<br>";
$msg.= "<b>Temp file:</b> " . $arr["tmp_name"] . "<br>";
*/
$filename = "upload/" . $filename;
if (file_exists("upload/" . $arr["name"])) {
// $msg.= $arr["name"] . " <b>already exists.</b> ";
} else {
move_uploaded_file($arr["tmp_name"], "./upload/" . $arr["name"]);
$imgFullpath = "http://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER["REQUEST_URI"] . '?') . '/' . "upload/" . $arr["name"];
// $msg.= "<b>Stored in:</b><a href = '$imgFullpath' target='_blank'> " .$imgFullpath.'<a>';
$filename = "upload/" . $filename;
//return $filename;
}
$picarr['error'] = 0;
$picarr['msg'] = $msg;
$picarr['filename'] = $filename;
}
} else {
$picarr['error'] = 0;
$picarr['msg'] = "<span class='error'>***Invalid file Size or Type***<span>";
$picarr['filename'] = 'assets/images/noimage.png';
}
return $picarr;
}
?>
|
Java
|
UTF-8
| 1,209 | 2.484375 | 2 |
[] |
no_license
|
package com.school.entity;
/**
* @program: design
* @description: 时光胶囊评论
* @author: Antony
* @create: 2019-04-18 09:44
**/
public class TimecapsuleComm {
//id
private long id;
//时光胶囊的id
private long timecapsuleId;
//用户的id
private long userId;
//评论内容
private String content;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getTimecapsuleId() {
return timecapsuleId;
}
public void setTimecapsuleId(long timecapsuleId) {
this.timecapsuleId = timecapsuleId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "TimecapsuleComm{" +
"id=" + id +
", timecapsuleId=" + timecapsuleId +
", userId=" + userId +
", content='" + content + '\'' +
'}';
}
}
|
Java
|
UTF-8
| 1,862 | 2.65625 | 3 |
[] |
no_license
|
package com.techbee.userprofileapi.classes;
public class UserProfile {
private int userProfileId;
private String firstName;
private String lastName;
private String email;
private String password;
public UserProfile() {
}
/**
* @return the userProfileId
*/
public int getUserProfileId() {
return userProfileId;
}
/**
* @param userProfileId the userProfileId to set
*/
public void setUserProfileId(int userProfileId) {
this.userProfileId = userProfileId;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public boolean setFirstName(String firstName) {
if (!firstName.isBlank()) {
this.firstName = firstName;
return true;
} else {
System.out.println("First Name can't be blank");
return false;
}
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public boolean setLastName(String lastName) {
if (!lastName.isBlank()) {
this.lastName = lastName;
return true;
} else {
System.out.println("Last Name can't be blank");
return false;
}
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public boolean setEmail(String email) {
if (!email.isBlank()) {
this.email = email;
return true;
} else {
System.out.println("Email can't be blank");
return false;
}
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public boolean setPassword(String password) {
if (!password.isBlank()) {
this.password = password;
return true;
} else {
System.out.println("Password can't be blank");
return false;
}
}
}
|
Java
|
UTF-8
| 1,585 | 2.1875 | 2 |
[] |
no_license
|
package com.kuycoding.covid19.viewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.kuycoding.covid19.api.ApiEndPoint;
import com.kuycoding.covid19.api.ApiService;
import com.kuycoding.covid19.model.CountryModel;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class CountryViewModel extends ViewModel {
private MutableLiveData<List<CountryModel>> mutableLiveData = new MutableLiveData<>();
public void setCountryData() {
Retrofit retrofit = ApiService.getRetrofitServiceKawalCovid();
ApiEndPoint apiEndPoint = retrofit.create(ApiEndPoint.class);
Call<List<CountryModel>> call = apiEndPoint.getKawalIndo();
call.enqueue(new Callback<List<CountryModel>>() {
@Override
public void onResponse(Call<List<CountryModel>> call, Response<List<CountryModel>> response) {
if (response.isSuccessful()) {
List<CountryModel> countryModelList = null;
if (response.body() != null) {
countryModelList = response.body();
}
mutableLiveData.postValue(countryModelList);
}
}
@Override
public void onFailure(Call<List<CountryModel>> call, Throwable t) {
}
});
}
public MutableLiveData<List<CountryModel>> getCountryData() {
return mutableLiveData;
}
}
|
Markdown
|
UTF-8
| 3,274 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
---
title: Аврам становится Авраамом
date: 20/04/2021
---
Не только имена Бога имеют духовное и богословское значение, но и имена людей. Для нас сегодня не так важно, какое имя дать девочке: Мария или Сусанна. Однако для древних семитов имя было исполнено духовного значения. Все семитские имена что-то означают и обычно состоят из фразы или короткого предложения, в которое входят пожелания или выражения благодарности со стороны родителя. Например: _Даниил_ (евр. _Дани-Эль_) — «Судья — мой Бог», _Иоиль_ (евр. _Йоэль_)— «Яхве—Бог» и _Нафан_ (евр. _Натан_) — «Дар (Божий)».
Из-за значимости, придаваемой именам, их меняли, чтобы отразить важные изменения, произошедшие в жизни.
`Прочитайте следующие тексты. Какие обстоятельства в них описаны и почему именно в этих обстоятельствах имена были изменены?`
`1. Быт. 32:28`
`2. Быт. 41:45`
`3. Дан. 1:7`
Для нас сегодня не так уж и сложно понять связь имени с самим человеком. Если кого-то постоянно называть глупым или некрасивым, то рано или поздно это «имя» повлияет на то, как человек себя воспринимает. И наоборот, называя человека определенным именем или меняя его, можно изменить отношение человека к себе и повлиять на его поведение.
Учитывая это, не так сложно понять, почему Бог пожелал изменить имя Аврам на Авраам. Имя Аврам означает «Отец превознесен». Бог изменил его на Авраам, что означает «Отец множества». Когда мы читаем обетование завета, в котором Бог говорит: «Тьмы тем потомков Я дам тебе: произойдут от тебя народы, и царями будут потомки твои» (Быт. 17:6; ИПБ), эта смена имени имеет бо́льший смысл. Возможно, так Бог хотел помочь Аврааму поверить обетованию завета, данному 99-летнему мужчине, женатому на пожилой женщине, которая оставалась бесплодной. Одним словом, Бог сделал это, чтобы помочь Аврааму укрепить веру в обетования, данные ему.
|
C#
|
UTF-8
| 1,194 | 2.796875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lista_de_Estrutura_Condicional___Forms
{
public partial class Exercicio11 : Form
{
public Exercicio11()
{
InitializeComponent();
}
private void txt_Nota4_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
ResultadoMedia();
}
}
private void ResultadoMedia()
{
double media = Convert.ToDouble(txt_Nota1.Text) + Convert.ToDouble(txt_Nota2.Text) + Convert.ToDouble(txt_Nota3.Text) + Convert.ToDouble(txt_Nota4.Text) / 4;
if (media < 5.99)
{
lbl_Resultado.Text = "Reprovado";
}
else if ((media <= 6.00)||(media < 7.99))
{
lbl_Resultado.Text = "Recuperação";
}
else if (media > 7.99)
{
lbl_Resultado.Text = "Aprovado";
}
}
}
}
|
Python
|
ISO-8859-1
| 835 | 2.53125 | 3 |
[] |
no_license
|
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - MoinMoin.Page Tests
@copyright: 2003-2004 by Jrgen Hermann <[email protected]>
@license: GNU GPL, see COPYING for details.
"""
import unittest
from MoinMoin._tests import request
from MoinMoin import Page
class existsTestCase(unittest.TestCase):
"""Page: testing wiki page"""
def testExists(self):
""" Page: page.exists() finds existing pages only """
tests = (
# Page name, expected
('FrontPage', 1),
('OnlyAnIdiotWouldCreateSuchaPage', 0),
)
for name, expected in tests:
pg = Page.Page(request, name)
self.assertEqual(pg.exists(), expected,
'%s should%s exist' % (name, (' not', '')[expected]))
|
C++
|
UTF-8
| 500 | 2.71875 | 3 |
[] |
no_license
|
/***from dust i have come, dust i will be***/
class Solution {
public:
vector<int> dp;
void solve(int curr, int cnt, int n)
{
if(curr > n) return;
if(dp[curr] != -1) return;
dp[curr] = cnt;
solve(curr << 1 | 1, cnt + 1, n);
solve(curr << 1, cnt, n);
}
vector<int> countBits(int num) {
dp.resize(num + 1);
fill(dp.begin(), dp.end(), -1);
solve(0, 0, num);
return dp;
}
};
|
C#
|
UTF-8
| 1,172 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerScore : MonoBehaviour {
// instantiate the class so that it can be reffered to from other scripts
public static PlayerScore instance;
// when the script instance is awaken, store the instance class (used for references in scripts)
void Awake ()
{
instance = this;
}
// the score at the beginning of the game
public int score;
// the score text on the HUD
private string scoreText = "Score: ";
// Use this for initialization
void Start ()
{
// initially set the score to 0
score = 0;
// the score text component initialized to 0
GetComponent<Text>().text = scoreText + score.ToString();
}
// Update is called once per frame
void Update ()
{
// continuously update the players score
GetComponent<Text>().text = scoreText + score.ToString();
}
// add to the score of the player
public void addScore (int score)
{
this.score += score;
}
// get the score of the current player
public int getScore ()
{
return score;
}
}
|
JavaScript
|
UTF-8
| 577 | 3.171875 | 3 |
[] |
no_license
|
let tony={
name: "tonny",
lastname: 'stark',
friends: ["hulk","banner"],
age: 33,
isAvenger: true,
abc:undefined,
address:{
state: "new york" ,
city: "he",
}
,sayhi:function fn(){
console.log("hey everyone");
return " its iron man here";
}
}
//console.log(tony.sayhi());
//console.log(tony["sayhi"]())
let karr = Object.keys(tony);
// console.log(karr);
// for(let key in tony){
// console.log(tony[key]);
// }
for(i=0;i<karr.length;i++){
let arr=karr[i];
console.log(tony[karr[i]])
}
|
Markdown
|
UTF-8
| 1,028 | 3.078125 | 3 |
[] |
no_license
|
The username must be between 5 and 49 charcters.
There is a function func(char*,char*,...) that gets as arguments a pointer to a char array, the string "%lX" and EAX.
The password and the array of characters are the compared using lstrcmpA.
So we need to see what that function does and how is EAX calculated.
ecx=eax=ebx=0;
ok=1;
while(ok)
{
eax=(unsigned int)username[ecx];
ecx++;
eax=eax^ecx;
ebx=ebx+eax;
ok=lengthusername-ecx;
}
this is the eax that will be given to the function as one of the arguments.
The function had a huge jumptable but I observed that it checkd for '%' characters and treated the "%%" cases.
I assumed it is a implementation of the wsprintfA function.
I tested this but the passwords were only working when they had no letters(A,B,C,D,E,F).
I thought I was wrong and have to really look at that jumptable.
Fortunately it was just that I put a lower case 'x'("%lx") insted of upper case in the keygen.
|
Markdown
|
UTF-8
| 4,459 | 3.28125 | 3 |
[] |
no_license
|
## 说明
- sqlite模块函数主要是用于操作sqlite数据库
- sqlite模块的对象前缀是sqlite,例如 sqlite.close()这样调用
- sqlite 教程:https://www.runoob.com/sqlite/sqlite-tutorial.html
- **频繁读写有可能造成sqlite的锁住,请再读写数据的时候进行加上sleep进行暂停50ms**
## sqlite.connectOrCreateDb 连接数据库
* 创建或者链接一个数据库
* @param dbName 数据库路径名称
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var create = sqlite.connectOrCreateDb("/sdcard/test.db");
> logd("create db result:"+create);
> }
> main();
> ```
## sqlite.createTable 创建表
* 创建数据表
* @param tableName 表名称
* @param columns 列名称,例如 ["name","pwd"]
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var tableName="tbl_user";
> var columns=["name","pwd"];
> var createTable = sqlite.createTable(tableName,columns);
> logd("createTable result:"+createTable);
> }
> main();
> ```
## sqlite.insert 插入数据
* 插入数据
* @param tableName 表名
* @param map 数据的map表
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var tableName="tbl_user";
> var map={
> "name":"我是名称",
> "pwd":"我是密码"
> };
> var insert = sqlite.insert(tableName,map);
> logd("insert result:"+insert);
> }
> main();
> ```
## sqlite.update 更新数据
* 更新数据
* @param tablename 表名称
* @param map 数据的map表
* @param where 条件语句
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var tableName="tbl_user";
> var map={
> "name":"我是名称22"
> };
> var where="id>3";
> var update = sqlite.update(tableName,map,where);
> logd("update result:"+update);
> }
> main();
> ```
## sqlite.query 查询数据
* 查询数据
* @param sql sql语句
* @return JSON | 数据集合对象
> ```javascript
>
> function main(){
> var tableName="tbl_user";
> var sql="select * from "+tableName;
> var data = sqlite.query(sql);
> logd("data result:"+JSON.stringify(data));
> }
> main();
> ```
## sqlite.delete 删除数据
* 删除数据
* @param sql sql语句
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var tableName="tbl_user";
> var sql="delete from "+tableName+" where id>3;";
> var result = sqlite.delete(sql);
> logd("delete result:"+ result);
> }
> main();
> ```
## sqlite.execSql 执行sql
* 查询数据
* @param sql sql语句
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var tableName="tbl_user";
> var sql="delete from "+tableName+" where id>3;";
> var result = sqlite.execSql(sql);
> logd("execSql result:"+ result);
> }
> main();
> ```
## sqlite.dropDatabase 删除数据库
* 删除数据库
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var result = sqlite.dropDatabase();
> logd("dropDatabase result:"+ result);
> }
> main();
> ```
## sqlite.dropTable 删除表
* 删除表
@param table 表名
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var tableName="tbl_user";
> var result = sqlite.dropTable(tableName);
> logd("dropTable result:"+ result);
> }
> main();
> ```
## sqlite.close 关闭数据库链接,释放资源
* 关闭数据库链接,释放资源
* @return boolean true 代表请求权限成功,false代表失败
> ```javascript
>
> function main(){
> var result = sqlite.close();
> logd("close result:"+ result);
> }
> main();
> ```
## sqlite.getErrorMsg 获取错误信息
* 获取上一次执行sql的错误信息
* @return {string} null代表无错误信息
> ```javascript
>
> function main(){
> var tableName="tbl_user";
> var result = sqlite.dropTable(tableName);
> logd("dropTable result:"+ result);
> var result = sqlite.getErrorMsg();
> logd("getErrorMsg result:"+ result);
> }
> main();
> ```
|
C#
|
UTF-8
| 13,194 | 2.59375 | 3 |
[] |
no_license
|
using System;
using System.IO;
using SevenEngine;
using SevenEngine.Imaging;
using Seven.Structures;
using SevenEngine.Shaders;
using Game.States;
using OpenTK.Graphics.OpenGL;
namespace Game
{
// This is an example of how to use my engine.
// Read this file and the "GameState.cs" file within the "State" folder.
// Hope you enjoy using my engine :)
public class Game : SevenEngineWindow
{
public Game(int width, int height) : base(width, height) { }
public override void InitializeDisplay()
{
// SET INITIAL DISPLAY SETTINGS HERE.
// Use the static class "GraphicsSettingsManager"
// EXAMPLES:
// GraphicsSettingsManager.SettingToChange = newValue;
//GraphicsSettingsManager.Fullscreen = true;
GraphicsSettingsManager.BackFaceCulling = true;
GraphicsSettingsManager.DepthBuffer = true;
GraphicsSettingsManager.VerticalSyncronization = true;
GraphicsSettingsManager.ClearColor = Color.DEFAULT;
GraphicsSettingsManager.Texture2D = true;
GraphicsSettingsManager.Blend = true;
GraphicsSettingsManager.SetAlphaBlending();
GraphicsSettingsManager.Lighting = true;
}
public override void InitializeSounds()
{
// LOAD SOUNDS HERE.
// Use the static class "SoundManager"
// Just keep this function here. I haven't finished the SoundManager class yet...
Output.WriteLine("No sound effects currently loaded.");
}
public override void InitializeTextures()
{
// LOAD TEXTURES HERE.
// Use the static class "TextureManager"
// Supported file types: bmp, jpeg, png, gif, ttf
// EXAMPLES:
// TextureManager.LoadTexture("nameOfTexture", "filePath");
// NOTE: If you use my static "FilePath" class the directory should be cross platform
// Textures for models
TextureManager.LoadTexture("grass", FilePath.FromRelative(@"\..\..\Assets\Textures\grass.bmp"));
TextureManager.LoadTexture("rock", FilePath.FromRelative(@"\..\..\Assets\Textures\rock3.bmp"));
TextureManager.LoadTexture("rock2", FilePath.FromRelative(@"\..\..\Assets\Textures\rock4.bmp"));
TextureManager.LoadTexture("RedRanger", FilePath.FromRelative(@"\..\..\Assets\Textures\RedRangerBody.bmp"));
TextureManager.LoadTexture("Tux", FilePath.FromRelative(@"\..\..\Assets\Textures\tux.bmp"));
TextureManager.LoadTexture("TuxRed", FilePath.FromRelative(@"\..\..\Assets\Textures\tuxRed.bmp"));
TextureManager.LoadTexture("TuxGreen", FilePath.FromRelative(@"\..\..\Assets\Textures\tuxGreen.bmp"));
TextureManager.LoadTexture("BlueRanger", FilePath.FromRelative(@"\..\..\Assets\Textures\BlueRangerBody.bmp"));
TextureManager.LoadTexture("PinkRanger", FilePath.FromRelative(@"\..\..\Assets\Textures\PinkRangerBody.bmp"));
TextureManager.LoadTexture("BlackRanger", FilePath.FromRelative(@"\..\..\Assets\Textures\BlackRangerBody.bmp"));
TextureManager.LoadTexture("YellowRanger", FilePath.FromRelative(@"\..\..\Assets\Textures\YellowRangerBody.bmp"));
TextureManager.LoadTexture("MushroomCloud", FilePath.FromRelative(@"\..\..\Assets\Textures\MushCloud.bmp"));
// Textures for menus
TextureManager.LoadTexture("Menu", FilePath.FromRelative(@"\..\..\Assets\Textures\Menu.bmp"));
// Textrues for skybox
TextureManager.LoadTexture("SkyboxLeft", FilePath.FromRelative(@"\..\..\Assets\Textures\SkyBoxes\NightWalker\NightWalkerLeft.bmp"));
TextureManager.LoadTexture("SkyboxRight", FilePath.FromRelative(@"\..\..\Assets\Textures\SkyBoxes\NightWalker\NightWalkerRight.bmp"));
TextureManager.LoadTexture("SkyboxFront", FilePath.FromRelative(@"\..\..\Assets\Textures\SkyBoxes\NightWalker\NightWalkerFront.bmp"));
TextureManager.LoadTexture("SkyboxBack", FilePath.FromRelative(@"\..\..\Assets\Textures\SkyBoxes\NightWalker\NightWalkerBack.bmp"));
TextureManager.LoadTexture("SkyboxTop", FilePath.FromRelative(@"\..\..\Assets\Textures\SkyBoxes\NightWalker\NightWalkerTop.bmp"));
}
public override void InitializeFonts()
{
// LOAD Fonts HERE.
// Use the static class "TextManager"
// Supported file types: fnt
// NOTE: the image files used by the fnt files must be supported by my image importer
// EXAMPLES:
// TextManager.LoadFontFile("nameOfFont", "filePathToFont", "filePathToFontTextures");
// Renderer.Font = TextManager.Get("nameOfFont");
// NOTE: If you use my static "FilePath" class the directory should be cross platform
TextManager.LoadFontFile("Calibri", FilePath.FromRelative(@"\..\..\Assets\Texts\Calibri2.fnt"), FilePath.FromRelative(@"\..\..\Assets\Texts\"));
}
public override void InitializeModels()
{
// LOAD MODEL FILES HERE.
// Use the static class "StaticModelManager"
// Supported file types: obj
// NOTE: I only support obj file with single objects at the moment, please export each object separately
// NOTE: I currently do not support materials
// I WILL BE CHANGING THESE FUNCTIONS AROUND SOON (ONCE I GET A FULLY FEATURED OBJ IMPORTER WORKING),
// BUT HERE IS THER CURRENT TWO FUNCTIONS YOU SHOULD USE...
// EXAMPLES:
// StaticModelManager.LoadMesh("meshName", "filePath");
// string[] textures; string[] meshes; string[] meshNamesRelativeToTheModel;
// StaticModelManager.LoadModel("modelName", textures, meshes, meshNamesRelativeToTheModel);
// NOTE: If you use my static "FilePath" class the directory should be cross platform
// Loading the meshes
// Meshes are parts of a static model that have the same texture. You cannot render static
// meshes because they do not have transformations. Put them in a static model to render them.
StaticModelManager.LoadMesh("terrain", FilePath.FromRelative(@"\..\..\Assets\Models\Terrain.obj"));
StaticModelManager.LoadMesh("RedRanger", FilePath.FromRelative(@"\..\..\Assets\Models\RedRanger.obj"));
StaticModelManager.LoadMesh("BlackRanger", FilePath.FromRelative(@"\..\..\Assets\Models\RedRanger.obj"));
StaticModelManager.LoadMesh("BlueRanger", FilePath.FromRelative(@"\..\..\Assets\Models\RedRanger.obj"));
StaticModelManager.LoadMesh("YellowRanger", FilePath.FromRelative(@"\..\..\Assets\Models\RedRanger.obj"));
StaticModelManager.LoadMesh("PinkRanger", FilePath.FromRelative(@"\..\..\Assets\Models\RedRanger.obj"));
StaticModelManager.LoadMesh("Tux", FilePath.FromRelative(@"\..\..\Assets\Models\tux.obj"));
StaticModelManager.LoadMesh("TuxRed", FilePath.FromRelative(@"\..\..\Assets\Models\tux.obj"));
StaticModelManager.LoadMesh("TuxGreen", FilePath.FromRelative(@"\..\..\Assets\Models\tux.obj"));
StaticModelManager.LoadMesh("mountain", FilePath.FromRelative(@"\..\..\Assets\Models\mountain.obj"));
StaticModelManager.LoadMesh("MushroomCloud", FilePath.FromRelative(@"\..\..\Assets\Models\MushCloud.obj"));
// Forming the static models out of the meshes and textures
// Static models represent a collection of static meshes that all have the same transformational values.
StaticModelManager.LoadModel("MushroomCloud", new string[] { "MushroomCloud" }, new string[] { "MushroomCloud" }, new string[] { "MushroomCloud" });
StaticModelManager.LoadModel("Terrain", new string[] { "Terrain" }, new string[] { "terrain" }, new string[] { "grass" });
StaticModelManager.LoadModel("Mountain", new string[] { "mountain" }, new string[] { "mountain" }, new string[] { "rock" });
StaticModelManager.LoadModel("Mountain2", new string[] { "mountain" }, new string[] { "mountain" }, new string[] { "rock2" });
StaticModelManager.LoadModel("Tux", new string[] { "Body" }, new string[] { "Tux" }, new string[] { "Tux" });
StaticModelManager.LoadModel("TuxRed", new string[] { "Body" }, new string[] { "TuxRed" }, new string[] { "TuxRed" });
StaticModelManager.LoadModel("TuxGreen", new string[] { "Body" }, new string[] { "TuxGreen" }, new string[] { "TuxGreen" });
StaticModelManager.LoadModel("RedRanger", new string[] { "Body" }, new string[] { "RedRanger" }, new string[] { "RedRanger" });
StaticModelManager.LoadModel("BlueRanger", new string[] { "Body" }, new string[] { "BlueRanger" }, new string[] { "BlueRanger" });
StaticModelManager.LoadModel("BlackRanger", new string[] { "Body" }, new string[] { "BlackRanger" }, new string[] { "BlackRanger" });
StaticModelManager.LoadModel("PinkRanger", new string[] { "Body" }, new string[] { "PinkRanger" }, new string[] { "PinkRanger" });
StaticModelManager.LoadModel("YellowRanger", new string[] { "Body" }, new string[] { "YellowRanger" }, new string[] { "YellowRanger" });
StaticModelManager.LoadMesh("Dodecahedron", FilePath.FromRelative(@"\..\..\Assets\Models\Dodecahedron.obj"));
StaticModelManager.LoadModel("Dodecahedron", new string[] { "Body" }, new string[] { "Dodecahedron" }, new string[] { "rock2" });
}
public override void InitializeShaders()
{
// LOAD SHADER FILES HERE.
// Use the static class "ShaderManager"
// Supported file types: glsl
// EXAMPLES:
// ShaderManager.LoadVertexShader("vertexShaderName", FilePath.FromRelative((@"filePathToVertexShader"));
// ShaderManager.LoadFragmentShader("fragmentShaderName", FilePath.FromRelative((@"filePathToFragmentShader"));
// ShaderManager.LoadGeometryShader("geometryShaderName", FilePath.FromRelative((@"filePathToGeometryShader"));
// ShaderManager.LoadExtendedGeometryShader("extendedGeometryShaderName", FilePath.FromRelative((@"filePathToExtendedGeometryShader"));
// ShaderManager.MakeShaderProgram("shaderProgramName", "vertexShaderName", "fragmentShaderName", "geometryShaderName", "extendedGeometryShaderName");
// // NOTE: PARAMETERS TO THE "MakeShaderProgram()" METHOD MAY BE "null" IF YOU AREN'T USING THOSE SHADERS
// ShaderManager.SetActiveShader("shaderProgramName");
// NOTE: If you use my static "FilePath" class the directory should be cross platform
// These basic shaders do not include lighting effects.
ShaderManager.LoadVertexShader("VertexShaderBasic", FilePath.FromRelative(@"\..\..\Assets\Shaders\Vertex\VertexShaderBasic.glsl"));
ShaderManager.LoadFragmentShader("FragmentShaderBasic", FilePath.FromRelative(@"\..\..\Assets\Shaders\Fragment\FragmentShaderBasic.glsl"));
ShaderManager.MakeShaderProgram("ShaderProgramBasic", "VertexShaderBasic", "FragmentShaderBasic", null, null);
ShaderManager.LoadVertexShader("VertexShaderLight", FilePath.FromRelative(@"\..\..\Assets\Shaders\Vertex\VertexShaderLight2.glsl"));
ShaderManager.LoadFragmentShader("FragmentShaderLight", FilePath.FromRelative(@"\..\..\Assets\Shaders\Fragment\FragmentShaderLight2.glsl"));
ShaderManager.MakeShaderProgram("ShaderProgramLight", "VertexShaderLight", "FragmentShaderLight", null, null);
//ShaderManager.SetActiveShader("ShaderProgramBasic");
// This is really hack-y, I will be editing this soon.
GL.ShadeModel(ShadingModel.Smooth);
GL.Material(MaterialFace.Front, MaterialParameter.Specular, new float[] { 1.0f, 1.0f, 1.0f, 1.0f });
GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 800.0f);
GL.Material(MaterialFace.Front, MaterialParameter.Ambient, new float[] { 0.4f, 0.4f, 0.4f, 1.0f });
GL.Material(MaterialFace.Front, MaterialParameter.Diffuse, new float[] { .8f, .8f, 0.8f, 1.0f });
GL.Light(LightName.Light0, LightParameter.Position, new float[] { 0.0f, 1000.0f, 0.0f, 1.0f });
Renderer.DefaultShaderProgram = ShaderManager.LightShader;
}
public override void InitializeStates()
{
// LOAD THE GAME STATES HERE
// Use the static class "StateManager"
// EXAMPLES:
// StateManager.AddState(new YourStateClass("nameOfState"));
// StateManager.StateManager.TriggerStateLoad("nameOfState");
// StateManager.ChangeState("nameOfState");
//StateManager.AddState(new GameState("gameState"));
StateManager.AddState(new AiBattle("AiBattle"));
// The following line calls the "Load" function of your state.
// The state must be loaded before you make it the current state.
StateManager.TriggerStateLoad("AiBattle");
StateManager.ChangeState("AiBattle");
// Try this state for sprite usage example
/*StateManager.AddState(new SpriteState("SpriteState"));
StateManager.TriggerStateLoad("SpriteState");
StateManager.ChangeState("SpriteState");*/
}
public override void Update(double elapsedTime)
{
// DO NOT UPDATE LOW LEVEL GAME LOGIC HERE!!!
// Only change states as need be with the static "StateManager" class.
// EXAMPLES:
// string stateStatus = StateManager.Update((float)elapsedTime);
// if (stateStatus == "menuState")
// StateManager.ChangeState("menuState");
// NOTE: DO NOT alter this function unless you fully understand it
string stateStatus = StateManager.Update((float)elapsedTime);
}
}
}
|
Java
|
UTF-8
| 3,457 | 2.5625 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAL;
import banco.Banco;
import entidades.Pet;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author GABRIEL
*/
public class DALpets
{
public boolean salvar(Pet p)
{
String sql="insert into pet values ('#0',#1',#2,'#3','#4','#5',#6,#7)";
sql=sql.replace("#0",""+p.getCod());
sql=sql.replace("#1",p.getNome());
sql=sql.replace("#2",""+p.getPeso());
sql=sql.replace("#3",p.getCor());
sql=sql.replace("#4",p.getDataNasc().toString());
sql=sql.replace("#5",""+p.getSexo());
sql=sql.replace("#6",""+p.getEspecie().getCod());
sql=sql.replace("#7",""+p.getRaca().getCod());
return Banco.getCon().manipular(sql);
}
public boolean alterar(Pet p)
{
String sql="update pet set pet_nome='#1', pet_peso=#2, pet_cor'#3', pet_dtnasc='#4', pet_sexo='#5', esp_cod=#6, rac_cod='#7' where pet_cod=#8";
sql=sql.replace("#1",p.getNome());
sql=sql.replace("#1",p.getNome());
sql=sql.replace("#2",""+p.getPeso());
sql=sql.replace("#3",p.getCor());
sql=sql.replace("#4",p.getDataNasc().toString());
sql=sql.replace("#5",""+p.getSexo());
sql=sql.replace("#6",""+p.getEspecie().getCod());
sql=sql.replace("#7",""+p.getRaca().getCod());
sql=sql.replace("#8",""+p.getCod());
return Banco.getCon().manipular(sql);
}
public boolean apagar(Pet p)
{
return Banco.getCon().
manipular("delete from pet where pet_cod="+p.getCod());
}
public Pet getUm(int cod)
{
Pet pet=null;
String sql="select * from pet where pet_cod="+cod;
ResultSet rs=Banco.getCon().consultar(sql);
try{
if(rs.next())
pet=new Pet(rs.getInt("pet_cod"),rs.getString("pet_nome"),
rs.getDouble("pet_peso"),rs.getString("pet_cor"),
rs.getDate("pet_dtnasc").toLocalDate(),
rs.getString("pet_sexo").charAt(0),
new DALespecie().getUm(rs.getInt("esp_cod")),
new DALracas().getUm(rs.getInt("rac_cod")));
}
catch(Exception e){}
return pet;
}
public List <Pet> get(String filtro) //se filtro vazio, retorna todas
{
List <Pet> pets=new ArrayList();
Pet pet=null;
String sql="select * from pet";
if(!filtro.isEmpty())
sql=sql+"where "+filtro;
ResultSet rs=Banco.getCon().consultar(sql);
try{
while (rs.next())
{ pet=new Pet(rs.getInt("pet_cod"),rs.getString("pet_nome"),
rs.getDouble("pet_peso"),rs.getString("pet_cor"),
rs.getDate("pet_dtnasc").toLocalDate(),
rs.getString("pet_sexo").charAt(0),
new DALespecie().getUm(rs.getInt("esp_cod")),
new DALracas().getUm(rs.getInt("rac_cod")));
pets.add(pet);
}
}
catch(Exception e){}
return pets;
}
}
|
Java
|
UTF-8
| 2,566 | 3.140625 | 3 |
[] |
no_license
|
package db.pojos;
import java.sql.Date;
import java.util.*;
public class Day {
private Integer id;
private int deaths;
private int infectedPatients;
private float average;
private Date date;
private List<Day> savedDates = new ArrayList();
public Day(Integer id, int deaths,int infectedPatients , float average, Date date) {
super();
this.id = id;
this.deaths = deaths;
this.infectedPatients=infectedPatients;
this.average = average;
this.date = date;
}
public Day( int deaths, int infectedPatients,float average, Date date) {
super();
this.id = id;
this.deaths = deaths;
this.infectedPatients=infectedPatients;
this.average = average;
this.date = date;
}
public Integer getId() {
return id;
}
public int getInfectedPatients() {
return infectedPatients;
}
public void setId(Integer id) {
this.id = id;
}
public void setInfectedPatients(int infectedPatients) {
this.infectedPatients = infectedPatients;
}
public List<Day> getSavedDates() {
return savedDates;
}
public int getDeaths() {
return deaths;
}
public float getAverage() {
return average;
}
public Date getDate() {
return date;
}
public void setDeaths(int deaths) {
this.deaths = deaths;
}
public void setAverage(float average) {
this.average = average;
}
public void setSavedDates(List<Day> savedDates) {
this.savedDates = savedDates;
}
public void setDate(Date date) {
this.date = date;
}
public void LocalDate(Date date) {
this.date = date;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(average);
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + deaths;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Day other = (Day) obj;
if (Float.floatToIntBits(average) != Float.floatToIntBits(other.average))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (deaths != other.deaths)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Day [id=" + id + ", deaths=" + deaths + ", average=" + average + ", date=" + date + "]";
}
}
|
PHP
|
UTF-8
| 371 | 3.234375 | 3 |
[] |
no_license
|
<?php
class Local
{
private $name;
private $location;
public function __construct(string $name, array $location)
{
$this->name = $name;
$this->location = $location;
}
public function getInformations() : array
{
return [
'name' => $this->name,
'location' => $this->location
];
}
}
|
Markdown
|
UTF-8
| 9,871 | 2.5625 | 3 |
[] |
no_license
|
# 大型网站架构系列:负载均衡详解(3) - 建建的博客 - CSDN博客
2017年03月10日 13:53:42[纪建](https://me.csdn.net/u013898698)阅读数:125
## [大型网站架构系列:负载均衡详解(3)](http://www.cnblogs.com/itfly8/p/5080743.html)
## 本次分享大纲
- 软件负载均衡概述
- Ngnix负载均衡
- Lvs负载均衡
- Haproxy负载均衡
- 本次分享总结
## 一、软件负载均衡概述
硬件负载均衡性能优越,功能全面,但是价格昂贵,一般适合初期或者土豪级公司长期使用。因此软件负载均衡在互联网领域大量使用。常用的软件负载均衡软件有Nginx,Lvs,HaProxy等。本文参考大量文档,部分为直接拷贝,参考出处见负载均衡详解(4)。
## 二、Ngnix负载均衡
Ngnix是一款轻量级的Web服务器/反向代理服务器,工作在七层Http协议的负载均衡系统。具有高性能、高并发、低内存使用等特点。是一个轻量级的Http和反向代理服务器。Nginx使用epoll and kqueue作为开发模型。能够支持高达 50,000 个并发连接数的响应。
操作系统:Liunx,Windows(Linux、FreeBSD、Solaris、Mac OS X、AIX以及Microsoft Windows)
开发语言:C
并发性能:官方支持每秒5万并发,实际国内一般到每秒2万并发,有优化到每秒10万并发的。具体性能看应用场景。
### 2.1.特点
1.模块化设计:良好的扩展性,可以通过模块方式进行功能扩展。
2.高可靠性:主控进程和worker是同步实现的,一个worker出现问题,会立刻启动另一个worker。
3.内存消耗低:一万个长连接(keep-alive),仅消耗2.5MB内存。
4.支持热部署:不用停止服务器,实现更新配置文件,更换日志文件、更新服务器程序版本。
5.并发能力强:官方数据每秒支持5万并发;
6.功能丰富:优秀的反向代理功能和灵活的负载均衡策略
### 2.2.功能
#### 2.2.1基本功能
- 支持静态资源的web服务器。
- http,smtp,pop3协议的反向代理服务器、缓存、负载均衡;
- 支持FASTCGI(fpm)
- 支持模块化,过滤器(让文本可以实现压缩,节约带宽),ssl及图像大小调整。
- 内置的健康检查功能
- 基于名称和ip的虚拟主机
- 定制访问日志
- 支持平滑升级
- 支持KEEPALIVE
- 支持url rewrite
- 支持路径别名
- 支持基于IP和用户名的访问控制。
- 支持传输速率限制,支持并发数限制。
#### 2.2.2扩展功能
#### 2.2.3性能
Nginx的高并发,官方测试支持5万并发连接。实际生产环境能到2-3万并发连接数。10000个非活跃的HTTP keep-alive 连接仅占用约2.5MB内存。三万并发连接下,10个Nginx进程,消耗内存150M。淘宝tengine团队测试结果是“24G内存机器上,处理并发请求可达200万”。
### 2.3架构
#### 2.3.1Nginx的基本工作模式

一个master进程,生成一个或者多个worker进程。但是这里master是使用root身份启动的,因为nginx要工作在80端口。而只有管理员才有权限启动小于低于1023的端口。master主要是负责的作用只是启动worker,加载配置文件,负责系统的平滑升级。其它的工作是交给worker。那么当worker被启动之后,也只是负责一些web最简单的工作,而其他的工作都是有worker中调用的模块来实现的。
模块之间是以流水线的方式实现功能的。流水线,指的是一个用户请求,由多个模块组合各自的功能依次实现完成的。比如:第一个模块只负责分析请求首部,第二个模块只负责查找数据,第三个模块只负责压缩数据,依次完成各自工作。来实现整个工作的完成。
他们是如何实现热部署的呢?其实是这样的,我们前面说master不负责具体的工作,而是调用worker工作,他只是负责读取配置文件,因此当一个模块修改或者配置文件发生变化,是由master进行读取,因此此时不会影响到worker工作。在master进行读取配置文件之后,不会立即的把修改的配置文件告知worker。而是让被修改的worker继续使用老的配置文件工作,当worker工作完毕之后,直接当掉这个子进程,更换新的子进程,使用新的规则。
#### 2.3.2Nginx支持的sendfile机制
Sendfile机制,用户将请求发给内核,内核根据用户的请求调用相应用户进程,进程在处理时需要资源。此时再把请求发给内核(进程没有直接IO的能力),由内核加载数据。内核查找到数据之后,会把数据复制给用户进程,由用户进程对数据进行封装,之后交给内核,内核在进行tcp/ip首部的封装,最后再发给客户端。这个功能用户进程只是发生了一个封装报文的过程,却要绕一大圈。因此nginx引入了sendfile机制,使得内核在接受到数据之后,不再依靠用户进程给予封装,而是自己查找自己封装,减少了一个很长一段时间的浪费,这是一个提升性能的核心点。

以上内容摘自网友发布的文章,简单一句话是资源的处理,直接通过内核层进行数据传递,避免了数据传递到应用层,应用层再传递到内核层的开销。
目前高并发的处理,一般都采用sendfile模式。通过直接操作内核层数据,减少应用与内核层数据传递。
#### 2.3.3Nginx通信模型(I/O复用机制)
开发模型:epoll和kqueue。
支持的事件机制:kqueue、epoll、rt signals、/dev/poll 、event ports、select以及poll。
支持的kqueue特性包括EV_CLEAR、EV_DISABLE、NOTE_LOWAT、EV_EOF,可用数据的数量,错误代码.
支持sendfile、sendfile64和sendfilev;文件AIO;DIRECTIO;支持Accept-filters和TCP_DEFER_ACCEP.
以上概念较多,大家自行百度或谷歌,知识领域是网络通信(BIO,NIO,AIO)和多线程方面的知识。
### 2.4均衡策略
nginx的负载均衡策略可以划分为两大类:内置策略和扩展策略。内置策略包含加权轮询和ip hash,在默认情况下这两种策略会编译进nginx内核,只需在nginx配置中指明参数即可。扩展策略有很多,如fair、通用hash、consistent hash等,默认不编译进nginx内核。由于在nginx版本升级中负载均衡的代码没有本质性的变化,因此下面将以nginx1.0.15稳定版为例,从源码角度分析各个策略。
### 2.4.1. 加权轮询(weighted round robin)
轮询的原理很简单,首先我们介绍一下轮询的基本流程。如下是处理一次请求的流程图:

图中有两点需要注意,第一,如果可以把加权轮询算法分为先深搜索和先广搜索,那么nginx采用的是先深搜索算法,即将首先将请求都分给高权重的机器,直到该机器的权值降到了比其他机器低,才开始将请求分给下一个高权重的机器;第二,当所有后端机器都down掉时,nginx会立即将所有机器的标志位清成初始状态,以避免造成所有的机器都处在timeout的状态,从而导致整个前端被夯住。
### 2.4.2. ip hash
ip hash是nginx内置的另一个负载均衡的策略,流程和轮询很类似,只是其中的算法和具体的策略有些变化,如下图所示:

### 2.4.3. fair
fair策略是扩展策略,默认不被编译进nginx内核。其原理是根据后端服务器的响应时间判断负载情况,从中选出负载最轻的机器进行分流。这种策略具有很强的自适应性,但是实际的网络环境往往不是那么简单,因此要慎用。
### 2.4.4 通用hash、一致性hash
这两种也是扩展策略,在具体的实现上有些差别,通用hash比较简单,可以以nginx内置的变量为key进行hash,一致性hash采用了nginx内置的一致性hash环,可以支持memcache。
### 2.5场景
Ngnix一般作为入口负载均衡或内部负载均衡,结合反向代理服务器使用。以下架构示例,仅供参考,具体使用根据场景而定。
#### 2.5.1入口负载均衡架构

Ngnix服务器在用户访问的最前端。根据用户请求再转发到具体的应用服务器或二级负载均衡服务器(LVS)
#### 2.5.2内部负载均衡架构

LVS作为入口负载均衡,将请求转发到二级Ngnix服务器,Ngnix再根据请求转发到具体的应用服务器。
#### 2.5.3Ngnix高可用

分布式系统中,应用只部署一台服务器会存在单点故障,负载均衡同样有类似的问题。一般可采用主备或负载均衡设备集群的方式节约单点故障或高并发请求分流。
Ngnix高可用,至少包含两个Ngnix服务器,一台主服务器,一台备服务器,之间使用Keepalived做健康监控和故障检测。开放VIP端口,通过防火墙进行外部映射。
DNS解析公网的IP实际为VIP。
大型网站架构交流(架构之家)QQ群一466097527(已满)群二464527023 (已满)群三612849302(可加);微信公众号:itfly8。以架构为核心的兴趣群,专注大型分布式网站架构,大数据,架构模式,设计模式。技术分享,经典电子书分享,欢迎加入!
|
Python
|
UTF-8
| 3,356 | 4.03125 | 4 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
************************************************
@Time : 2019-08-05 10:58
@Author : zxp
@Project : AlgorithmAndDataStructure
@File : 13_基本排序.py
@Description: ==================================
冒泡排序,选择排序,插入排序
@license: (C) Copyright 2013-2019.
************************************************
"""
# *********+++++++++++*********========*********+++++++++++*********========
# 三个排序方法的复杂度为:O(n^2)
# 冒泡排序: 每次寻找最大/小值--放到最后
# 选择排序: 每次寻找相对 大/小值--找到之后,与最前面的数据互换.
# 插入排序: 以插入的方式(插入之前进行比较)得到有序数据
# 从小到大: 索引值和值的方向是一样的;从大到小,索引值和值的方向是一样的
# *********+++++++++++*********========*********+++++++++++*********========
import random
class BaseSort(object):
def __init__(self):
"""继承父类的排序--写的一个初始化代码"""
super(BaseSort, self).__init__()
def bubbleSort(self, data_quence):
"""从小到大排序,后面的的顺序会固定"""
data_quence_length = len(data_quence)
for x in range(data_quence_length - 1):
# 比较的范围
for y in range(data_quence_length - 1 - x):
if data_quence[y] > data_quence[y + 1]:
"""顺序排序,索引值和值方向相同"""
data_quence[y], data_quence[y + 1] = data_quence[y + 1], data_quence[y]
return data_quence
def selectSort(self, data_sequence):
"""每次找到最小的,与第一个数互换,依次比较"""
data_sequence_length = len(data_sequence)
# 选择的次数
for x in range(0, data_sequence_length - 1):
min_index = x
# 选择的范围
for y in range(x, data_sequence_length):
# 选出此次最小的值,用min_index标记
if data_sequence[min_index] > data_sequence[y]:
min_index = y
# 最小值与当前位置的值互换
if min_index != x:
data_sequence[min_index], data_sequence[x] = data_sequence[x], data_sequence[min_index]
return data_sequence
def insertSort(self, data_sequence):
data_quence_length = len(data_sequence)
# 比较次数及其比较范围
for i in range(1, data_quence_length):
# pos就是为data_sequence中i位置的值,所找到合适的插入位置
pos = i
value = data_sequence[i]
while pos > 0 and value < data_sequence[pos - 1]:
data_sequence[pos], data_sequence[pos - 1] = data_sequence[pos - 1], value
pos -= 1
# 为i位置上的值 找到合适的位置插入(在有序数列当中)
data_sequence[pos] = data_sequence[i]
return data_sequence
def testBaseSorted():
sequence_l = list(range(10))
random.shuffle(sequence_l)
sorted_sequence = sorted(sequence_l)
base_sort = BaseSort()
assert base_sort.bubbleSort(sequence_l) == sorted_sequence
assert base_sort.selectSort(sequence_l) == sorted_sequence
assert base_sort.insertSort(sequence_l) == sorted_sequence
|
Java
|
UTF-8
| 1,327 | 2.4375 | 2 |
[] |
no_license
|
/**
*
*/
package com.santosh.moviesapp.services.impl;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.santosh.moviesapp.persistence.dao.CustomerDao;
import com.santosh.moviesapp.persistence.models.Customer;
import com.santosh.moviesapp.services.CustomerService;
/**
* @author santkamb
*
*/
@Service
public class CustomerServiceImpl implements CustomerService {
private final Logger logger = LoggerFactory.getLogger(CustomerServiceImpl.class);
private CustomerDao customerDao;
/**
* @param customerDao
*/
public CustomerServiceImpl(CustomerDao customerDao) {
super();
this.customerDao = customerDao;
}
@Override
public Iterable<Customer> retrieveAllCustomers() {
return customerDao.getAllCustomers();
}
@Override
public Iterable<Customer> save(List<Customer> customers) {
Iterable<Customer> customerList = customerDao.save(customers);
logger.info("customers are saved : {} ",customerList);
return customerList;
}
@Override
public Optional<Customer> retrieveCustomer(Long customerId) {
Optional<Customer> customer = customerDao.getCustomer(customerId);
logger.info("customer: {} ",customer);
return customer;
}
}
|
Markdown
|
UTF-8
| 1,525 | 2.875 | 3 |
[] |
no_license
|
# Botanical Workspace
A web application that helps you stay focused while maintaining a real houseplant
## Description
Botanical Workspace is a productivity app with a twist - your focus determines the fate of a real houseplant. When you want to be productive, click the start timer button and get to work! If you leave the Botanical Workspace page, the timer ends and your connected houseplant gets flooded with water, a terrible fate. However, if you make it all the way, you are rewarded and your plant is safe.
## Background
Submitted to the Backyard Hacks 2020 Hackathon.
## Technology
Botanical Workspace is built on three components, the front-end focus app, the back-end server, and the water pump hardware.
### Front-end
The front-end is built with React. It has a countdown timer for productivity and a chart reflecting the health of the plant. The chart uses chart.js. Requests and information are sent to the back-end server
### Back-end and Hardware
The back-end is made with a Flask server which handles the routes and information from the front-end application. Using piserial, it communicates with the Arduino Uno. The water mechanic uses a solenoid valve connected to a water source.
## Usage
Make sure you have the dependencies. You may need more than what is listed below.
```
npm install
pip install flask
pip install piserial
```
Then run the app and server.
```
npm start
python app.py
```
## Contributors
Matthews Ma
Samer Rustum
Rohan Shetty
Harry Kim
|
Python
|
UTF-8
| 2,210 | 4.25 | 4 |
[] |
no_license
|
import turtle
def getSideLength():
"""
This function is here to ask the user for the size of the image/flower.
:return: This return returns the size that the user has just replied with back to the main and converts their input
to an int.
"""
side_length = input("What do you want the side length to be?")
return int(side_length)
def getCenterColor():
"""
This function is here to ask the user for the center petal color
:return: This return returns the center color that was just recieved back to the main so that the rest of the
program knows the center color.
"""
center_color = input("What do you want the center petal color to be?")
return center_color
def getPetalColor():
"""
This function is here to ask the user for the remaining petals color.
:return: This return returns the petal color that was just recieved and sends it to the main so that the rest of
the program knows the remaining petals color.
"""
petal_color = input("What do you want the petal color to be?")
return petal_color
def draw_hexagon(size, color):
"""
This function is drawing the hexagon itself.
:param size: Uses the param size defined in getSideLength and main.
:param color: Uses the param color defined in getCenterColor and main.
:return: Returns the parameters
"""
turtle.begin_fill()
# Function that draws octagon and makes it a specific color
for x in range(6):
turtle.color(color)
turtle.fd(size)
turtle.rt(60)
turtle.end_fill()
turtle.speed(100)
def turn_turtle(size):
"""
This function is here to turn the turtle after drawing a hexagon.
:param size: Uses the size param to know how far forward to go before turning.
"""
turtle.fd(size)
turtle.left(60)
def main():
color = getCenterColor()
size = getSideLength()
petal_color = getPetalColor()
turtle.goto(0, 0)
turtle.left(120)
draw_hexagon(size, color)
turtle.right(120)
turn_turtle(size)
draw_hexagon(size, petal_color)
for y in range(5):
turn_turtle(size)
draw_hexagon(size, petal_color)
main()
turtle.exitonclick()
|
Markdown
|
UTF-8
| 4,167 | 3.109375 | 3 |
[] |
no_license
|
## 功能说明
调低设备温度接口属于温度控制和查询消息(Temperature Control and Query Messages),包括 *DecrementTargetTemperatureRequest*、*DecrementTargetTemperatureConfirmation* 用于将指定设备的温度降低指定值。
>**注意**:Smart Home Skill API 始终将摄氏温度设置传递给您的技能适配器,而您的技能适配器应该以摄氏温度返回温度。您还需要将温度保存至少两位小数,这能确保内部转换需要的足够精度。
## DecrementTargetTemperatureRequest
#### 示例语句
“小微,空调温度调低一度”
#### 目的
请求指定设备的温度降低指定的数量,以摄氏度为单位。从 Smart Home Skill API 发送到技能适配器。
### Header 描述
| 属性 | 值 |
| --- | --- |
| name | DecrementTargetTemperatureRequest |
| namespace | SmartHome.Control |
### Payload 描述
| 属性 | 描述 | 是否必需 |
| --- | --- | --- |
| accessToken | 与客户的设备云帐户相关的访问令牌。| 是 |
| appliance object | 执行操作的设备。| 是 |
| appliance.applianceID | 设备标识符。标识符在技术适配器的域内的最终用户拥有的所有设备上必须是唯一的。此外,标识符需要在同一设备的多个发现请求之间保持一致。标识符可以包含任何字母或数字和以下特殊字符:`_ - = # ; : ? @ &`。该值不能超过256个字符。| 是 |
| appliance.additionalApplianceDetails | 提供关于技能适配器使用的设备的附加信息的字符串名称/值对。该属性的内容不能超过5000字节。而且,Smart Home Skill API 即不理解也不使用这些数据。| 是,但列表可以为空。|
| deltaTemperature | 指示要降低的温度数值对象(以摄氏度表示)。仅包含一个值为数字的属性*value*。| 是 |
### 示例代码
```
{
"header": {
"messageId": "9422676d-2356-4aa7-aa88-c642f12bfcd6",
"name": "DecrementTargetTemperatureRequest",
"namespace": "SmartHome.Control",
"payloadVersion": "1"
},
"payload": {
" deltaTemperature": {
"value": 1.0
},
"accessToken": "[OAuth token here]",
"appliance": {
"additionalApplianceDetails": {},
"applianceId": "[Device ID]"
}
}
}
```
## DecrementTargetTemperatureConfirmation
#### 小微响应示例
“好的”**
#### 目的
表示设备的目标温度成功降低。这是对 *DecrementTargetTemperatureRequest* 的预期响应,并从技能适配器发送到 Smart Home Skill API。
### Header 描述
| 属性 | 值 |
| --- | --- |
| name | DecrementTargetTemperatureConfirmation |
| namespace | SmartHome.Control |
### Payload 描述
| 属性 | 描述 | 必需 |
| --- | --- | --- |
| targetTemperature | 指示设备设置的目标温度(以摄氏度为单位)的对象。仅包含一个值是数字的属性 *value*。| 是 |
| temperatureMode | 指示设备设置的温度模式的对象。包含单个属性 *value*,其值为以下字符串之一:AUTO,COOL,HEAT。| 是 |
| previousState object | 表示设备的先前模式和温度。| 是 |
| previousState.targetTemperature | 指示设备设置的目标温度(以摄氏度为单位)的对象。仅包含一个值是数字的属性 *value*。| 是 |
| previousState. temperatureMode | 指示设备设置的温度模式的对象。包含单个属性 *value*,其值为以下字符串之一:AUTO,COOL,HEAT。| 是 |
### 示例代码
```
{
"header": {
"messageId": "9422676d-2356-4aa7-aa88-c642f12bfcd6",
"name": "DecrementTargetTemperatureConfirmation",
"namespace": "SmartHome.Control",
"payloadVersion": "1"
},
"payload": {
"targetTemperature": {
"value": 25.0
},
"temperatureMode": {
"value": "AUTO"
},
"previousState": {
"targetTemperature": {
"value": 21.0
},
"temperatureMode": {
"value": "AUTO"
}
}
}
}
```
|
Java
|
UTF-8
| 162 | 1.945313 | 2 |
[] |
no_license
|
package com.nsp.test.jvm.class_test;
public class SuperClass
{
public static final int value = 123;
static {
System.out.println("Super class init");
}
}
|
C
|
UTF-8
| 4,765 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#include "commander.h"
#include "grunt.h"
int get_num_args(char *line) {
// Get the number of arguments by counting non space chunks
int num_args = 0;
int in_space = 0;
int i; for (i = 0; line[i]; i++) {
if (line[i] != ' ') {
if (num_args == 0) {
num_args = 1;
} else if (in_space) {
in_space = 0;
num_args++;
}
}
if (line[i] == ' ' && num_args) in_space = 1;
}
return num_args;
}
int get_and_run_userin() {
char buff[256];
fgets(buff, sizeof(buff), stdin);
// Buff will have space-separated command line arguments, then a newline,
// then a terminating null. We can use strsep to get rid of the newline.
// Since fgets will terminate on the first newline, we can be certain there
// is no next command after it
char *ptr_to_buff = buff;
char *line = strsep(&ptr_to_buff, "\n");
// Blank lines should just return 0, since a blank command doesn't 'crash'
if (!(*line)) {
return 0;
}
int num_commands = 1;
int i; for (i = 0; line[i]; i++) {
if (line[i] == ';') num_commands++;
}
char *commands[num_commands];
for (i = 0; i < num_commands; i++) {
commands[i] = strsep(&line, ";");
}
int retval;
int counter; for (counter = 0; counter < num_commands; counter++) {
if (!(commands[counter][0])) {
retval = 0;
continue;
}
// Get the number of arguments from get_num_args
int num_args = get_num_args(commands[counter]);
// Split the chunks by spaces and put into an array of char pointers of
// size num_args + 1
char *args[num_args + 1];
for (i = 0; i < num_args; i++) {
args[i] = strsep(&commands[counter], " ");
if (!args[i][0]) i--;
}
if (!args[num_args - 1][0]) args[num_args - 1] = NULL;
args[num_args] = NULL;
char *command[num_args];
int j;
int redirected = 0;
// Check for redirection or pipe symbols
for (i = 0; i < num_args; i++) {
if (!strcmp(args[i], ">")) {
for (j = 0; j < i; j++) {
command[j] = args[j];
}
command[i] = NULL;
retval = stdout_to_file_overwrite(command, args[num_args - 1]);
redirected = 1;
} else if (!strcmp(args[i], ">>")) {
for (j = 0; j < i; j++) {
command[j] = args[j];
}
command[i] = NULL;
retval = stdout_to_file_append(command, args[num_args - 1]);
redirected = 1;
} else if (!strcmp(args[i], "2>")) {
for (j = 0; j < i; j++) {
command[j] = args[j];
}
command[i] = NULL;
retval = stderr_to_file_overwrite(command, args[num_args - 1]);
redirected = 1;
} else if (!strcmp(args[i], "2>>")) {
for (j = 0; j < i; j++) {
command[j] = args[j];
}
command[i] = NULL;
retval = stderr_to_file_append(command, args[num_args - 1]);
redirected = 1;
} else if (!strcmp(args[i], "2>1")) {
for (j = 0; j < i; j++) {
command[j] = args[j];
}
command[i] = NULL;
retval = stderr_to_stdout(command);
redirected = 1;
} else if (!strcmp(args[i], "&>")) {
retval = stdout_to_stderr(command);
redirected = 1;
} else if (!strcmp(args[i], "<")) {
for (j = 0; j < i; j++){
command[j] = args[j];
}
command[i] = NULL;
retval = file_to_stdin(command, args[num_args - 1]);
redirected = 1;
} else if (!strcmp(args[i], "|")) {
char *command1[i + 1];
char *command2[num_args - i + 1];
for (j = 0; j < i; j++){
command1[j] = args[j];
}
command1[i] = NULL;
for (j = i + 1; j <= num_args; j++){
command2[j - i - 1] = args[j];
}
retval = pipe_of_wish(command1, command2);
redirected = 1;
}
}
if (!redirected) retval = execute(args[0], args);
}
return retval;
}
|
Java
|
UTF-8
| 470 | 1.679688 | 2 |
[] |
no_license
|
package com.gec.service;
import java.util.List;
import com.gec.bean.Document;
import com.gec.util.PageModel;
public interface DocumentService {
//分页查询
public PageModel<Document> findByPage(int pageIndex,Document entity);
public Document findById(Integer id);
public boolean save(Document entity);
public boolean update(Document entity);
//查询所有
public List<Document> findAll();
public boolean del(String[] id);
}
|
Markdown
|
UTF-8
| 2,972 | 3.640625 | 4 |
[] |
no_license
|
# CSS 也能修改图片颜色?
图标是前端页面中不可避免要用到的,常用图标的形式也有多种:图片、字体、SVG。目前越来越多地会使用 SVG 和字体图标,其中一个原因就是字体和 SVG 都能动态改变颜色,而图片却不能,因为很多情况下我们需要对同一个图标进行不同的颜色显示。
那么,图片究竟可不可以改变颜色呢?通常我们可以在 PS 中修改一个图片的颜色,但是在 HTML 中还真没听说过。
这可能是咱们孤陋寡闻了,还真就有这样一个神奇的 CSS 属性。我们看下面的代码
```html
<div class="box">
<span class="icon"></span>
</div>
```
应用下面的 CSS
```css
.icon {
width: 100px;
height: 100px;
display: inline-block;
background-image: url('./github.png');
}
```

实际上通过 `background-image` 指定的图像不仅可以是一张图片,还可以是渐变色 `linear-gradient`,而且是可以指定多个图像的,所有图像以 Z 方向堆叠,并且先指定的图像会在后指定的图像上面。
所以如果我们再给背景图像再加上一个渐变色(这里用两个相同的颜色模拟了纯红色)
```css
background-image: url('./github.png'), linear-gradient(#f00, #f00);
```
结果并没有什么变化,因为这里第一个设置的是图片,所以我们只看到图片,渐变色被遮盖了。
到此就该祭出我们的大杀器了:`background-blend-mode` ,这是用来定义背景图片的混合方式,于是我们加上该样式
```css
background-image: url('./github.png'), linear-gradient(#f00, #f00);
background-blend-mode: lighten;
```
你会看到下面的结果

当然 `background-blend-mode` 还有其它的取值,可以挨着试试看效果。
上面我们用渐变色模拟了纯色,如果是真的渐变色呢?
```css
.icon {
background-image: url('./github.png'), linear-gradient(#f00, #0f0);
background-blend-mode: lighten;
}
```
这里我们用了红+绿的渐变色,看看效果

有同学要说了,真正的图标颜色会受到上层容器的影响,也就是设置 `.box` 的 `color` 就会让图标变成同样的颜色,其实和 SVG 的原理一样,使用 `currentColor` 即可
```css
.icon {
background-image: url('./github.png');
background-color: currentColor;
background-blend-mode: lighten;
}
```
然后我们设置一下 box 的颜色
```css
.box {
color: blue
}
```

可以看到图标变成了蓝色, F12 动态修改 box 的 color 你会发现图标的颜色也在跟着变。
注意,如果图片是背景透明的 PNG,`background-blend-mode` 是无能为力的,所以需要保证图片为背景白色且非透明。此外,该 CSS 属性除了 IE ,其它主流浏览器均支持。
### demo
[demo](https://codepen.io/huzhengen/pen/ZqNEob)
|
Java
|
UTF-8
| 1,349 | 2.109375 | 2 |
[] |
no_license
|
/**
* Copyright © 2017鼎泰智源科技有限公司. All rights reserved.
*
* @Title: Field.java
* @Prject: InterfaceWeb
* @Package: com.fahai.cc.interf.mysql.entity
* @Description: TODO
* @author: Aaron.ye
* @date: 2017年6月16日 下午1:23:47
* @version: V1.0
*/
package com.fahai.cc.interf.mysql.entity;
import java.io.Serializable;
/**
* @ClassName: Field
* @Description: TODO
* @author: Aaron.ye
* @date: 2017年6月16日 下午1:23:47
*/
public class Field implements Serializable{
/**
* @fieldName: serialVersionUID
* @fieldType: long
* @Description: TODO
*/
private static final long serialVersionUID = 1133660529105178139L;
private String fieldCode;
private String fieldName;
private String fieldType;
private String dimensionCode;
public String getFieldCode() {
return fieldCode;
}
public void setFieldCode(String fieldCode) {
this.fieldCode = fieldCode;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldType() {
return fieldType;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
}
public String getDimensionCode() {
return dimensionCode;
}
public void setDimensionCode(String dimensionCode) {
this.dimensionCode = dimensionCode;
}
}
|
Rust
|
UTF-8
| 7,670 | 3.40625 | 3 |
[
"MIT"
] |
permissive
|
use std::{
collections::HashMap,
fmt,
fs::{self, File, OpenOptions},
io::{BufRead, BufReader, Write},
net::IpAddr,
path::{Path, PathBuf},
result,
};
pub type Result<T> = result::Result<T, Box<dyn std::error::Error>>;
/// A custom error struct for this crate.
#[derive(Debug, Clone)]
pub struct Error(String);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
/// `HostsBuilder` manages a section of /etc/hosts file that contains a list of IP to hostname
/// mappings. A hosts file can have multiple sections that are distinguished by tag names.
///
/// # Examples
///
/// ```no_run
/// use hostsfile::{HostsBuilder, Result};
/// # fn main() -> Result<()> {
/// let mut hosts = HostsBuilder::new("dns");
/// hosts.add_hostname("8.8.8.8".parse().unwrap(), "google-dns1");
/// hosts.add_hostname("8.8.4.4".parse().unwrap(), "google-dns2");
/// hosts.write_to("/tmp/hosts")?;
/// # Ok(())
/// # }
/// ```
///
/// `/tmp/hosts` will have a section:
///
/// ```text
/// # DO NOT EDIT dns BEGIN
/// 8.8.8.8 google-dns1
/// 8.8.4.4 google-dns2
/// # DO NOT EDIT dns END
/// ```
///
/// Another run of `HostsBuilder` with the same tag name overrides the section.
///
/// ```no_run
/// use hostsfile::{HostsBuilder, Result};
/// # fn main() -> Result<()> {
/// let mut hosts = HostsBuilder::new("dns");
/// hosts.add_hostnames("1.1.1.1".parse().unwrap(), &["cloudflare-dns", "apnic-dns"]);
/// hosts.write_to("/tmp/hosts")?;
/// # Ok(())
/// # }
/// ```
///
/// `/tmp/hosts` will have a section:
///
/// ```text
/// # DO NOT EDIT dns BEGIN
/// 1.1.1.1 cloudflare-dns apnic-dns
/// # DO NOT EDIT dns END
/// ```
///
/// On Windows the host file format is slightly different in this case:
/// ```text
/// # DO NOT EDIT dns BEGIN
/// 1.1.1.1 cloudflare-dns
/// 1.1.1.1 apnic-dns
/// # DO NOT EDIT dns END
/// ```
pub struct HostsBuilder {
tag: String,
hostname_map: HashMap<IpAddr, Vec<String>>,
}
impl HostsBuilder {
/// Creates a new `HostsBuilder` with the given tag name. It corresponds to a section in the
/// hosts file containing a list of IP to hostname mappings.
pub fn new<S: Into<String>>(tag: S) -> Self {
Self {
tag: tag.into(),
hostname_map: HashMap::new(),
}
}
/// Adds a mapping of `ip` to `hostname`. If there hostnames associated with the IP already,
/// the hostname will be appended to the list.
pub fn add_hostname<S: ToString>(&mut self, ip: IpAddr, hostname: S) {
let hostnames_dest = self.hostname_map.entry(ip).or_insert_with(Vec::new);
hostnames_dest.push(hostname.to_string());
}
/// Adds a mapping of `ip` to a list of `hostname`s. If there hostnames associated with the IP
/// already, the new hostnames will be appended to the list.
pub fn add_hostnames<I: IntoIterator<Item = impl ToString>>(
&mut self,
ip: IpAddr,
hostnames: I,
) {
let hostnames_dest = self.hostname_map.entry(ip).or_insert_with(Vec::new);
for hostname in hostnames.into_iter() {
hostnames_dest.push(hostname.to_string());
}
}
/// Inserts a new section to the system's default hosts file. If there is a section with the
/// same tag name already, it will be replaced with the new list instead.
pub fn write(&self) -> Result<()> {
let hosts_file = if cfg!(unix) {
PathBuf::from("/etc/hosts")
} else if cfg!(windows) {
PathBuf::from(
// according to https://support.microsoft.com/en-us/topic/how-to-reset-the-hosts-file-back-to-the-default-c2a43f9d-e176-c6f3-e4ef-3500277a6dae
// the location depends on the environment variable %WinDir%.
format!(
"{}\\System32\\Drivers\\Etc\\hosts",
std::env::var("WinDir")?
),
)
} else {
return Err(Box::new(Error("unsupported operating system.".to_owned())));
};
if !hosts_file.exists() {
return Err(Box::new(Error(format!(
"hosts file {:?} missing",
&hosts_file
))));
}
self.write_to(&hosts_file)
}
/// Inserts a new section to the specified hosts file. If there is a section with the same tag
/// name already, it will be replaced with the new list instead.
///
/// On Windows, the format of one hostname per line will be used, all other systems will use
/// the same format as Unix and Unix-like systems (i.e. allow multiple hostnames per line).
pub fn write_to<P: AsRef<Path>>(&self, hosts_path: P) -> Result<()> {
let hosts_path = hosts_path.as_ref();
let begin_marker = format!("# DO NOT EDIT {} BEGIN", &self.tag);
let end_marker = format!("# DO NOT EDIT {} END", &self.tag);
let hosts_file = OpenOptions::new()
.create(true)
.read(true)
.write(true)
.open(hosts_path)?;
let mut lines = BufReader::new(hosts_file)
.lines()
.map(|line| line.unwrap())
.collect::<Vec<_>>();
let begin = lines.iter().position(|line| line.trim() == begin_marker);
let end = lines.iter().position(|line| line.trim() == end_marker);
let insert = match (begin, end) {
(Some(begin), Some(end)) => {
lines.drain(begin..end + 1);
begin
},
(None, None) => {
// Insert a blank line before a new section.
if let Some(last_line) = lines.iter().last() {
if !last_line.is_empty() {
lines.push("".to_string());
}
}
lines.len()
},
_ => {
return Err(Box::new(Error(format!(
"start or end marker missing in {:?}",
&hosts_path
))));
},
};
// The tempfile should be in the same filesystem as the hosts file.
let hosts_dir = hosts_path
.parent()
.expect("hosts file must be an absolute file path");
let temp_dir = tempfile::Builder::new().tempdir_in(hosts_dir)?;
let temp_path = temp_dir.path().join("hosts");
// Copy the existing hosts file to preserve permissions.
fs::copy(&hosts_path, &temp_path)?;
let mut file = File::create(&temp_path)?;
for line in &lines[..insert] {
writeln!(&mut file, "{}", line)?;
}
if !self.hostname_map.is_empty() {
writeln!(&mut file, "{}", begin_marker)?;
for (ip, hostnames) in &self.hostname_map {
if cfg!(windows) {
// windows only allows one hostname per line
for hostname in hostnames {
writeln!(&mut file, "{} {}", ip, hostname)?;
}
} else {
// assume the same format as Unix
writeln!(&mut file, "{} {}", ip, hostnames.join(" "))?;
}
}
writeln!(&mut file, "{}", end_marker)?;
}
for line in &lines[insert..] {
writeln!(&mut file, "{}", line)?;
}
// Move the file atomically to avoid a partial state.
fs::rename(&temp_path, &hosts_path)?;
Ok(())
}
}
|
Python
|
UTF-8
| 13,448 | 3.796875 | 4 |
[] |
no_license
|
# import os
# PATH = r"D:\GIT\python\setting"
# FILE_NAME = 'damages.txt'
#
# full_path = os.path.join(PATH, FILE_NAME)
#
#
# with open(full_path, 'r', encoding='UTF-8') as file:
# for el in file:
# print(el)
# Задание - 1
# Создайте функцию, принимающую на вход Имя, возраст и город проживания человека
# Функция должна возвращать строку вида "Василий, 21 год(а), проживает в городе Москва"
# def about_user (name, age, city):
# Функция принимает имя, возраст и город пользователя и возвращает форматированную строку с этими данными
# result = '{}, {} год(а), проживанет в городе {}'.format(name, age, city)
# return result
#
# name = input('Привет! Укакжите свое имя, пожалуйста: ')
# age = input('Укажите Ваш возраст: ')
# city = input('Укажите город Вашего проживания: ')
#
# result = about_user(name, age, city)
# print(result)
# Задание - 2
# Создайте функцию, принимающую на вход 3 числа, и возвращающую наибольшее из них
# def max_number(a, b, c):
## Функция принимает 3 числа и возвращает самое большое из них
# num_list = [a,b,c]
# max_num = (max(num_list))
# return max_num
#
# num_1 = int (input('Введите значение первого числа: '))
# num_2 = int (input('Введите значение второго числа: '))
# num_3 = int (input('Введите значение третьего числа: '))
#
# result = max_number(num_1, num_2, num_3)
# print('Максимальное число из введеных вами: {}'.format(result))
# Задание - 3
# Создайте функцию, принимающую неограниченное количество строковых аргументов,
# верните самую длинную строку из полученных аргументов
# def max_str (* arg):
#
# # Функция принмает произвольное число строк, сравнивает их и возвращает самую длянную из них
#
# max_len = max (arg, key = len)
# return max_len
#
#
# arg_1 = input('Введите первыю строку: ')
# arg_2 = input('Введите вторую строку: ')
# arg_3 = input('Введите трутью строку: ')
#
# result = max_str(arg_1, arg_2, arg_3)
# print('Самая дилинная строка это: : {}'.format(result))
################################################################################################
# Задание - 1
# Давайте опишем пару сущностей player и enemy через словарь,
# который будет иметь name - строка полученная от пользователя,
# health - 100, damage - 50.
# Теперь надо создать функцию attack(person, person) функция в качестве аргумента будет
# принимать атакующего и атакуемого, функция должна получить параметр damage атакующего и отнять это количество
# health от атакуемого
# import random
# import time
# import math
#
#
# def player ( **kwargs):
# person = 'Великий {} {} мы приветствуем тебя на нашей битве! Помни, что твой уровень здоровья равен {}%, сила удара {}'.format(kwargs['type_of_warrior'], kwargs['name'], kwargs['health'], kwargs['damage'])
# return person
#
# def attack (health, damage):
# if health > 0:
# armor = random.randrange(0, 2)
# arg_armor = random.randrange (1 , 7)
# if armor ==1:
# health = health - (damage*(arg_armor/10))
# protection = 'Броня смягчила удар.'
# else:
# health -= damage
# protection = 'Удар сквозь броню.'
#
# else:
# health <= 0
#
# return (math.trunc(health),protection)
#
#
#
# type_list = {'1': 'Воин', '2':'Эльф', '3':'Орк'}
# names_of_enemy = {'1': '\'Могучий Слон\'', '2':'\'Меткий Глаз\'', '3':'\'Несокрушимая Стена\''}
# damage_man = random.randrange(10,30)
# damage_elf = random.randrange(5, 40)
# damage_ork = random.randrange(0,50)
# health_full = 100
# health = health_full *2
# health_enemy = health_full
#
# type_of_warrior = input('Выберите кем Вы будете 1 - Воин, 2 - Эльф, 3 - Орк: ')
# name = input('Введите свое имя: ')
#
# if type_of_warrior == '1':
# damage = damage_man
# playman = {'type_of_warrior': 'Воин', 'name': name.title(), 'health': health_full, 'damage': damage}
# elif type_of_warrior == '2':
# damage = damage_elf
# playman = {'type_of_warrior': 'Эльф', 'name': name.title(), 'health': health_full, 'damage': damage}
# elif type_of_warrior == '3':
# damage = damage_ork
# playman = {'type_of_warrior': 'Орк', 'name': name.title(), 'health': health_full, 'damage': damage}
# else:
# print('ЭЭЭЭ СТОП! Вы неверно выбрали расу. До свидания.')
# time.sleep(3)
# exit()
#
#
#
# time.sleep(2)
#
# enemy = str (random.randrange(1,4))
#
# if enemy == '1':
# damage_enemy = damage_man
# elif enemy == '2':
# damage_enemy = damage_elf
# elif enemy == '3':
# damage_enemy = damage_ork
#
#
# print('Ваш соперник {} {}.'.format(type_list[enemy], names_of_enemy[enemy]))
# time.sleep(3)
#
# print(player(**playman))
#
# time.sleep(2)
# while health > 0:
# if health_enemy > 0:
# kick = input('Нанести удар? y/n: ')
# if kick == 'y':
# health_enemy, protection = attack(health_enemy, damage)
# print('Вы нанесли урон, уровень здоровья вашего противника равен: {}%. {}'.format(health_enemy, protection))
# time.sleep(3)
# health, protection = attack(health, damage_enemy)
# print('Вам нанесли урон, ваш уровень здоровья равен: {}%. {}'.format(health, protection))
# else:
# print('Слабак, сбежал с поля боя')
# time.sleep(3)
# exit()
# else:
# print('ТАДА!!!! ПОБЕДА!! {} {} вы победили в честной схватке! У Вас осталое еще {}HP.'.format(type_list[enemy], names_of_enemy[enemy],health))
# any = input('Пресс эни кей')
# exit()
#
# else:
# print('THE END. {} {} вы пали геройской смертью'.format(type_list[type_of_warrior], name))
#
# any = input('Пресс эни кей')
# exit()
# Задание - 2
# Давайте усложним предыдущее задание, измените сущности, добавив новый параметр - armor = 0.7
# Теперь надо добавить функцию, которая будет вычислять и возвращать полученный урон по формуле damage / armor
# Следовательно у вас должно быть 2 функции, одна наносит урон, вторая вычисляет урон по отношению к броне.
# Сохраните эти сущности, каждую в свой файл, в качестве названия для файла использовать name, расширение .txt
# Напишите функцию, которая будет считывать файл игрока и его врага, получать оттуда данные, и записывать их в словари,
# после чего происходит запуск игровой сессии, где сущностям поочередно наносится урон,
# пока у одного из них health не станет меньше или равен 0.
# После чего на экран должно быть выведено имя победителя, и количество оставшихся единиц здоровья.
import random
import time
import math
def player ( **kwargs):
person = 'Великий {} {} мы приветствуем тебя на нашей битве! Помни, что твой уровень здоровья равен {}%, сила удара {}'.format(kwargs['type_of_warrior'], kwargs['name'], kwargs['health'], kwargs['damage'])
return person
def attack (health, damage):
if health > 0:
armor = random.randrange(0, 2)
arg_armor = random.randrange (1 , 7)
if armor ==1:
health = health - (damage*(arg_armor/10))
protection = 'Броня смягчила удар.'
else:
health -= damage
protection = 'Удар сквозь броню.'
else:
health <= 0
return (math.trunc(health),protection)
type_list = {'1': 'Воин', '2':'Эльф', '3':'Орк'}
names_of_enemy = {'1': '\'Могучий Слон\'', '2':'\'Меткий Глаз\'', '3':'\'Несокрушимая Стена\''}
damage_man = random.randrange(10,30)
damage_elf = random.randrange(5, 40)
damage_ork = random.randrange(0,50)
health_full = 100
health = health_full *2
health_enemy = health_full
type_of_warrior = input('Выберите кем Вы будете 1 - Воин, 2 - Эльф, 3 - Орк: ')
name = input('Введите свое имя: ')
if type_of_warrior == '1':
damage = damage_man
playman = {'type_of_warrior': 'Воин', 'name': name.title(), 'health': health_full, 'damage': damage}
elif type_of_warrior == '2':
damage = damage_elf
playman = {'type_of_warrior': 'Эльф', 'name': name.title(), 'health': health_full, 'damage': damage}
elif type_of_warrior == '3':
damage = damage_ork
playman = {'type_of_warrior': 'Орк', 'name': name.title(), 'health': health_full, 'damage': damage}
else:
print('ЭЭЭЭ СТОП! Вы неверно выбрали расу. До свидания.')
time.sleep(3)
exit()
time.sleep(2)
enemy = str (random.randrange(1,4))
if enemy == '1':
damage_enemy = damage_man
elif enemy == '2':
damage_enemy = damage_elf
elif enemy == '3':
damage_enemy = damage_ork
print('Ваш соперник {} {}.'.format(type_list[enemy], names_of_enemy[enemy]))
time.sleep(3)
print(player(**playman))
time.sleep(2)
while health > 0:
if health_enemy > 0:
kick = input('Нанести удар? y/n: ')
if kick == 'y':
health_enemy, protection = attack(health_enemy, damage)
print('Вы нанесли урон, уровень здоровья вашего противника равен: {}%. {}'.format(health_enemy, protection))
time.sleep(3)
health, protection = attack(health, damage_enemy)
print('Вам нанесли урон, ваш уровень здоровья равен: {}%. {}'.format(health, protection))
else:
print('Слабак, сбежал с поля боя')
time.sleep(3)
exit()
else:
print('ТАДА!!!! ПОБЕДА!! {} {} вы победили в честной схватке! У Вас осталое еще {}HP.'.format(type_list[enemy], names_of_enemy[enemy],health))
any = input('Пресс эни кей')
exit()
else:
print('THE END. {} {} вы пали геройской смертью'.format(type_list[type_of_warrior], name))
any = input('Пресс эни кей')
exit()
############################################################################################
# Задание - 1
# Вам даны 2 списка одинаковой длины, в первом списке имена людей, во втором зарплаты,
# вам необходимо получить на выходе словарь, где ключ - имя, значение - зарплата.
# Есть условие, не отображать людей получающих более зарплату 500000
# Запишите результаты в файл salary.txt так, чтобы на каждой строке было 2 столбца,
# столбцы разделяются пробелом, тире, пробелом. в первом имя, во втором зарплата, например: Vasya - 5000
# После чего прочитайте файл, выведите построчно имя и зарплату - 13% (налоги ведь),
# где имя должно быть полностью в верхнем регистре!
# Подумайте вспоминая урок, как это можно сделать максимально кратко, используя возможности языка Python.
names = ['Vasya', 'Anton', 'Oleg', 'Sergey', 'Alexandr', 'Andrey']
salary = [10000, 15000, 710000, 18000, 13500, 1000000]
|
Java
|
UTF-8
| 286 | 2.0625 | 2 |
[] |
no_license
|
package rube.simple;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
@MessagingGateway
public interface EchoGateway {
@Gateway(requestChannel = "requestChannel")
String echo(String message);
}
|
C#
|
UTF-8
| 392 | 2.9375 | 3 |
[] |
no_license
|
using System;
using System.Threading;
namespace DemoApplication
{
class Program
{
static void Main(string[] args) {
Console.WriteLine("Введите ваше имя: ");
string name = Console.ReadLine();
Thread.Sleep(5000);
Console.WriteLine("Привет " + name + "!");
Console.ReadLine();
}
}
}
|
Ruby
|
UTF-8
| 518 | 3.484375 | 3 |
[] |
no_license
|
class Bitmap
DEFAULT_COLOR = "0"
attr_reader :image
def initialize(x:, y:)
@x, @y = x, y
clear
end
def show
puts @image.map { |line| line << "\n" }.join
end
def clear
@image = Array.new(@y) { Array.new(@x, DEFAULT_COLOR) }
end
def draw_colour(x:, y:, colour:)
x, y = normalize_coordinates(x: x, y: y).values_at(:x, :y)
image[x][y] = colour
end
private
def normalize_coordinates(x:, y:)
raise 'no' unless @x >= x or @y >= y
{ x: x - 1, y: y - 1 }
end
end
|
TypeScript
|
UTF-8
| 2,843 | 2.890625 | 3 |
[] |
no_license
|
import * as ts from "typescript";
import { fixExpressionNode } from "./ExpressionNode";
import { ConvertState } from "./ConvertState";
import { addComments } from "./Utils";
export function removeThisKeyword(block: ts.Block, text: string, context: ts.TransformationContext) {
function removeThis(node: ts.Node) {
node = ts.visitEachChild(node, removeThis, context);
if (ts.isPropertyAccessExpression(node))
if (node.expression.kind === ts.SyntaxKind.ThisKeyword) {
return addComments(text, node.name, node.name);
}
return node;
}
return ts.visitEachChild(block, removeThis, context);
}
function fixExpressionNodes(block: ts.Block, context: ts.TransformationContext, info: ConvertState) {
function visit(node: ts.Node) {
node = ts.visitEachChild(node, visit, context);
if (ts.isExpressionStatement(node)) {
return fixExpressionNode(node, info);
}
return node;
}
// Handle transforms and replacement
return ts.visitEachChild(block, visit, context);
}
export function fixBlockInnards(block: ts.Block, context: ts.TransformationContext, info: ConvertState) {
// info.outputTextCount = 0;
// Handle transforms and replacement
block = fixExpressionNodes(block, context, info);
// Remove this on rest
block = removeThisKeyword(block, info.sourceFile.text, context);
// console.log('OutputText: ' + info.outputTextCount);
// Add "let outputText = '';" to that start of the block
// if (info.outputTextCount) {
// block = addComments(
// info.sourceFile.text,
// block,
// ts.createBlock(
// [
// createOutputTextStatement(),
// ...block.statements,
// createScreenReturn()
// ],
// true
// )
// );
// }
return block;
}
// Creates "let outputText = '';" Statement node
// function createOutputTextStatement() {
// return ts.createVariableStatement(
// undefined,
// ts.createVariableDeclarationList(
// [
// ts.createVariableDeclaration(
// ts.createIdentifier('outputText'),
// undefined,
// ts.createStringLiteral('')
// )
// ],
// ts.NodeFlags.Let
// )
// );
// }
// function createScreenReturn() {
// return ts.createReturn(
// ts.createObjectLiteral(
// [
// ts.createPropertyAssignment(
// ts.createIdentifier('text'),
// ts.createIdentifier('outputText')
// )
// ],
// false
// )
// );
// }
|
Python
|
UTF-8
| 5,298 | 2.625 | 3 |
[] |
no_license
|
import serial
import time
import threading
class Cabinet:
'Faxitron cabinet communications class'
def SerialRead(self):
while (self.stopThread == False):
while self.ser.inWaiting() > 0:
self.tempBuff += self.ser.read(1)
if self.tempBuff != '':
self.ser.flushInput()
#print ">>" + self.tempBuff
if(self.tempBuff == '\x1BTMSS0000800008\x0D'):
print("Cabinet Door Open!")
elif(self.tempBuff == '\x1BTMSS0000000000\x0D'):
print("Cabinet Door Closed!")
elif(self.tempBuff == '\x1B\x06\x0D'):
#print("Ack Received!")
self.ackRecieved = True
else:
self.readBuff = self.tempBuff
self.tempBuff = ''
self.readBuff = ''
def __init__(self, portNum):
self.ackRecieved = False
self.stopThread = False
self.ser = serial.Serial()
self.ser.port = portNum
self.ser.baudrate = 9600
self.ser.bytesize = serial.EIGHTBITS
self.ser.parity = serial.PARITY_NONE
self.ser.stopbits = serial.STOPBITS_ONE
self.ser.timeout = 1
self.ser.xonxoff = False
self.ser.rtscts = False
self.ser.dsrdtr = False
self.ser.writeTimeout = 2
self.readBuff = ''
self.tempBuff = ''
try:
self.ser.open()
except e:
print ("error open serial port: " + str(e))
exit()
t = threading.Thread(target=self.SerialRead)
t.start()
def __del__(self):
self.stopThread = True
if self.ser.isOpen():
self.ser.close()
def close(self):
self.stopThread = True
self.ser.close()
def SendCommand(self,command):
counter = 0
ackRecieved = False
fullCommand = '\x1B' + command + '\x0D'
if self.ser.isOpen():
self.ser.write(fullCommand)
time.sleep(0.1)
#self.readBuff = ''
else:
print ("cannot open serial port ")
def Configure(self,kV,mS):
counter = 0
self.ackRecieved = False
_kV = "%.2f" % kV
mA = 1
_mA = "%.1f" % mA
command = 'CBM' + str(_kV).zfill(6)+str(_mA).zfill(6)+str(mS).zfill(6)
self.SendCommand(command)
while(counter < 5 and self.ackRecieved == False):
time.sleep(0.1)
counter += 1
if self.ackRecieved == True:
return True
else:
return False
def GetConfig(self):
command = 'RB'
self.SendCommand(command)
time.sleep(0.1)
if(self.readBuff != ''):
kv = float(self.readBuff[7:13])
#print("KV: %.2f KV" % kv)
mA = float(self.readBuff[13:19])
#print("mA: %.1f mA" % mA)
mS = int(self.readBuff[19:-1])
#print("Duration: %d mS" % mS)
return (kv,mA,mS)
def SetKV(self, kV):
mS = 0
command = 'RB'
self.SendCommand(command)
time.sleep(0.1)
if(self.readBuff != ''):
mS = int(self.readBuff[19:-1])
return self.Configure(kV,mS)
def GetKV(self):
command = 'RK'
self.SendCommand(command)
time.sleep(0.1)
if(self.readBuff != ''):
kv = float(self.readBuff[3:-1])
#print("KV is: %.2f KV" % kv)
return kv
def SetTime(self, mS):
kV = 0
command = 'RB'
self.SendCommand(command)
time.sleep(0.1)
if(self.readBuff != ''):
kV = float(self.readBuff[7:13])
return self.Configure(kV,mS)
def GetTime(self):
command = 'RT'
self.SendCommand(command)
time.sleep(0.1)
if(self.readBuff != ''):
mS = int(self.readBuff[3:-1])
#print("Duration is: %d ms" % mS)
return mS
def FireXRay(self):
counter = 0
self.ackRecieved = False
self.SendCommand('CMSS0006400064')
time.sleep(0.1)
self.SendCommand('CMSS0001600000')
time.sleep(0.1)
self.SendCommand('CX1')
time.sleep(0.1)
while(counter < 5 and self.ackRecieved == False):
time.sleep(0.1)
counter += 1
if self.ackRecieved == True:
return True
else:
return False
def WaitXRayOff(self):
counter = 0
print("\nX-Ray off"),
while self.readBuff == '\x1BTDTR1\x0D' and counter <5000:
print("-"),
time.sleep(0.01)
counter +=1
print("")
def WaitXRayOn(self):
counter = 0
print("\nX-Ray on"),
while self.readBuff != '\x1BTDTR1\x0D' and counter <5000:
print("+"),
time.sleep(0.001)
counter += 1
print(counter)
|
PHP
|
UTF-8
| 925 | 2.640625 | 3 |
[] |
no_license
|
<?php
#U ovom kontroleru handlamo sve staticne stranice nase aplikacije
#namespace pomaze da kontroleru kazemo da ostane u ovom folderu!
namespace App\Http\Controllers;
use App\Category;
use App\Post;
class PagesController extends Controller
{
#kad pravimo metode u kotrolerima nazivamo ih vrstazahtjevaImeMetode
#svaka funkcija prima neke parametre
#komunicira s modelom
#prima podatke od modela,a obraduje ih i predaje view
public function getIndex()
{
$posts = Post::orderBy('created_at','desc')->paginate(2);
$categories = Category::all();
return view('pages.welcome')->withPosts($posts)->withCategories($categories);
}
public function getAbout()
{
$dataToPass=[];
$dataToPass['authors'] = "Filip Šekerija i Jozo Spajić";
$dataToPass['git']= "https://github.com/jspajic/blog";
return view('pages.about')->withData($dataToPass);
}
}
|
Java
|
UTF-8
| 1,874 | 2.015625 | 2 |
[
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"Apache-2.0",
"MIT",
"BSD-2-Clause"
] |
permissive
|
/*
This file is part of Intake24.
© Crown copyright, 2012, 2013, 2014.
This software is licensed under the Open Government Licence 3.0:
http://www.nationalarchives.gov.uk/doc/open-government-licence/
*/
package uk.ac.ncl.openlab.intake24.client.survey.rules;
import org.pcollections.PSet;
import org.pcollections.PVector;
import org.workcraft.gwt.shared.client.Function1;
import org.workcraft.gwt.shared.client.Option;
import org.workcraft.gwt.shared.client.Pair;
import uk.ac.ncl.openlab.intake24.client.survey.*;
import uk.ac.ncl.openlab.intake24.client.survey.prompts.AssociatedFoodPrompt;
import uk.ac.ncl.openlab.intake24.client.survey.prompts.AutomaticAssociatedFoodsPrompt;
import uk.ac.ncl.openlab.intake24.client.survey.prompts.MealOperation;
import java.util.logging.Logger;
import static org.workcraft.gwt.shared.client.CollectionUtils.exists;
import static org.workcraft.gwt.shared.client.CollectionUtils.indexOf;
public class ShowAutomaticAssociatedFoodsPrompt implements PromptRule<Meal, MealOperation> {
private final Logger log = Logger.getLogger("ShowAutomaticAssociatedFoodPrompt");
private final String locale;
public ShowAutomaticAssociatedFoodsPrompt(final String locale) {
this.locale = locale;
}
@Override
public Option<Prompt<Meal, MealOperation>> apply(final Meal meal, SelectionMode selectionType, PSet<String> surveyFlag) {
if (!meal.encodingComplete() || meal.associatedFoodsComplete())
return Option.none();
else
return Option.<Prompt<Meal, MealOperation>>some(new AutomaticAssociatedFoodsPrompt(locale, meal));
}
public static WithPriority<PromptRule<Meal, MealOperation>> withPriority(int priority, String locale) {
return new WithPriority<PromptRule<Meal, MealOperation>>(new ShowAutomaticAssociatedFoodsPrompt(locale), priority);
}
}
|
Python
|
UTF-8
| 227 | 3.625 | 4 |
[] |
no_license
|
arr = [5,7,8,9,1,2,6,3,4]
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1],arr[j]
for i in range(len(arr)):
print(arr[i],end = " ")
|
C#
|
UTF-8
| 1,309 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
namespace dotgo.io
{
/// <summary>
/// ReaderAt is the interface that wraps the basic ReadAt method.
/// ReadAt reads len(p) bytes into p starting at offset off in the underlying input source.
/// It returns the number of bytes read (0 <= n <= len(p)) and any error encountered.
/// When ReadAt returns n<len(p), it returns a non-nil error explaining why more bytes were not returned.
/// In this respect, ReadAt is stricter than Read.
/// Even if ReadAt returns n<len(p), it may use all of p as scratch space during the call.
/// If some data is available but not len(p) bytes, ReadAt blocks until either all the data is available or an error occurs.
/// In this respect ReadAt is different from Read.
/// If the n = len(p) bytes returned by ReadAt are at the end of the input source,
/// ReadAt may return either err == EOF or err == nil.
/// If ReadAt is reading from an input source with a seek offset, ReadAt should not affect nor
/// be affected by the underlying seek offset.
/// Clients of ReadAt can execute parallel ReadAt calls on the same input source.
/// Implementations must not retain p.
/// </summary>
public interface ReaderAt
{
(int n, error err) ReadAt(slice<byte> p, long offset);
}
}
|
Markdown
|
UTF-8
| 2,117 | 3.03125 | 3 |
[] |
no_license
|
# Code Portfolio
## I590 - Applied Data Science
### April 15, 2019
This folder is an organized collection of code snippets and additional comments that would be useful as a data scientist. The expectation is that while this is start as part of the Applied Data Science course, it will continue to grow and evolve over time. The Code Portfolio is organized as follows:
### Folder Structure:
CodePortfolio is a folder within the DataScience folder. The DataScience folder will contain both CodePortfolio as well as Projects that are being designed and implemented over time. The intent is to share all of the content with the broader data science community.
DataScience (Main Folder)
- CodePortfolio
- Projects
### File Naming:
The files within CodePortfolio folder are structured as follows:
<NN>_<FocusArea>_using_<Toolset>.<ext>
- NN - Numeric Sequence of the files. This is used primarily for organization. This convention forces certain files to be ahead of others. For example, we would like to understand import before wranging etc.
- FocusArea - This name represents a specific focus area of the data science lifecycle. We start with 4 basic steps import, wrangling, visualization and analysis. More focus areas are expected to be added over time.
- Toolset - This indicates whether we use specific toolset to highlight the focus areas such as R, Python etc. With so many tools available in the community, it is important to ground ourselves and understand how to implement across ultiple toolset.
- ext - This represents the file extension, so we understand how to open and read the CodePortfolio files. Examples include, ipynb (Jupyter Python Notebooks), rmd (R Markdown), r (R Scripts), py (Python source file), html and pdf for viewing static content.
### github
All of the files including data, diagrams and configurations will be made available in github and as public. This will enable interested users to download the content and view / execute code to get a better fell of the content and context.
This folder is expected to grow over time as more useful tips and tricks are learned.
|
C++
|
UTF-8
| 2,276 | 3.421875 | 3 |
[] |
no_license
|
#include "ClapTrap.hpp"
ClapTrap::ClapTrap(std::string const &name):
hitPoints(100), maxHitPoints(100), energyPoints(100),
maxEnergyPoints(100), level(1), name(name),
meleeAttackDamage(100), rangedAttackDamage(100),
armorDamageReduction(100)
{
std::cout << "ClapTrap " << this->name << " created." << std::endl;
}
ClapTrap::ClapTrap(ClapTrap const &other)
{
ClapTrap::copy(other);
std::cout << "ClapTrap " << this->name << " created." << std::endl;
}
ClapTrap &ClapTrap::operator=(ClapTrap const &other)
{
ClapTrap::copy(other);
return (*this);
}
void ClapTrap::copy(ClapTrap const &other)
{
this->hitPoints = other.hitPoints;
this->maxHitPoints = other.maxHitPoints;
this->energyPoints = other.energyPoints;
this->maxEnergyPoints = other.maxEnergyPoints;
this->level = other.level;
this->name = other.name;
this->meleeAttackDamage = other.meleeAttackDamage;
this->rangedAttackDamage = other.rangedAttackDamage;
this->armorDamageReduction = other.armorDamageReduction;
}
ClapTrap::~ClapTrap()
{
std::cout << "ClapTrap " << name << " is now dead." << std::endl;
}
int ClapTrap::rangedAttack(std::string const &target)
{
std::cout << this->name << " attacked " << target << " at range, causing "
<< this->rangedAttackDamage << " of damage!" << std::endl;
return (this->rangedAttackDamage);
}
int ClapTrap::meleeAttack(std::string const &target)
{
std::cout << this->name << " attacked " << target << " at melee, causing "
<< this->meleeAttackDamage << " of damage!" << std::endl;
return (this->meleeAttackDamage);
}
int ClapTrap::takeDamage(unsigned int amount)
{
int damage = amount - this->armorDamageReduction;
if (damage > 0)
{
if (damage > this->hitPoints)
{
damage = this->hitPoints;
this->hitPoints = 0;
}
else
this->hitPoints -= damage;
std::cout << this->name << " took " << damage << " of damage!" << std::endl;
}
return (damage);
}
int ClapTrap::beRepaired(unsigned int amount)
{
int heal = this->hitPoints + amount;
if (heal > this->maxHitPoints)
{
heal = this->maxHitPoints - this->hitPoints;
this->hitPoints = this->maxHitPoints;
}
else
{
heal = amount;
this->hitPoints += amount;
}
std::cout << this->name << " gained back " << heal << " hit points!" << std::endl;
return (heal);
}
|
JavaScript
|
UTF-8
| 1,844 | 4.15625 | 4 |
[] |
no_license
|
/*
You are given a text, which contains different english letters and punctuation symbols. You should find the most frequent letter in the text. The letter returned must be in lower case.
While checking for the most wanted letter, casing does not matter, so for the purpose of your search, "A" == "a". Make sure you do not count punctuation symbols, digits and whitespaces, only letters.
If you have two or more letters with the same frequency, then return the letter which comes first in the latin alphabet. For example -- "one" contains "o", "n", "e" only once for each, thus we choose "e".
Input: A text for analysis as a string.
Output: The most frequent letter in lower case as a string.
*/
function mostWanted(data) {
var x = data.toLowerCase()
var a = /\w/g
var y = x.match(a)
var xx = 0
var z = []
var z1 = []
for(var i = 0; i < y.length; i++){
var v = 0
for(var n = 0; n < y.length; n++){
if(y[i] === y[n]){
v++
}
}
z.push(v)
}
var a = Math.max(...z)
for(var o = 0; o < z.length; o++){
if(a === z[o]){
xx++
}
}
if(a < xx || a === 1){
var p = y
for(var o1 = 0; o1 < z.length; o1++){
if(a > z[o1]){
p = p.filter(function(mm){
return mm !== y[o1]
})
}
}
for(var t = 97; t <= 122; t++){
var v1 = 0
for(var k = 0; k < p.length; k++){
if(String.fromCharCode(t) === p[k]){
v1 = t
}
}if(v1 !== 0){
z1.push(v1)
}
}
return String.fromCharCode(z1[0])
}else{
var b = z.indexOf(a)
return y[b]
}
}
console.log(mostWanted("But"))
|
Java
|
UTF-8
| 902 | 2.125 | 2 |
[] |
no_license
|
package hsl.pojo.command.ad;
import hg.common.component.BaseCommand;
/**
*
* @类功能说明:修改广告状态(显示-隐藏)Command
* @类修改者:
* @修改日期:
* @修改说明:
* @公司名称:浙江汇购科技有限公司
* @部门:技术部
* @作者:yuqz
* @创建时间:2014年12月25日下午3:14:57
* @版本:V1.0
*
*/
public class HslUpdateAdStatusCommand extends BaseCommand{
private static final long serialVersionUID = 1L;
/**
* 广告的ID
*/
private String id;
/**
* 按广告优先级和广告位的加载条数,自动维护是否显示状态
*/
private Boolean isShow;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Boolean getIsShow() {
return isShow;
}
public void setIsShow(Boolean isShow) {
this.isShow = isShow;
}
}
|
Markdown
|
UTF-8
| 3,553 | 2.671875 | 3 |
[
"Unlicense"
] |
permissive
|
# Chilean police officer arrested after shooting students at protest
Published at: **2019-11-07T21:33:13+00:00**
Author: **Jonathan Franklin**
Original: [the Guardian](https://www.theguardian.com/world/2019/nov/07/chile-protests-police-arrest-shooting-students)
Other officers have been accused of a beating and sexual abuse as unrest enters third week, with 2,000 injured
A Chilean police major who shot two students during a school protest has been arrested as a wave of political unrest enters a third week and the number of injured in street violence topped 2,000.
Maj Humberto Tapia was arrested by detectives on Thursday and charged with illegally discharging his shotgun inside a public school that had been occupied by students on Tuesday. A call by the beleaguered principal led to a confrontation with students in which Tapia fired into the floor, sending buckshot ricocheting into the legs of students.
The arrest came a day after prosecutors announced that 12 other police were under investigation for allegedly beating a 55-year-old man – and amid growing allegations that officers had raped and sexually abused detained protesters.
At least three soldiers have been charged for shooting protesters while an estimated 4,500 protesters have been arrested, although the vast majority have been released within 24 hours.
What began as a protest over a rise in subway fares has grown into a tsunami of unrest in which hundreds of thousands of Chileans have joined peaceful marches calling for an overhaul of the country’s economic and social model.
Some protests have also turned violent and arson and looting is calculated to have caused as much as $1.5bn in damages.
Chile’s embattled president, Sebastián Piñera, has been accused of a heavy-handed response to the protests: he initially responded by saying the country was “at war” and has since appeared to lurch between conciliation and further crackdown.
On Thursday afternoon, he summoned the heads of the armed forces, supreme court and congress for an urgent meeting of the national security council and called for emergency legislation to increase prison sentences for protesters who wear masks, build barricades or destroy property.
Piñera also called for the creation of a new intelligence effort to increase surveillance of politically active Chileans.
Such efforts are likely to cause concern in a country that only emerged from military rule in 1990 and has since witnessed a string of scandals involving the police. Last week, thousands of documents were dumped on the internet after the national police computer system was hacked, revealing surveillance of students and environmental activists.
Jorge Sharp, a former student protest leader who is now mayor of the port city of Valparaíso, said on Twitter that Piñera had missed the point. “More repression won’t resolve the social injustices,” Sharp said. “It will only provoke more violence.”
In an attempt to defuse the nationwide rebellion that has lowered his approval rating to 9%, Piñera has met with an injured protester and told the country in a broadcast that he too had participated in marches and fought for justice.
But when his health minister, Jaime Mañalich, arrived at Salvador hospital in Santiago on Thursday morning to visit injured civilians, a spontaneous protest led by nurses, doctors and hospital staff led to scenes of chaos.
Mañalich was first trapped inside the hospital, then barely made it into a ministerial car, which, as it left the public hospital, proceeded to run over one of the protesters.
|
SQL
|
UTF-8
| 3,700 | 4.0625 | 4 |
[] |
no_license
|
/* -----------------------------------------------------------------------
Vorlesung Datenbanksysteme
Burkhardt Renz, THM
SQL Teil 10
Views
$Id: sql10.sql 367 2019-03-04 08:39:50Z br $
----------------------------------------------------------------------- */
;
/* Das Ergebnis einer Select-Anweisung ist konzeptionell aufgebaut wie
eine Tabelle, man kann es also als eine _logische_ Tabelle sehen.
Eine Sicht (englisch: View) ist eine solche _logische_ Tabelle, die
durch eine Select-Anweisung definiert wird. Man kann eine Sicht in
Select-Anweisungen wie eine Tabelle verwenden.
In diesem Abschnitt werden wir Views definieren und verwenden (und am Ende
auch wieder löschen).
*/
;
-- Erstellen einer View
-- Beispiel: View für Kontakte des Weinhändlers
;
create view Kontakte as
select Vorname || ' ' || Name as Name, Str as Anschrift1,
PLZ || ' ' || Ort as Anschrift2 from Kunde
union
select Firma as Name, 'PF '|| Postfach as Anschrift1,
PLZ || ' ' || Ort as Anschrift2 from Lieferant;
select * from Kontakte;
/* ergibt:
name | anschrift1 | anschrift2
-------------------+--------------------+-------------------
Thomas Kehl | Weinstr. 3 | 79675 Kaiserstuhl
Bremer Weinkontor | PF 56 | 28195 Bremen
Thomas Kehl | Im Riesling 3 | 68734 Eltville
Karin Riesling | 67, Rue du Château | F-68567 Colmar
Weinimport Lehr | PF 45367 | F-68567 Colmar
*/
;
-- Wir können im Systemkatalog sehen, welche Tabellen und Views es in
-- unserer Datenbank gibt
-- alle Tabellen und Views in unserem Schema 'public'
select table_name
from information_schema.tables
where table_schema = 'public';
/* ergibt:
table_name
------------
lieferant
lieferbez
kunde
auftrag
artikel
auftrpos
kontakte
*/
;
-- nur die Tabellen
select table_name
from information_schema.tables
where table_type = 'BASE TABLE' and table_schema = 'public';
/* ergibt:
table_name
------------
lieferant
lieferbez
kunde
auftrag
artikel
auftrpos
*/
;
-- nur die Views
select table_name
from information_schema.tables
where table_type = 'VIEW' and table_schema = 'public';
/* ergibt:
table_name
------------
kontakte
*/
;
-- geht auch so:
select table_name
from information_schema.views
where table_schema = 'public';
/* Diskussion:
Bedeutung von Views für die logische Datenunabhängigkeit: wenn man
konsequent Views verwendet, kann man die Basistabellen in gewissem Maße
ändern, ohne dass Anwendungen, die die Views verwenden, geändert werden
müssen.
Views sind in der ANSI/SPARC-Architektur Teil der externen Sicht,
ihre Definition übersetzt die externe Sicht in die konzeptuelle Sicht
*/
;
-- Eine View kann man (in der Abfrage) verwenden wie eine Tabelle
-- Beispiel: Abfrage mit Bedingung
;
select *
from Kontakte
where Name like '%Kehl%';
/* ergibt:
name | anschrift1 | anschrift2
-------------+---------------+-------------------
Thomas Kehl | Weinstr. 3 | 79675 Kaiserstuhl
Thomas Kehl | Im Riesling 3 | 68734 Eltville
*/
;
/* Updates sind mit Views im Allgemeinen nicht möglich.
In unserem Beispiel der Kontakte wäre bei einem neuen
Eintrag nicht klar, ob es sich um einen Kunden oder einen
Lieferanten handelt.
Es gibt änderbare Sichten (updatable views), der SQL-Standard
definiert präzise, welche Select-Anweisung für änderbare
Sichten erlaubt sind.
*/
;
-- Wir löschen die View wieder
drop view Kontakte;
-- Noch da?
select table_name
from information_schema.tables
where table_schema = 'public';
select table_name
from information_schema.views
where table_schema = 'public';
|
Python
|
UTF-8
| 485 | 3.046875 | 3 |
[] |
no_license
|
class Solution:
def maxSubArray(self, nums):
max_seq = nums[0]
curr_sum = nums[0]
for num in nums[1:]:
if curr_sum <= 0:
curr_sum = num
else:
curr_sum += num
if curr_sum > max_seq:
max_seq = curr_sum
return max_seq
example = Solution()
nums = [-2,1,-3,4,-1,2,1,-5,4]
print(example.maxSubArray(nums))
|
Java
|
UTF-8
| 1,365 | 2.984375 | 3 |
[] |
no_license
|
/*
* Copyright 2006-2021 (c) Care.com, Inc.
* 77 Fourth Avenue, 5th Floor Waltham, MA, 02451, U.S.A.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Care.com, Inc. ("Confidential Information"). You shall not disclose
* such Confidential Information and shall use it only in accordance with
* the terms of an agreement between you and CZen.
*/
/**
* Created 15/01/21 3:27 PM
*
* @author Kridai
*/
public class SingleNumber3 {
public static void main(String[] args) {
SingleNumber3 sn3 = new SingleNumber3();
Solution s = sn3.new Solution();
System.out.println(s.solve(new int[]{186, 256, 102, 377, 186, 377}).toString());
}
public class Solution {
public int[] solve(int[] A) {
int xor = 0;
for(int i = 0; i< A.length;i ++) {
xor = xor ^ A[i];
}
System.out.println(Integer.toBinaryString(xor));
int bit = 1;
while((bit & xor) == 0) {
bit = bit << 1;
}
System.out.println(Integer.toBinaryString(bit));
int a = 0;
int b = 0;
for(int i = 0; i< A.length;i++) {
if((A[i] & bit) == 0) {
a = a ^ A[i];
}
else {
b = b ^ A[i];
}
}
if( a > b) {
a = a+b;
b = a-b;
a= a-b;
}
return new int[]{a,b};
}
}
}
|
Python
|
UTF-8
| 1,520 | 2.5625 | 3 |
[] |
no_license
|
# import the necessary packages
import os
import cv2
import utils
import time
import argparse
import mask_rcnn
import numpy as np
args = mask_rcnn.get_args(video=True)
labels = mask_rcnn.get_labels(args["classes_path"])
net = mask_rcnn.get_net( args["frozen_inference"], args["inception"])
vs = cv2.VideoCapture(args["video_path"])
writer = None
try:
total = int(vs.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)) if utils.is_cv2() \
else int(vs.get(cv2.CAP_PROP_FRAME_COUNT))
print("[INFO] {} total frames in video".format(total))
except:
print("[INFO] could not determine # of frames in video")
total = -1
while True:
(grabbed, frame) = vs.read()
if not grabbed:
break
start = time.time()
(boxes, masks) = mask_rcnn.process_image(net,frame)
end = time.time()
drawed_image = mask_rcnn.blur_background(
frame,
boxes,
masks,
labels,
float(args["confidence"]),
float(args["threshold"])
)
if writer is None:
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
writer = cv2.VideoWriter(args["output"], fourcc, 30,
(drawed_image.shape[1], drawed_image.shape[0]), True)
if total > 0:
elap = (end - start)
print("[INFO] {:.2f} seconds to predict a unique frame".format(elap))
print("[INFO] estimated total time to finish: {:.2f} minutes".format(
(elap * total)/60))
writer.write(drawed_image)
print("[INFO] cleaning up...")
writer.release()
vs.release()
|
Java
|
UTF-8
| 296 | 1.984375 | 2 |
[
"MIT"
] |
permissive
|
package sushi.bpmn.element;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
/**
* This enum contains the gateway types of an BPMN event-based gateway.
* @author micha
*/
public enum BPMNEventBasedGatewayType {
@Enumerated(EnumType.STRING)
Exclusive, Parallel;
}
|
C#
|
UTF-8
| 4,529 | 3.53125 | 4 |
[
"MIT"
] |
permissive
|
using System;
namespace Classes_e_Obejtos
{
//classes statics não permitem instanciar objetos,e nem construtores/destrutores
class Jogador // a classe pode ser public,abstract , sealed , static
{
public int energia = 100; // propriedades |ou| variaveis
public bool vivo = true; // propriedades |ou| variaveis
public string nome="Jogador" ;
public Jogador(string n) //método construtor
{
energia = 100;
vivo = true;
nome = n;
}
public Jogador(string n,int ener)
{
energia =ener;
vivo = true;
nome = n;
}
public Jogador(string n, int ener,bool vi) //criei tbm varias opções de construtor para a mesma classe
{
energia = ener;
vivo = vi;
nome = n;
}
public void info() //AQUI FOI A AULA DE SOBRECARGA DE CONSTRUTORES
{
Console.WriteLine("nome Jogador:{0}", nome);
Console.WriteLine("energia Jogador:{0}", energia);
Console.WriteLine("Estado Jogador:{0}", vivo);
Console.WriteLine("____________________________________");
}
~Jogador() // método destrutor a diferença e o ~
{
Console.WriteLine("Jogador{0} foi deletado",nome);
}
}
class aula28
{
static void Main() // public , private , protected, abstract , sealed , virtual ,static
{
string nome;
Console.WriteLine("Digite o nome do jogador 1:");
nome = Console.ReadLine();
//****objeto****\\
//classe | nome = new| Classe()
Jogador j1 = new Jogador(nome); // instaciei um novo objeto da classe jogador
Jogador j2 = new Jogador("Théo",100); //new reserva um espaço no endereço da memoria para esse objeto
Jogador j3 = new Jogador("godofredo",40,true);
Jogador j4 = new Jogador("zogofredo",0,false);
j1.info();//_______
j2.info();// ___
j3.info();// ___SOBRECARGA DE CONSTRUTORES
j4.info();//_______
/*//aqui usei os consoles.Writeline pois não tinha chamado como metodo info
j1.energia = 50; // para alterar
Console.WriteLine("As caracteristicas do jogador 1 é: energia: [{0}] nome: [{1}] esta ativo: [{2}]", j1.energia, j1.nome, j1.vivo);
Console.WriteLine("As caracteristicas do jogador 2 é: energia: [{0}] nome: [{1}] esta ativo: [{2}]", j2.energia,j2.nome, j2.vivo);
Console.WriteLine("As caracteristicas do jogador 2 é: energia: [{0}] nome: [{1}] esta ativo: [{2}]", j3.energia, j3.nome, j3.vivo);
Console.WriteLine("As caracteristicas do jogador 2 é: energia: [{0}] nome: [{1}] esta ativo: [{2}]", j4.energia, j4.nome, j4.vivo);*/
}
}
//------------- --ESBOÇO DA CLASSE MOSTRADA NA AULA: ---------------------------------------//
// [ModificadorClasse] class NOME_DA_CLASSE
// {
// Variáveis / Propriedades
// [EspecificadorAcesso] tipo NOME_PROPRIEDADE;
//
// Metodos
// [EspecificadorAcesso] retorno NOME_METODO([arg1,...])
// {
// corpo do método
// }
// }
//-------O QUE SÃO E APLICAÇÕES:-----------------------------------------------//
// [ModificadorClasse]: Define a visibilidade da classe.
// public: pública, sem restrição de visualização.
// abstract: Classe-Base para outrsas classes, não podem ser instanciados a objetos desta classe
// sealed: Classe não pode ser herdada
// static: Classe não permite a instanciação de objetos e seus membros devem ser "static"
//
// [EspecificadorAcesso]: Onde um membro da classe pode ser acessado
// public: pública, sem restrição de acesso.
// private: Só podem ser acessados pela própria classe.
// protected: Podem ser acessados na própria classe e nas classes derivadas
// abstract: Os métodos não tem implementação somente os cabeçalhos
// sealed: O método não pode ser redefinido.
// virtual: O método pode ser redefinido em uma classe derivada.
// static: o método pode ser chamado mesmo sem a instanciação de um objeto.
}
|
TypeScript
|
UTF-8
| 125 | 2.53125 | 3 |
[] |
no_license
|
export enum IColorMode {
DARK = 'dark',
LIGHT = 'light',
}
export interface ISettingsState {
colorMode: IColorMode;
}
|
Java
|
UTF-8
| 353 | 2.1875 | 2 |
[] |
no_license
|
package model.commands;
import java.io.Serializable;
/**
* Enum allows the server to create the drawable objects instead of the client
* since android has trouble creating graphical java objects.
*
* @author William Snider
*
*/
public enum Drawing implements Serializable {
RECTANGLE, CIRCLE, TEXT, RECTANLE_FILLED, CIRCLE_FILLED;
}
|
Python
|
UTF-8
| 614 | 3.296875 | 3 |
[] |
no_license
|
"""
Parses an input file in .fasta format
and returns the gene dictionary
"""
def parse_fasta(data):
keys = []
label_idxes = []
values = []
removed_lines = data.split()
for i in range(len(removed_lines)):
if removed_lines[i].startswith('>'):
keys.append(removed_lines[i].strip('>'))
label_idxes.append(i)
label_idxes.append(len(removed_lines)) # append dummy index to terminate next loop
for i in range(len(label_idxes) - 1):
values.append(''.join(removed_lines[label_idxes[i] + 1:label_idxes[i + 1]]))
return dict(zip(keys, values))
|
JavaScript
|
UTF-8
| 10,863 | 2.65625 | 3 |
[] |
no_license
|
const chai = require('chai');
const chaitHttp = require('chai-http');
const faker = require('faker');
const mongoose = require('mongoose');
const expect = chai.expect;
const activityRouter = require('../routers/activityRouter');
const {Activity} = require('../models/activityModel')
const {Event} = require('../models/eventModel')
const {app, runServer, closeServer} = require('../server.js');
const {TEST_DATABASE_URL} = require('../config.js')
chai.use(chaitHttp);
function seedActivityData(){
const activityData = []
for (let i=1; i<=10; i++){
activityData.push(generateActivityData());
}
return Activity.insertMany(activityData)
}
//Generate test data
//I used strings for the date and time and number instead of currency because that's how they are stored
function generateActivityData(){
return{
eventId: "5af4c9c6f4266d148c2bc6ad",
activity_name: faker.lorem.word(),
activity_url: faker.lorem.words(),
activity_date: faker.lorem.words(),
activity_time: faker.lorem.words(),
kids_welcome: faker.random.boolean(),
kid_cost: faker.random.number(),
adult_cost: faker.random.number(),
group_cost: faker.random.number(),
group_size: faker.random.number(),
activity_host: faker.internet.userName(),
host_name: faker.internet.userName(),
//attendees: faker.internet.userName(),
kid_number: faker.random.number(),
adult_number: faker.random.number(),
activity_comments: {comment: faker.lorem.sentence(), name: faker.internet.userName()}
}
}
function tearDownDb(){
return mongoose.connection.dropDatabase();
}
describe('Activity API endpoint', function(){
before(function(){
return runServer(TEST_DATABASE_URL);
});
beforeEach(function(){
return seedActivityData();
});
afterEach(function(){
return tearDownDb();
});
after(function(){
return closeServer();
});
describe('GET endpoint', function(){
it('should return all activities associated with an event', function(){
let eventId = "5af4c9c6f4266d148c2bc6ad"
let res;
return chai.request(app)
.get(`/activity/event/${eventId}`)
.then(function(_res){
res = _res;
expect(res).to.have.status(200);
expect(res).to.be.json;
expect(res.body).to.be.an('array');
expect(res.body).to.have.length.of.at.least(1)
return Activity.count()
.then(function(count){
expect(res.body).to.have.lengthOf(count);
});
});
});
it('should return the correct activity when called by Id', function(){
let singleAct;
return Activity
.findOne()
.then(function(a){
singleAct = a.body;
})
return chai.request(app)
.get(`activity/${singleAct.id}`)
.then(function(res){
expect(res).to.be.an('object');
expect(res).to.include.keys('id', 'eventId', 'activity_name', 'activity_host');
return res
})
.then(function(res){
expect(singleAct.id).to.equal(res.id);
expect(singleAct.activity_name).to.equal(res.activity_name);
expect(singleAct.activity_comments).to.equal(res.activity_comments);
expect(singleAct.eventId).to.equal(res.eventId);
expect(singleAct.activity_host).to.equal(res.activity_host);
});
});
});
describe('POST endpoint', function(){
xit('should create a new activity', function(){
const newAct = generateActivityData()
delete newAct.activity_comments
newAct.activity_comments = faker.lorem.sentence();
return chai.request(app)
.post('/activity')
.send(newAct)
.then(function(res){
expect(res).to.have.status(201);
expect(res).to.be.json;
expect(res.body).to.include.keys('id', 'eventId', 'name', 'url', 'date', 'time', 'kids_welcome',
'kid_cost', 'adult_cost', 'group_cost', 'group_size', 'host', 'host_name',
'kid_number', 'adult_number', 'activity_comments');
expect(res.body.name).to.equal(newAct.activity_name);
expect(res.body.eventId).to.equal(newAct.eventId);
expect(res.body.url).to.equal(newAct.activity_url);
expect(res.body.date).to.equal(newAct.activity_date);
expect(res.body.time).to.equal(newAct.activity_time);
expect(res.body.kids_welcome).to.equal(newAct.kids_welcome);
expect(res.body.kid_cost).to.equal(newAct.kid_cost);
expect(res.body.adult_cost).to.equal(newAct.adult_cost);
expect(res.body.group_cost).to.equal(newAct.group_cost);
expect(res.body.group_size).to.equal(newAct.group_size);
expect(res.body.host).to.equal(newAct.activity_host);
expect(res.body.host_name).to.equal(newAct.host_name);
//expect(res.body.attendees).to.include(newAct.attendees);
expect(res.body.kid_number).to.equal(newAct.kid_number);
expect(res.body.adult_number).to.equal(newAct.adult_number);
expect(res.body.activity_comments.comment).to.equal(newAct.activity_comments.comment);
return Activity.findById(res.body.id);
})
.then(function(nAct){
expect(nAct.activity_name).to.equal(newAct.activity_name);
expect(nAct.eventId).to.equal(newAct.eventId);
expect(nAct.activity_url).to.equal(newAct.activity_url);
expect(nAct.activity_date).to.equal(newAct.activity_date);
expect(nAct.activity_time).to.equal(newAct.activity_time);
expect(nAct.kids_welcome).to.equal(newAct.kids_welcome);
expect(nAct.kid_cost).to.equal(newAct.kid_cost);
expect(nAct.adult_cost).to.equal(newAct.adult_cost);
expect(nAct.group_cost).to.equal(newAct.group_cost);
expect(nAct.group_size).to.equal(newAct.group_size);
expect(nAct.activity_host).to.equal(newAct.activity_host);
expect(nAct.host_name).to.equal(newAct.host_name);
//expect(nAct.attendees).to.include(newAct.attendees);
expect(nAct.kid_number).to.equal(newAct.kid_number);
expect(nAct.adult_number).to.equal(newAct.adult_number);
});
});
});
describe('PUT endpoint', function(){
it('should update included fields', function(){
const updateAct = {
activity_name: faker.lorem.word(),
group_size: faker.random.number(),
}
return Activity
.findOne()
.then(function(act){
updateAct.id = act.id;
return chai.request(app)
.put(`/activity/${updateAct.id}`)
.send(updateAct)
})
.then(function(res){
expect(res).to.have.status(204);
return Activity.findById(updateAct.id);
})
.then(function(uAct){
expect(uAct.activity_name).to.equal(updateAct.activity_name);
expect(uAct.group_size).to.equal(updateAct.group_size);
})
});
xit('should add a userId to the attendees array and increase attendence', function(){
const joinAct = {
userId: faker.internet.userName(),
kid_number: 1,
adult_number: 1
}
const orgAct ={}
return Activity
.findOne()
.then(function(act){
joinAct.id = act.id;
orgAct.kid_number = act.kid_number;
orgAct.adult_number = act.adult_number;
return chai.request(app)
.put(`/activity/join/${joinAct.id}`)
.send(joinAct)
})
.then(function(res){
expect(res).to.have.status(204);
return Activity.findById(joinAct.id)
})
.then(function(jAct){
expect(jAct.attendees).to.include(joinAct.userId);
expect(jAct.kid_number).to.equal(joinAct.kid_number+orgAct.kid_number);
expect(jAct.adult_number).to.equal(joinAct.adult_number+orgAct.adult_number);
})
})
it('should add a comment to the array', function(){
const newComment = {
comment: faker.lorem.sentence(),
name: faker.internet.userName()
}
return Activity
.findOne()
.then(function(act){
newComment.id = act.id;
return chai.request(app)
.put(`/activity/comments/${newComment.id}`)
.send(newComment)
})
.then(function(res){
expect(res).to.have.status(204);
return Activity.findById(newComment.id)
})
.then(function(comment){
const foundComment = comment.activity_comments.filter(c => c.comment === newComment.comment && c.name === newComment.name)
expect(foundComment).to.have.lengthOf(1)
})
})
});
describe('DELETE endpoint', function(){
it('should delete an activity by id', function(){
const deleteAct = {}
return Activity
.findOne()
.then(function(act){
deleteAct.id = act.id;
})
return chai.request(app)
.delete(`/activity/${deleteAct.id}`)
.then(function(res){
expect(res).to.have.status(204);
const deleted = Activity.findById(deleteAct.id);
return deleted;
})
.then(function(dAct){
expect(dAct).to.be.null;
})
});
});
});
|
Python
|
UTF-8
| 448 | 3.34375 | 3 |
[] |
no_license
|
def add_letters(*letters):
if letters:
lst = [0, "a", "b", "c", "d", "e", "f","g", "h", "i", "j", "k", "l", "m", "n", "o", "p", 'q', "r", "s", "t", "u", "v", "w", "x", "y", "z" ]
sum = 26
for i in letters:
if i in lst:
sum += lst.index(i)
if sum > 26:
if sum % 26 == 0:
return lst[-1]
return lst[sum % 26]
return lst[sum]
return "z"
|
C#
|
UTF-8
| 2,147 | 2.671875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Storage.Queues;
using Bogus;
using Newtonsoft.Json;
using Spectre.Console;
namespace CarvedRockSoftware.Seeder.AzureStorageQueues
{
public class AzureStorageQueuesSeeder : ISeeder
{
private const string ConnectionString = "";
private readonly QueueClient _queueClient;
private readonly IEnumerable<(int Id, string Name, string Description)> _seedData;
public AzureStorageQueuesSeeder()
{
var queueClientOptions = new QueueClientOptions();
var policy = new FakeTransientErrorsHttpPipelinePolicy();
queueClientOptions.AddPolicy(policy, HttpPipelinePosition.PerRetry);
queueClientOptions.Retry.MaxRetries = 0;
_queueClient = new QueueClient(ConnectionString, "products", queueClientOptions);
var faker = new Faker();
_seedData = Enumerable.Range(1, 10).Select(i =>
{
var id = i;
var name = faker.Commerce.ProductName();
var description = faker.Commerce.ProductDescription();
return (id, name, description);
});
}
public async Task RunAsync()
{
await _queueClient.CreateIfNotExistsAsync();
await Task.WhenAll(_seedData.Select(async (product) =>
{
try
{
var json = JsonConvert.SerializeObject(product);
var messageText = JsonConvert.SerializeObject(json);
var base64messageString = Convert.ToBase64String(Encoding.UTF8.GetBytes(messageText));
await _queueClient.SendMessageAsync(base64messageString);
AnsiConsole.MarkupLine($"[green]{product.Name} seeded.[/]");
}
catch (Exception exception)
{
AnsiConsole.MarkupLine($"[red]{product.Name} failed.[/]");
}
}));
}
}
}
|
Java
|
UTF-8
| 289 | 2.046875 | 2 |
[] |
no_license
|
package ch1.aop;
import org.springframework.stereotype.Service;
/**
* 方法式拦截
*
* @author liaoxiaoxia
* @version 1.0.0
* @date 2019/5/29 10:41
* @since JDK 1.8
*/
@Service
public class DemoMethodService {
public void add() {
}
public void update() {
}
}
|
Python
|
UTF-8
| 1,304 | 3.765625 | 4 |
[] |
no_license
|
import random
from turtle import Turtle
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class Car(Turtle):
def __init__(self):
super().__init__()
self.shape('square')
self.color(random.choice(COLORS))
self.penup()
self.shapesize(stretch_wid=1, stretch_len=2)
self.setheading(180)
self.goto(310, random.randint(-250, 250))
class CarManager:
def __init__(self):
self.pace = STARTING_MOVE_DISTANCE
self.group = []
self.traffic = 6
self.set_start_position()
def set_start_position(self):
for index in range(10):
new_car = Car()
random_x = random.randint(0, 300)
new_car.setx(random_x)
self.group.append(new_car)
def generate_car(self):
ran_num = random.randint(0, self.traffic)
if ran_num == 0 or ran_num == 1:
new_car = Car()
self.group.append(new_car)
def drive(self):
for car in self.group:
car.forward(self.pace)
def speed_up(self):
self.pace += MOVE_INCREMENT
if self.traffic > 2:
self.traffic -= 1
def run_system(self):
self.generate_car()
self.drive()
|
C++
|
UTF-8
| 616 | 2.578125 | 3 |
[
"Unlicense"
] |
permissive
|
#ifndef TEXTURE_H
#define TEXTURE_H
#pragma once
#include <iostream>
#include <string>
#include <vector>
#define NO_TEXTURE "!ROOT!/headers/gfx/Textures/std/untextured.jpg"
//#define NO_TEXTURE "!ROOT!/data/textures/std/untextured.jpg"
// ttexture = Type Texture
typedef std::string ttexture;
class texture {
private:
ttexture text;
public:
texture(ttexture texture_ = NO_TEXTURE) { text = texture_; }
texture operator=(ttexture texture_) { text = texture_; }
texture get() { return text; }
void update(ttexture texture_) { text = texture_; }
virtual ~texture() {}
};
#endif // TEXTURE_H
|
Markdown
|
UTF-8
| 3,793 | 2.609375 | 3 |
[] |
no_license
|
# PhotoGallery
> System Design Project on PhotoGallery module
## Related Projects
- https://github.com/styeld-components/PhotoGallery
- https://github.com/styeld-components/Calendar
- https://github.com/styeld-components/reviews
- https://github.com/styeld-components/Carousel
## Table of Contents
1. [Usage](#Usage)
2. [Development](#development)
## Usage
> Some usage instructions
## Development
### setup
From within the root directory:
```sh
- run npm install in root directory
- run below scripts in package.json:
- npm run seed
- npm run build
- npm start
```
## Server Endpoints and API routes
**READ - Render Room's Photo Gallery**
----
* **URL** /api/:room_id/photos
* **Method:** `GET`
* **URL Params**
**Required:** `room_id`
* **Data Params** NA
* **Success Response:**
* **Code:** 200 OK <br />
**content:** `Successfully fetched!` and JSON Object of related photos
**Related photos**
```sh
{
user_id: Number,
room_id: Number,
room_photos: [{
image_id: Number,
image_url: String,
image_name: String,
description: String
}],
favorites: [{
favorite_name: String,
isFaved: Boolean,
}],
}
```
* **Error Response:**
* **Code:** 404 NOT FOUND <br />
**Response:** `Related photos doesnt exit`
**Create - Add photos to The Room's Photo Gallery**
----
* **URL** /api/:room_id/photos
* **Method:** `POST`
* **URL Params**
**Required:** `room_id`
* **Data Params** JSON Object
```sh
{
image_id: Number,
image_url: String,
image_name: String,
description: String
}
```
* **Success Response:**
* **Code:** 201 Created <br />
**Content:** `Successfully posted!`
* **Error Response:**
* **Code:** 401 UNAUTHORIZED <br />
**Content:** `Unathrorized user, unable to post`
**Create - Add a favorite **
----
* **URL** /api/:user_id/favorites
* **Method:** `POST`
* **URL Params**
**Required:** `user_id`
* **Data Params** JSON Object
```sh
{
favorite_name: String,
isFaved: Boolean,
}
```
* **Success Response:**
* **Code:** 201 Created <br />
**Content:** `Successfully posted!`
* **Error Response:**
* **Code:** 401 UNAUTHORIZED <br />
**Content:** `Unathrorized user, unable to post`
**Update - Update photo information**
----
* **URL** /api/:room_id/photos/:image_id
* **Method:** `PUT`
* **URL Params**
**Required:**
* `room_id`
* `image_id`
* **Data Params** JSON Object
```sh
{
image_url: String,
image_name: String,
description: String
}
```
* **Success Response:**
* **Code:** 201 Created <br />
**Response:** `Successfully updated!`
* **Error Response:**
* **Code:** 401 UNAUTHORIZED <br />
**Response:** `Unathrorized user, unable to update`
**Update - Update the status on favorite**
----
* **URL** /api/:room_id/photos
* **Method:** `PUT`
* **URL Params**
**Required:** `room_id`
* **Data Params** JSON Object
```sh
{
isFaved: Boolean,
}
```
* **Success Response:**
* **Code:** 201 Created <br />
**Response:** `Successfully updated!`
* **Error Response:**
* **Code:** 401 UNAUTHORIZED <br />
**Response:** `Unathrorized user, unable to update`
**Delete - Delete photo from the faovrite list**
----
* **URL** /api/:room_id/photos
* **Method:** `DELETE`
* **URL Params**
**Required:** `room_id`
* **Success Response:**
* **Code:** 204 OK <br />
**Response Content:** `Successfully removed!`
* **Error Response:**
* **Code:** 404 NOT FOUND <br />
**Response Content:** `fovorite does not exist, can't be remove`
or
* **Code:** 401 UNAUTHORIZED <br />
**Response Content:** `You are unauthorized to remove favorite`
|
JavaScript
|
UTF-8
| 1,551 | 2.5625 | 3 |
[] |
no_license
|
const buildForApi = (payload) => {
return {
name: payload.name,
task_list_id: payload.taskListId
};
};
const buildForUi = (payload) => {
return {
id: payload.id,
name: payload.name,
taskListId: payload.task_list_id
};
};
const all = (organizationId, projectId) => {
return fetch(`${process.env.API_URL}/organizations/${organizationId}/projects/${projectId}/tasks`, {
method: 'GET',
credentials: 'include'
})
.then((response) => {
return response.json();
})
.then((tasks) => {
return tasks.map(buildForUi);
});
};
const create = (organizationId, projectId, payload) => {
return fetch(`${process.env.API_URL}/organizations/${organizationId}/projects/${projectId}/tasks`, {
body: JSON.stringify(buildForApi(payload)),
credentials: 'include',
method: 'POST',
headers: {'Content-type': 'application/json'}
})
.then((response) => {
return response.json();
})
.then((task) => {
return buildForUi(task);
});
};
const update = (organizationId, projectId, taskId, payload) => {
return fetch(`${process.env.API_URL}/organizations/${organizationId}/projects/${projectId}/tasks/${taskId}`, {
body: JSON.stringify(buildForApi(payload)),
credentials: 'include',
method: 'PUT',
headers: {'Content-type': 'application/json'}
})
.then((response) => {
return response.json();
})
.then((task) => {
return buildForUi(task);
});
};
export default {
all,
create,
update
};
|
Python
|
UTF-8
| 901 | 2.59375 | 3 |
[] |
no_license
|
import boto3
dynamo = boto3.resource('dynamodb')
table=dynamo.Table('courses')
def lambda_handler(event, context):
tempid=event['id']
titleVal=event['title']
watchHrefVal=event['watchHref']
authorIdVal=event['authorId']
lenghtVal=event['length']
categoryVal=event['category']
try:
response=table.put_item(
Item = {
"id": tempid,
"title": titleVal,
"watchHref": watchHrefVal,
"authorId": authorIdVal,
"length": lenghtVal,
"category": categoryVal
})
response={ "id": tempid, "title": titleVal, "watchHref": watchHrefVal, "authorId": authorIdVal, "length": lenghtVal, "category": categoryVal }
return response
except Exception as e:
print(">>>>>>"+str(e))
|
C#
|
UTF-8
| 4,368 | 3.65625 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmNote
{
public class MinHeap<T> where T : IComparable
{
private ArrayList<T> data;
public MinHeap(int capacity)
{
data = new ArrayList<T>(capacity);
}
public MinHeap()
{
data = new ArrayList<T>();
}
public MinHeap(T[] arr)
{
data = new ArrayList<T>(arr);
for (var i = Parent(arr.Length - 1); i >= 0; i--)
{
SiftDown(i);
}
}
/// <summary>
/// 返回堆中元素个数
/// </summary>
/// <returns></returns>
public int GetSize()
{
return data.GetSize();
}
/// <summary>
/// 返回一个布尔值,表示堆中是否为空
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
return data.IsEmpty();
}
/// <summary>
/// 返回完全二叉树的数组表示中,一个索引所表示的元素的父亲节点的索引
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private int Parent(int index)
{
if (index == 0)
{
throw new ArgumentException("Index-0 doesn't have parent.");
}
return (index - 1) / 2;
}
/// <summary>
/// 返回完全二叉树的数组表示中,一个索引所表示的元素的左孩子节点的索引
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private int LeftChild(int index)
{
return index * 2 + 1;
}
/// <summary>
/// 返回完全二叉树的数组表示中,一个索引所表示的元素的右孩子节点的索引
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private int RightChild(int index)
{
return index * 2 + 2;
}
/// <summary>
/// 向堆中添加函数
/// </summary>
/// <param name="e"></param>
public void Add(T e)
{
data.AddLast(e);
SiftUp(data.GetSize() - 1);
}
private void SiftUp(int k)
{
while (k > 0 && data.Get(Parent(k)).CompareTo(data.Get(k)) > 0)
{
data.Swap(k, Parent(k));
k = Parent(k);
}
}
/// <summary>
/// 看一眼堆中最小的元素
/// </summary>
/// <returns></returns>
public T FindMin()
{
if (data.GetSize() == 0)
{
throw new ArgumentException("Can not FindMax when heap is empty..");
}
return data.Get(0);
}
/// <summary>
/// 取出堆中最小的元素
/// </summary>
/// <returns></returns>
public T ExtractMin()
{
var ret = FindMin();
data.Swap(0, data.GetSize() - 1);
data.RemoveLast();
SiftDown(0);
return ret;
}
private void SiftDown(int k)
{
while (LeftChild(k) < data.GetSize())
{
// 得到k左右孩最小的那个
var j = LeftChild(k);
if (j + 1 < data.GetSize() && data.Get(j + 1).CompareTo(data.Get(j)) < 0)
{
j = RightChild(k);
}
// 没有违反堆的性质,k比左右孩子中最小的还小
if (data.Get(k).CompareTo(data.Get(j)) <= 0)
{
break;
}
// 违反了堆性质,k需要下沉
data.Swap(k, j);
k = j;
}
}
/// <summary>
/// 取出堆中最小元素,并且替换成元素e
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public T Replace(T e)
{
var ret = FindMin();
data.Set(0, e);
SiftDown(0);
return ret;
}
}
}
|
Go
|
UTF-8
| 1,497 | 2.875 | 3 |
[] |
no_license
|
package redis
import (
"time"
"github.com/astaxie/beego"
"github.com/garyburd/redigo/redis"
)
var (
db_addr string = ""
db_password string = ""
Session_live_time int = 3600 //session过期时间 单位秒
redisPool *redis.Pool //redis连接池
)
func init() {
db_addr = beego.AppConfig.String("redis_addr")
db_password = beego.AppConfig.String("redis_password")
var err error
Session_live_time, err = beego.AppConfig.Int("session_live_time")
if err != nil {
Session_live_time = 3600
}
}
func RedisConnect(dbNum int) redis.Conn {
conn, _ := redis.Dial("tcp", db_addr, redis.DialPassword(db_password), redis.DialDatabase(dbNum))
return conn
}
//获取Redis连接池
func newRedisPool(server, password string) (*redis.Pool, error) {
var err error
return &redis.Pool{
MaxIdle: 32,
IdleTimeout: 180 * time.Second,
Dial: func() (redis.Conn, error) {
var c redis.Conn
c, err = redis.Dial("tcp", server)
if err != nil {
return nil, err
}
if password != "" {
if _, err = c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}, err
}
/*
获取redis数据库连接
*/
func GetRedisConnection() (redis.Conn, error) {
if redisPool == nil {
var err error
redisPool, err = newRedisPool(db_addr, db_password)
if err != nil {
return nil, err
}
}
return redisPool.Get(), nil
}
|
TypeScript
|
UTF-8
| 3,476 | 2.578125 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
const pinBox = document.getElementById("pinBox") as HTMLDivElement;
const pinInput = document.getElementById("pinInput") as HTMLInputElement;
const loadingSpinnerContainer = document.querySelector(".spinner-container") as HTMLDivElement;
const loadingSpinner = document.getElementById("loadingSpinner") as HTMLDivElement;
const resendCodeButton = document.getElementById("resendCodeButton") as HTMLButtonElement;
const resendCodeContainer = document.getElementById("resendCodeContainer") as HTMLDivElement;
if (loadingSpinner) {
loadingSpinner.style.display = "none";
}
interface State {
errorMessage: string | undefined;
errorHidden: boolean;
formShown: boolean;
}
const state: State = {
errorMessage: undefined,
errorHidden: true,
formShown: true,
};
const API_URL = "https://elliotapiserver.com/Auth";
const verifyEmail = async (): Promise<void> => {
const Data = {
email: localStorage.getItem("EmailToVerify"),
code: pinInput.value.toString(),
};
try {
const res = await fetch(API_URL + "/VerifyEmail", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(Data),
});
pinInput.value = "";
if (res.status === 200) {
localStorage.setItem("EmailToVerify", "");
window.location.replace("/pages/login/login.html");
} else if (res.status === 301) {
pinBox.style.display = "block";
resendCodeContainer.style.display = "block";
loadingSpinner.style.display = "none";
loadingSpinnerContainer.style.display = "none";
errorMessageEmail.style.display = "block";
pinInput.focus();
} else if (res.status === 404) {
await window.location.replace("/pages/login/signup.html");
}
} catch (error) {
loadingSpinner.style.display = "none";
state.errorHidden = false;
state.errorMessage = error.message;
setTimeout(() => {
state.errorHidden = true;
}, 5000);
setTimeout(() => {
state.formShown = true;
}, 400);
}
};
const checkPinInput = (): void => {
if (pinInput.value.length === 4) {
pinBox.style.display = "none";
loadingSpinner.style.display = "block";
loadingSpinnerContainer.style.display = "flex";
resendCodeContainer.style.display = "none";
verifyEmail();
}
};
if (pinInput) {
pinInput.addEventListener("keydown", (e) => {
if (!Number.isInteger(parseInt(e.key)) && e.keyCode !== 8) {
e.preventDefault();
}
});
pinInput.addEventListener("keyup", () => {
checkPinInput();
});
}
if (resendCodeButton) {
resendCodeButton.addEventListener("click", (e) => {
e.preventDefault();
resendEmail();
});
}
const resendEmail = async (): Promise<void> => {
try {
const data = {
email: localStorage.getItem("EmailToVerify"),
};
const res = await fetch(API_URL + "/ResendEmail", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (res.status === 201) {
resendCodeContainer.innerHTML = "Code Sent!";
} else if (res.status === 500) {
throw new Error("Cannot resend verification code, please try again later.");
} else if (res.status === 404) {
throw new Error("No user with that email");
}
} catch (error) {
console.error(error);
}
};
export const emailVerified = () => {
if (localStorage.getItem("EmailToVerify") === "") {
window.location.replace("/pages/login/login.html");
}
};
|
Python
|
UTF-8
| 1,869 | 3.859375 | 4 |
[] |
no_license
|
import random
print('HI GUYS WELCOME TO PLAY AHORCADOS')
# words = ['unlucky', 'steps', 'so', 'last', 'let', 'something', 'sometimes']
words = ['unlucky','unlucky']
def draw(n=[]):
print(['unlucky', 'steps', 'so', 'last', 'let', 'something', 'sometimes'])
container = """\t\t\t+------------------+
\t\t\t| |
\t\t\t{0}\t\t\t\t|
\t\t {1} {2} {3}\t\t\t\t|
\t\t\t{4}\t\t\t\t|
\t\t {5} {6}\t\t\t\t|
\t\t\t\t\t\t\t|
\t\t\t\t\t\t\t|
\t\t\t\t\t\t\t|
\t\t\t\t\t\t\t|
\t\t\t\t\t\t\t|
\t\t\t\t\t\t\t|===================
""".format(n[0], n[1], n[2], n[3], n[4], n[5], n[6])
return container
def lucky(words):
# do a random the list words
random.shuffle(words)
# random item from the list words
word_random = random.choice(words)
return word_random
def play():
# call to the function lucky()
word = list(lucky(words))
# stored the body in a tupla
failed = ('O','/','|','\\','|','/','\\')
# assigning values
number_failed, parameters = 0, ["","","","","","",""]
guess_letter = len(word) * ["(-)"]
# print the function draw
print(draw(parameters))
print(guess_letter)
for i in range(len(word)):
# input the user for enter the letter okey
enter_letter= input("enter the letter ok")
# if the input of user is okey
for j in range(len(word)):
if enter_letter == word[j]:
guess_letter[j] = enter_letter
word[j] = '.'
print(draw(parameters))
print(guess_letter)
break
else:
parameters[number_failed] = failed[number_failed]
number_failed += 1
print(draw(parameters))
print(guess_letter)
return "bye"
def main():
begin = play()
print(begin)
main()
|
Markdown
|
UTF-8
| 5,665 | 2.53125 | 3 |
[
"CC-BY-4.0",
"MIT",
"CC-BY-3.0"
] |
permissive
|
<properties
pageTitle="自動調整入口網站中的雲端服務 |Microsoft Azure"
description="瞭解如何使用自動小數位數的設定規則的雲端服務 web 角色或工作者角色 Azure 中的入口網站。"
services="cloud-services"
documentationCenter=""
authors="Thraka"
manager="timlt"
editor=""/>
<tags
ms.service="cloud-services"
ms.workload="tbd"
ms.tgt_pltfrm="na"
ms.devlang="na"
ms.topic="article"
ms.date="09/06/2016"
ms.author="adegeo"/>
# <a name="how-to-auto-scale-a-cloud-service"></a>如何自動調整大小雲端服務
> [AZURE.SELECTOR]
- [Azure 入口網站](cloud-services-how-to-scale-portal.md)
- [Azure 傳統入口網站](cloud-services-how-to-scale.md)
觸發的比例或縮小作業雲端服務工作者角色的可設定條件。 角色條件可以根據 CPU、 或網路負載的角色。 您也可以設定 conditation,根據訊息佇列或與您的訂閱相關聯的某些其他 Azure 資源的度量。
>[AZURE.NOTE] 本文著重於雲端服務 web 及工作者角色。 當您直接建立虛擬機器 (傳統) 時,它會裝載雲端服務中。 您可以藉由將它[可用性設定](../virtual-machines/virtual-machines-windows-classic-configure-availability.md)縮放標準的虛擬機器並手動將其開啟或關閉。
## <a name="considerations"></a>考量
設定應用程式的縮放比例之前,您應該考慮下列資訊︰
- 縮放比例,並受到核心使用方式。 較大的角色執行個體使用更多核心。 您可以調整只在核心的限制內的應用程式,您的訂閱。 例如,如果您的訂閱有二十核心和您與調整大小的兩個中執行的應用程式的限制雲端服務 (總計的四個核心),您可以只縮放設定其他雲端服務部署在您的訂閱 16 個核心。 大小的詳細資訊,請參閱[雲端服務的大小](cloud-services-sizes-specs.md)。
- 您可以在不按比例縮放在佇列中郵件閥值。 如需有關如何使用佇列的詳細資訊,請參閱[如何使用佇列中儲存服務](../storage/storage-dotnet-how-to-use-queues.md)。
- 您也可以調整您的訂閱相關聯的其他資源。
- 若要啟用您的應用程式的可用性,您應該確認部署與兩個或多個角色執行個體。 如需詳細資訊,請參閱[服務等級協定](https://azure.microsoft.com/support/legal/sla/)。
## <a name="where-scale-is-located"></a>縮放比例所在的位置
選取您的雲端服務之後,您應該看到雲端服務刀。
1. 在雲端服務防禦,在 [**角色及執行個體**] 方塊中,選取雲端服務的名稱。
**重要事項**︰ 請務必按一下雲端服務角色,而不是下一個角色的角色執行個體。

2. 選取 [**縮放比例**] 方塊。

## <a name="automatic-scale"></a>自動縮放比例
您可以使用兩種模式**手動**或**自動**設定角色的縮放設定。 手動您所預期,您設定的執行個體絕對的計數。 自動不過可讓您設定的規則,如何以及更您應縮放。
將**依比例縮放**選項**排程和效能**的規則。

1. 現有的設定檔。
2. 新增上層設定檔的規則。
3. 新增另一個設定檔。
選取 [**新增設定檔**]。 設定檔會決定您想要的刻度使用哪一種的模式︰**永遠**、**週期**、**固定日期**。
您已設定的設定檔和規則之後,請選取 [頂端的 [**儲存**] 圖示。
#### <a name="profile"></a>設定檔
設定檔設定最小值和最大比例] 的執行個體,並且也時縮放比例範圍作用中。
* **永遠**
永遠保持此範圍的可用的執行個體。

* **循環**
選擇一組縮放週的日子。

* **固定的日期**
若要縮放的角色固定的日期範圍。

您已設定設定檔之後,請選取 [設定檔刀底部的 [**確定**] 按鈕。
#### <a name="rule"></a>規則
規則會新增至 [設定檔,而且代表會觸發小數位數的條件。
規則的觸發程序會根據度量單位,您可以新增條件的值的雲端服務 (CPU 使用率、 磁碟活動或網路活動)。 此外,您可以讓郵件佇列中或公制與您的訂閱相關聯的某些其他 Azure 資源的觸發程序。

您已設定規則之後,請選取規則刀底部的 [**確定**] 按鈕。
## <a name="back-to-manual-scale"></a>回到手動縮放比例
瀏覽至[縮放設定](#where-scale-is-located),並將**依比例縮放**選項設定為**手動輸入執行個體字數統計**。

這樣就會移除該角色的自動化縮放比例,然後您可以直接設定執行個體計數。
1. 小數位數 (手動或自動) 選項。
2. 若要設定要縮放的執行個體角色執行個體滑桿。
3. 若要縮放至角色的執行個體。
您已設定縮放設定後,請選取 [頂端的 [**儲存**] 圖示。
|
JavaScript
|
UTF-8
| 429 | 3.578125 | 4 |
[] |
no_license
|
str="The quick brown fox jumps over the lazy dog"
chr='the'
function count(s,c){
let strArray=s.split(" ")
return strArray.filter(word => word.toLowerCase() == c).length
//console.log(strArray.filter(word => word.toLowerCase() == c).length)
// strArray.forEach(function(value){
// if(value.toLowerCase()==c){
// count++
// }
// })
//return count
}
console.log(count(str,chr))
|
Python
|
UTF-8
| 633 | 2.75 | 3 |
[] |
no_license
|
from observer.lib import Subject
class KPIs(Subject):
_opened_tickets = -1
_closed_tickets = -1
_new_tickets = -1
@property
def opened_tickets(self) -> int:
return self._opened_tickets
@property
def closed_tickets(self) -> int:
return self._closed_tickets
@property
def new_tickets(self) -> int:
return self._new_tickets
def set_kpis(self, opened_tickets: int, closed_tickets: int, new_tickets: int) -> None:
self._opened_tickets = opened_tickets
self._closed_tickets = closed_tickets
self._new_tickets = new_tickets
self.notify()
|
C#
|
UTF-8
| 563 | 3.546875 | 4 |
[] |
no_license
|
using System.Drawing;
namespace Inflate_Rectangle
{
class InflateRectangle
{
static void Inflate(ref Rectangle rect, Size inflateSize)
{
rect.X -= inflateSize.Height;
rect.Y -= inflateSize.Width;
rect.Height += 2 * inflateSize.Height;
rect.Width += 2 * inflateSize.Width;
}
static void Main()
{
Rectangle rect = new Rectangle(0, 0, 10, 10);
Size inflateSize = new Size(2, 2);
Inflate(ref rect, inflateSize);
}
}
}
|
Markdown
|
UTF-8
| 13,016 | 2.53125 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
uid: web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing
title: 使用 ASP.NET Web API 2 中的屬性路由建立 REST API |Microsoft Docs
author: MikeWasson
description: ''
ms.author: riande
ms.date: 06/26/2013
ms.assetid: 23fc77da-2725-4434-99a0-ff872d96336b
msc.legacyurl: /web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing
msc.type: authoredcontent
ms.openlocfilehash: 18a44c280e6df1603837938d24d7d639d8c87cc2
ms.sourcegitcommit: 2d3e5422d530203efdaf2014d1d7df31f88d08d0
ms.translationtype: MT
ms.contentlocale: zh-TW
ms.lasthandoff: 11/05/2018
ms.locfileid: "51021413"
---
<a name="create-a-rest-api-with-attribute-routing-in-aspnet-web-api-2"></a>ASP.NET Web API 2 中的屬性路由建立 REST API
====================
藉由[Mike Wasson](https://github.com/MikeWasson)
Web API 2 支援新類型的路由,稱為*屬性路由*。 屬性路由的一般概觀,請參閱 < [Web API 2 中的屬性路由](attribute-routing-in-web-api-2.md)。 在本教學課程中,您將使用屬性路由建立 REST API 的書籍集合。 API 將會支援下列動作:
| 動作 | 範例 URI |
| --- | --- |
| 取得所有書籍的清單。 | / api/書籍 |
| 取得活頁簿的識別碼。 | /api/books/1 |
| 取得活頁簿的詳細資訊。 | /api/books/1/details |
| 取得內容類型的書籍清單。 | /api/books/fantasy |
| 取得發行日期的書籍清單。 | /api/books/date/2013-02-16 /api/books/date/2013/02/16 (替代形式) |
| 取得特定作者的書籍清單。 | /api/authors/1/books |
所有方法都是唯讀狀態 (HTTP GET 要求)。
資料層,我們將使用 Entity Framework。 書籍記錄將會有下列欄位:
- 識別碼
- 標題
- 內容類型
- 發行日期
- 價格
- 描述
- AuthorID (Authors 資料表的外部索引鍵)
不過,對於大部分的要求,這個 API 會傳回此資料 (標題、 作者和內容類型) 的子集。 若要取得完整的記錄,用戶端要求`/api/books/{id}/details`。
## <a name="prerequisites"></a>必要條件
[Visual Studio 2017](https://visualstudio.microsoft.com/downloads/?utm_medium=microsoft&utm_source=docs.microsoft.com&utm_campaign=button+cta&utm_content=download+vs2017) Community、 Professional 或 Enterprise edition。
## <a name="create-the-visual-studio-project"></a>建立 Visual Studio 專案
執行 Visual Studio 啟動。 從**檔案**功能表上,選取**新增**,然後選取**專案**。
依序展開**已安裝** > **Visual C#** 類別目錄。 底下**Visual C#**,選取**Web**。 在專案範本清單中,選取**ASP.NET Web 應用程式 (.NET Framework)**。 將專案命名為"BooksAPI"。

在 **新的 ASP.NET Web 應用程式**對話方塊中,選取**空白**範本。 在"新增資料夾和核心參考 」,選取**Web API**核取方塊。 按一下 [確定 **Deploying Office Solutions**]。

這會建立基本架構的專案已針對 Web API 的功能。
### <a name="domain-models"></a>網域模型
接下來,新增的網域模型的類別。 在 [方案總管] 中,以滑鼠右鍵按一下 [模型] 資料夾。 選取 **新增**,然後選取**類別**。 將類別命名為 `Author` 。

您可以將 Author.cs 中的程式碼取代為下列:
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample1.cs)]
現在加入另一個類別,名為`Book`。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample2.cs)]
### <a name="add-a-web-api-controller"></a>新增 Web API 控制器
在此步驟中,我們將新增為資料層會使用 Entity Framework 的 Web API 控制器。
按 CTRL+SHIFT+B 以建置專案。 Entity Framework 會使用反射來探索模型中,屬性,因此需要編譯的組件,來建立資料庫結構描述。
在 [方案總管] 中,以滑鼠右鍵按一下 [控制器] 資料夾。 選取 **新增**,然後選取**控制站**。

在 **新增 Scaffold**對話方塊中,選取**Web API 2 控制器與動作,使用 Entity Framework**。
[](create-a-rest-api-with-attribute-routing/_static/image5.png)
在 [**新增控制器**] 對話方塊中,如**控制器名稱**,輸入"BooksController"。 選取 "使用非同步控制器動作"核取方塊。 針對**模型類別**,選取"活頁簿"。 (如果您沒有看到`Book`類別列在下拉式清單,請確定您建置專案。)然後按一下"+"按鈕。

按一下 **新增**中**新的資料內容**對話方塊。

按一下 **新增**中**新增控制器**對話方塊。 Scaffolding 會加入名為類別`BooksController`定義 API 控制器。 它也會新增一個名為類別`BooksAPIContext`在 Models 資料夾中,其定義用於 Entity Framework 資料內容。

### <a name="seed-the-database"></a>植入資料庫
從 [工具] 功能表中,選取**NuGet 套件管理員**,然後選取**Package Manager Console**。
在 [套件管理員主控台] 視窗中,輸入下列命令:
[!code-powershell[Main](create-a-rest-api-with-attribute-routing/samples/sample3.ps1)]
此命令會建立 Migrations 資料夾,並將新的程式碼檔案,名為 Configuration.cs。 開啟此檔案並新增下列程式碼`Configuration.Seed`方法。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample4.cs)]
在 [套件管理員主控台] 視窗中,輸入下列命令。
[!code-powershell[Main](create-a-rest-api-with-attribute-routing/samples/sample5.ps1)]
這些命令會建立本機資料庫,並叫用種子方法,來擴展資料庫。

## <a name="add-dto-classes"></a>新增的 DTO 類別
如果您執行應用程式現在,並將 GET 要求傳送至 /api/books/1,回應看起來如下所示。 (我新增縮排以提高可讀性)。
[!code-json[Main](create-a-rest-api-with-attribute-routing/samples/sample6.json)]
相反地,我想這項要求傳回的欄位子集。 此外,我希望它傳回作者的名稱,而不是作者的識別碼。 若要這麼做,我們要修改控制器方法,以傳回*資料傳輸物件*(DTO) 而不是 EF 模型。 DTO 是只設計來執行資料的物件。
在 [方案總管] 中,以滑鼠右鍵按一下專案,然後選取**新增** | **新資料夾**。 將資料夾命名"Dto"。 新增類別,名為`BookDto`Dto 資料夾中,使用下列定義:
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample7.cs)]
新增另一個類別,名為`BookDetailDto`。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample8.cs)]
接下來,更新`BooksController`類別,以傳回`BookDto`執行個體。 我們將使用[Queryable.Select](https://msdn.microsoft.com/library/system.linq.queryable.select.aspx)方法,以專案`Book`執行個體`BookDto`執行個體。 以下是控制器類別的更新程式碼。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample9.cs)]
> [!NOTE]
> 我刪掉`PutBook`, `PostBook`,和`DeleteBook`方法,因為本教學課程不需要它們。
現在如果您執行應用程式,並要求 /api/books/1,回應主體看起來應該像這樣:
[!code-json[Main](create-a-rest-api-with-attribute-routing/samples/sample10.json)]
## <a name="add-route-attributes"></a>新增路由屬性
接下來,我們會將轉換控制器以使用屬性路由。 首先,新增**RoutePrefix**屬性控制站。 此屬性會定義此控制站上的所有方法的初始 URI 區段。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample11.cs?highlight=1)]
然後新增 **[路由]** 屬性至控制器動作,如下所示:
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample12.cs?highlight=1,7)]
每個控制器方法的路由範本是前置詞加上字串中指定**路由**屬性。 針對`GetBook`方法,路由範本中包含的參數化的字串"{id: int}",會比對如果 URI 區段包含整數值。
| 方法 | 路由範本 | 範例 URI |
| --- | --- | --- |
| `GetBooks` | "api/books" | `http://localhost/api/books` |
| `GetBook` | 「 書籍 api / / {id: int}" | `http://localhost/api/books/5` |
## <a name="get-book-details"></a>取得活頁簿詳細資料
若要取得活頁簿詳細資料,用戶端會傳送 GET 要求`/api/books/{id}/details`,其中 *{id}* 本書的識別碼。
將下列方法加入 `BooksController` 類別。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample13.cs)]
如果您要求`/api/books/1/details`,回應看起來像這樣:
[!code-json[Main](create-a-rest-api-with-attribute-routing/samples/sample14.json)]
## <a name="get-books-by-genre"></a>依內容類型的書籍
若要取得特定的內容類型的書籍清單,用戶端會傳送 GET 要求`/api/books/genre`,其中*genre*是內容類型的名稱。 (例如,`/api/books/fantasy`)。
將下列方法加入`BooksController`。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample15.cs)]
這裡我們所定義的路由,其中包含 URI 範本中的 {genre} 參數。 請注意,Web API 可以區分這些兩個 Uri,並將它們路由傳送至不同的方法:
`/api/books/1`
`/api/books/fantasy`
這是因為`GetBook`方法包含 「 識別碼 」 區段必須是整數值的條件約束:
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample16.cs?highlight=1)]
如果您要求 /api/books/fantasy,回應看起來像這樣:
`[ { "Title": "Midnight Rain", "Author": "Ralls, Kim", "Genre": "Fantasy" }, { "Title": "Maeve Ascendant", "Author": "Corets, Eva", "Genre": "Fantasy" }, { "Title": "The Sundered Grail", "Author": "Corets, Eva", "Genre": "Fantasy" } ]`
## <a name="get-books-by-author"></a>作者的書籍
若要取得某位特定作者的書籍清單,用戶端會傳送 GET 要求`/api/authors/id/books`,其中*識別碼*作者的識別碼。
將下列方法加入`BooksController`。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample17.cs)]
有趣的此範例中,是因為"書籍"是處理的子資源"作者"。 此模式是 RESTful Api 中相當常見。
波狀符號 (~) 路由範本中的會覆寫中的路由前置詞**RoutePrefix**屬性。
## <a name="get-books-by-publication-date"></a>取得活頁簿發行日期
若要取得依發行日期的書籍清單,用戶端會傳送 GET 要求`/api/books/date/yyyy-mm-dd`,其中*yyyy-mm-dd 的-* 的日期。
若要這樣做的其中一個方法如下:
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample18.cs)]
`{pubdate:datetime}`參數會限制為符合**DateTime**值。 可以運作,但超出我們想要的實際更寬鬆。 比方說,這些 Uri 也會比對路由:
`/api/books/date/Thu, 01 May 2008`
`/api/books/date/2000-12-16T00:00:00`
沒有任何問題讓這些 Uri。 不過,您也可以將規則運算式的條件約束加入至路由範本,以限制路由至特定的格式:
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample19.cs?highlight=1)]
現在僅日期格式"yyyy-mm-dd 的-"會比對。 請注意,我們不使用 regex 驗證,我們會取得實際的日期。 Web API 會嘗試將轉換成 URI 區段時,處理**DateTime**執行個體。 無效的日期 2012 例如 '-47-99' 將無法進行轉換,而且用戶端會收到 404 錯誤。
您也可以支援斜線分隔符號 (`/api/books/date/yyyy/mm/dd`) 是新增另一個 **[Route]** 與其他規則運算式的屬性。
[!code-html[Main](create-a-rest-api-with-attribute-routing/samples/sample20.html)]
沒有細微但很重要明瞭。 第二個路由範本具有萬用字元 (\*) {pubdate} 參數的開頭:
[!code-json[Main](create-a-rest-api-with-attribute-routing/samples/sample21.json)]
這會告訴路由引擎該 {pubdate} 應該符合 URI 的其餘部分。 根據預設,範本參數會比對單一的 URI 區段。 在此情況下,我們要 {pubdate} 跨越數個 URI 區段:
`/api/books/date/2013/06/17`
## <a name="controller-code"></a>控制器程式碼
以下是 BooksController 類別的完整程式碼。
[!code-csharp[Main](create-a-rest-api-with-attribute-routing/samples/sample22.cs)]
## <a name="summary"></a>總結
屬性路由可讓您更多控制權和更大的彈性設計時為您的 API 的 Uri。
|
C
|
UTF-8
| 5,472 | 2.640625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <math.h>
unsigned int crca,crcb;
FILE *fp;
main(argc,argv,envs)
int argc;
char *argv[];
char *envs[];
{ unsigned long word;
int i;
fp = fopen("dig.dat","r");
fscanf(fp,"%x",&word);
crc(0,word);
printf(" word=%0.8x offline crca=%x crcb=%x\n",word,crca,crcb);
for(i=0;i<5;i++)
{ fscanf(fp,"%x",&word);
crc(1,word);
printf(" word=%8.8x offline crca=%x crcb=%x\n",word,crca,crcb);
}
fscanf(fp,"%x",&word);
printf(" crc word=%8.8x\n",word);
crc(2,word);
unscramble(word);
crc(1,0);
}
crc(int ent,unsigned long word)
{ int in0[16],in1[16];
static int crc0[16],crc1[16];
static int poly[16] = {1,0,1,0, 0,0,0,0, 0,0,0,0, 0,0,0,1};
int outbit0,outbit1;
int i,k,data_in0,data_in1,kk,kmax;
/* ==================================================
ent=0 first entry (header word) initialize
then do crc calculation
ent=1 normal data - just update crc calculation
ent=2 send through the crc from the digitizer
================================================== */
/* unpack the data word back into the serial streams in0 and in1 sent
by the digitizer in0(0) and in1(0) were the first bits recieved */
/* sort the 32 bit word back into the 2 serial streams */
in0[15] = (word>>30) & 1;
in0[14] = (word>>28) & 1;
in0[13] = (word>>26) & 1;
in0[12] = (word>>24) & 1;
in0[11] = (word>>22) & 1;
in0[10] = (word>>20) & 1;
in0[9] = (word>>18) & 1;
in0[8] = (word>>16) & 1;
in0[7] = (word>>14) & 1;
in0[6] = (word>>12) & 1;
in0[5] = (word>>10) & 1;
in0[4] = (word>>8) & 1;
in0[3] = (word>>6) & 1;
in0[2] = (word>>4) & 1;
in0[1] = (word>>2) & 1;
in0[0] = (word>>0) & 1;
in1[15] = (word>>31) & 1;
in1[14] = (word>>29) & 1;
in1[13] = (word>>27) & 1;
in1[12] = (word>>25) & 1;
in1[11] = (word>>23) & 1;
in1[10] = (word>>21) & 1;
in1[9] = (word>>19) & 1;
in1[8] = (word>>17) & 1;
in1[7] = (word>>15) & 1;
in1[6] = (word>>13) & 1;
in1[5] = (word>>11) & 1;
in1[4] = (word>>9) & 1;
in1[3] = (word>>7) & 1;
in1[2] = (word>>5) & 1;
in1[1] = (word>>3) & 1;
in1[0] = (word>>1) & 1;
/* if this is the first entry initialize the outbits and 16 bit crc's */
if(ent == 0)
{ outbit0=0;
outbit1=0;
for(i=0;i<16;i++)
{ crc0[i]=0;
crc1[i]=0;
}
}
/* now send the bits one at a time into the crc calculation */
kmax=16;
if(ent == 2) kmax=15;
for(k=0;k<kmax;k++)
{
/* -------------------- serial data stream 1 -------------- */
data_in1 = in1[k];
/* shift in 1 bit -- save the high order bit shifted out */
outbit1 = crc1[15];
for(i=15;i>0;i--) crc1[i] = crc1[i-1];
crc1[0] = data_in1;
/* exclusive or crc1 with the polynomial if outbit is 1 */
if(outbit1 == 1)
{ for(i=15;i>-1;i--)
{ crc1[i] = crc1[i] ^ poly[i]; /* ^ = xor */
}
}
/* -------------------- serial data stream 0 -------------- */
data_in0 = in0[k];
/* shift in 1 bit -- save the high order bit shifted out */
outbit0 = crc0[15];
for(i=15;i>0;i--) crc0[i] = crc0[i-1];
crc0[0] = data_in0;
if(outbit0 == 1)
{ for(i=15;i>-1;i--)
{ crc0[i] = crc0[i] ^ poly[i]; /* ^ = xor */
}
}
/* now put the crc0 bits back together as a 16 bit word */
crca = 0;
for(i=15;i>-1;i--)
{ crca = crca | (crc0[i]<<i);
}
/* now put the crc1 bits back together as a 16 bit word */
crcb = 0;
for(i=15;i>-1;i--) crcb = crcb | (crc1[i]<<i);
printf("crca=%x crcb=%x\n",crca,crcb);
}
if(crca == 0x1a71 || crca == 0xa816) exit(0);
}
unscramble(unsigned long word)
{ int in0[16],in1[16];
unsigned long out0,out1;
int i;
/* unscramble the crc word back into the 2 serial streams */
in0[15] = (word>>30) & 1;
in0[14] = (word>>28) & 1;
in0[13] = (word>>26) & 1;
in0[12] = (word>>24) & 1;
in0[11] = (word>>22) & 1;
in0[10] = (word>>20) & 1;
in0[9] = (word>>18) & 1;
in0[8] = (word>>16) & 1;
in0[7] = (word>>14) & 1;
in0[6] = (word>>12) & 1;
in0[5] = (word>>10) & 1;
in0[4] = (word>>8) & 1;
in0[3] = (word>>6) & 1;
in0[2] = (word>>4) & 1;
in0[1] = (word>>2) & 1;
in0[0] = (word>>0) & 1;
in1[15] = (word>>31) & 1;
in1[14] = (word>>29) & 1;
in1[13] = (word>>27) & 1;
in1[12] = (word>>25) & 1;
in1[11] = (word>>23) & 1;
in1[10] = (word>>21) & 1;
in1[9] = (word>>19) & 1;
in1[8] = (word>>17) & 1;
in1[7] = (word>>15) & 1;
in1[6] = (word>>13) & 1;
in1[5] = (word>>11) & 1;
in1[4] = (word>>9) & 1;
in1[3] = (word>>7) & 1;
in1[2] = (word>>5) & 1;
in1[1] = (word>>3) & 1;
in1[0] = (word>>1) & 1;
printf("in0 = %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n",
in0[0], in0[1], in0[2], in0[3], in0[4], in0[5], in0[6], in0[7],
in0[8], in0[9],in0[10],in0[11],in0[12],in0[13],in0[14],in0[15]);
printf("in1 = %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n",
in1[0], in1[1], in1[2], in1[3], in1[4], in1[5], in1[6], in1[7],
in1[8], in1[9],in1[10],in1[11],in1[12],in1[13],in1[14],in1[15]);
/* now pack the 2 streams back into 16 bit words */
out0 = 0;
out1 = 0;
for(i=0;i<16;i++)
{ out0 = out0 | (in0[i]<<i);
out1 = out1 | (in1[i]<<i);
}
printf("unscramble digitizer crc %x %x\n",out0,out1);
}
|
TypeScript
|
UTF-8
| 551 | 2.765625 | 3 |
[] |
no_license
|
import { Temp } from "../../src/common/temp";
import { TemperatureConverter } from "../../src/openweather/temp.converter";
describe("TemperatureConverter", () => {
test.each([
[Temp.CELSIUS, "metric"], [Temp.FAHRENHEIT, "imperial"]
])("Successfully map %o => %s", (from: Temp, to: string) => {
expect(TemperatureConverter.convert(from)).toEqual(to);
});
test.each([null, undefined])("Failed to map %s", (from: unknown) => {
expect(() => TemperatureConverter.convert(from as Temp)).toThrowError();
});
});
|
Java
|
UTF-8
| 4,772 | 1.804688 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.savor.operation.activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import com.common.api.utils.ShowMessage;
import com.savor.operation.R;
import com.savor.operation.bean.FixBean;
import com.savor.operation.bean.LoginResponse;
import com.savor.operation.core.AppApi;
import com.savor.operation.utils.ActivitiesManager;
import com.savor.operation.widget.CommonDialog;
/**
* 首页
*/
public class OutSourceMainActivity extends BaseActivity implements View.OnClickListener {
private static final int NOTIFY_DOWNLOAD_FILE = 10001;
private static final int UPDATE_LOCATION = 10002;
private long exitTime;
private TextView mSearchTv;
private FixBean fixBean;
private TextView mUserInfo;
private NotificationManager manager;
private int msg;
private Notification notif;
private TextView mLocationTv;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case UPDATE_LOCATION:
String currentLocation = mSession.getCurrentLocation();
if(!TextUtils.isEmpty(currentLocation)) {
mLocationTv.setText("当前位置:"+currentLocation);
}else {
mLocationTv.setText("当前位置:获取失败");
}
startLocationTimer();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_outsource_main);
getViews();
setViews();
setListeners();
startLocationTimer();
}
private void startLocationTimer() {
mHandler.sendEmptyMessageDelayed(UPDATE_LOCATION,1000*10);
}
@Override
public void getViews() {
mSearchTv = (TextView) findViewById(R.id.tv_search);
mLocationTv = (TextView) findViewById(R.id.tv_location);
mUserInfo = (TextView) findViewById(R.id.tv_user);
}
@Override
public void setViews() {
LoginResponse loginResponse = mSession.getLoginResponse();
if(loginResponse!=null) {
String nickname = loginResponse.getNickname();
mUserInfo.setText("当前登录用户:"+nickname);
}
String currentLocation = mSession.getCurrentLocation();
if(!TextUtils.isEmpty(currentLocation)) {
mLocationTv.setText("当前位置:"+currentLocation);
}
}
@Override
public void setListeners() {
mSearchTv.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_logout:
new CommonDialog(this, "是否退出?", new CommonDialog.OnConfirmListener() {
@Override
public void onConfirm() {
mSession.setLoginResponse(null);
Intent intent = new Intent(OutSourceMainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}, new CommonDialog.OnCancelListener() {
@Override
public void onCancel() {
}
},"确定").show();
break;
case R.id.tv_search:
Intent intent = new Intent(this,SearchHotelActivity.class);
startActivityForResult(intent,SingleHotelPositionInfoAcitivty.REQUEST_CODE_SELECT);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == SingleHotelPositionInfoAcitivty.RESULT_CODE_SELECT) {
if(data!=null) {
fixBean = (FixBean) data.getSerializableExtra("bean");
}
}
}
@Override
public void onSuccess(AppApi.Action method, Object obj) {
super.onSuccess(method, obj);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeMessages(UPDATE_LOCATION);
mHandler.removeCallbacksAndMessages(null);
}
}
|
C++
|
UTF-8
| 1,729 | 3.5 | 4 |
[] |
no_license
|
#ifndef DOCUMENTHEAP_HPP_INCLUDED
#define DOCUMENTHEAP_HPP_INCLUDED
#include "Document.hpp"
#include <vector>
/**
* \brief Documents max heap
*/
class DocumentHeap{
private:
/// heap array of document
std::vector<Document*> documents;
/// actual number of elements in the heap
size_t _size = 0, max_size = 0;
/**
* \brief Move the node up in the tree
* \param child index of the child node in the array
* \return void
*/
void up(size_t child);
/**
* \brief Move the node down in the tree
* \param father index of the father node in the array
* \return void
*/
void down(size_t father);
public:
/**
* \brief heap constructor
* \param max_size heap maximum size
*/
DocumentHeap(const size_t max_size);
/**
* \brief Returns the number of elements in the heap
* \return size_t
*/
size_t size() const { return _size; }
/**
* \brief returns true if the heap is empty
* \return bool
*/
bool empty() const { return _size == 0; }
/**
* \brief insert or update a node in the heap
* \param doc document to insert or update
* \return bool
*/
bool insertOrUpdate(Document* doc);
/**
* \brief update a node in the heap
* \param doc document to update
* \return bool
*/
bool update(Document* doc);
/**
* \brief remove the node with maximum priority
* \return Document*
*/
Document* pop();
/**
* \brief Returns the node with maximum priority
* \return Document*
*/
Document* top(){ return *documents.begin();}
/// class destructor
~DocumentHeap();
};
#endif
|
Python
|
UTF-8
| 461 | 3.296875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
def collatz(x):
if x%2 == 0:
return x/2
else:
return 3*x+1
def get_collatz_seq_len(x):
length = 1
while x != 1:
x = collatz(x)
length += 1
return length
init = 1000000
big_seq_len = 0
big_seq_num = init
while init > 0:
seq_len = get_collatz_seq_len(init)
if seq_len > big_seq_len:
big_seq_len = seq_len
big_seq_num = init
init -= 1
print(big_seq_num)
|
Java
|
UTF-8
| 3,021 | 2.78125 | 3 |
[] |
no_license
|
package selenium.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import selenium.helpers.Person;
import static org.junit.Assert.*;
public class FeedbackCheckPage extends GenericSamplePage {
//region get/set;
public String getEnteredName(){
return enteredName.getText();
}
public String getEnteredAge(){
return enteredAge.getText();
}
public String getEnteredLanguage(){
return enteredLanguage.getText();
}
public String getEnteredGender(){
return enteredGender.getText();
}
public String getEnteredOpinion(){
return enteredOpinion.getText();
}
public String getEnteredComment(){
return enteredComment.getText();
}
public void clickYesButton() {
buttonYes.click();
}
public void clickNoButton() {
buttonNo.click();
}
//endregion
//region web elements;
//name
@FindBy(how = How.ID, using = "name")
private WebElement enteredName;
//age
@FindBy(how = How.ID, using = "age")
private WebElement enteredAge;
//language
@FindBy(how = How.ID, using = "language")
private WebElement enteredLanguage;
//gender
@FindBy(how = How.ID, using = "gender")
private WebElement enteredGender;
//opinion
@FindBy(how = How.ID, using = "option")
private WebElement enteredOpinion;
//comment
@FindBy(how = How.ID, using = "comment")
private WebElement enteredComment;
//buttonYes
@FindBy(how = How.CLASS_NAME, using = "w3-green")
private WebElement buttonYes;
//buttonNo
@FindBy(how = How.CLASS_NAME, using = "w3-red")
private WebElement buttonNo;
//endregion
//region checkers
public void checkFeedbackEmpty(){
assertEquals(getEnteredName(),"");
assertEquals(getEnteredAge(),"");
assertEquals(getEnteredLanguage(),"");
assertEquals(getEnteredGender(),"null");
assertEquals(getEnteredOpinion(),"null");
assertEquals(getEnteredComment(),"");
}
public void checkFeedbackFilled(){
Person person = new selenium.helpers.Person();
assertEquals(getEnteredName(),person.name);
assertEquals(getEnteredAge(), person.age);
assertEquals(getEnteredLanguage(),person.language);
assertEquals(getEnteredGender(),person.gender);
assertEquals(getEnteredOpinion(),person.opinion);
assertEquals(getEnteredComment(),person.comment);
}
public void checkButtonsFormatting() {
//YesButton
assertEquals("rgba(76, 175, 80, 1)", buttonYes.getCssValue("background-color"));
assertEquals("rgb(255, 255, 255)", buttonYes.getCssValue("text-decoration-color"));
//NoButton
assertEquals("rgba(244, 67, 54, 1)", buttonNo.getCssValue("background-color"));
assertEquals("rgb(255, 255, 255)", buttonNo.getCssValue("text-decoration-color"));
}
//endregion
}
|
Markdown
|
UTF-8
| 1,216 | 2.734375 | 3 |
[] |
no_license
|
# Xml Document Transform
Are you using notepad to edit web.config files on production servers?
I use this tool to patch application and web configuration files during deployment as part of a CI/CD pipeline. Visual Studio can do this at build time but I often need to deploy the RELEASE build to multiple environments using different settings and connection strings.
## Usage
Pass input file and transform file as command line arguments, output goes to Console.Out:
```
xdt Source.config Transform.config
```
Normally you will redirect the output to a new file, save and replace the original
```
xdt Source.config Transform.config > result.config
move Source.config Source.config.orig
move result.config Source.config
```
# Examples and reference
* Try it out using the example files Source.config and Transform.config
* XDT syntax at https://docs.microsoft.com/en-us/previous-versions/aspnet/dd465326(v=vs.110)
## CI/CD
Here's one way to do it:
* Build this project with VS2017 or later
* Include the `xdt.exe` and `Microsoft.Web.XmlTransform.dll` files in your project and add as references
* Include your transform file in the output
* Run the transform from whatever deploy tool you are using
|
Markdown
|
UTF-8
| 12,715 | 2.609375 | 3 |
[] |
no_license
|
###### Biden’s border bind
# Joe Biden faces a humanitarian crisis at the southern border
##### A humanitarian crisis risks turning into a political one

> Mar 18th 2021
THE FIRST thing you see after crossing the bridge from Reynosa, in Mexico, into Texas is a large white sign with bright red letters that spell out “BINGO”. It is meant as an advertisement for a hall where people can play the game. But it also serves as a reminder of the long odds and random luck that lie in store for those making their way to America.
Hoping fortune may be on their side now that a is in the White House, a rising number of migrants are arriving. Guatemalans, Hondurans and Salvadoreans are fleeing violence, poverty and a pair of hurricanes. Mexicans are coming to escape a . From last October through February, Customs and Border Protection (CBP), which guards America’s borders, had around 400,000 encounters along the south-western border. That is the highest number during those months since 2006.
Many are children: in October-February, around 30,000 people under the age of 18 presented themselves at the border without a parent, setting off a scramble to find beds in a system already stretched by the pandemic. A record 120,000 could arrive this year—54% more than in the previous peak year of 2019.
Plenty of those who make the treacherous crossing are not spotted or apprehended by CBP. Matt Robinson, the head of security for the East Foundation, a not-for-profit outfit that manages 215,000 acres of ranchland in South Texas (an area roughly the size of New York City), reckons he is seeing ten to 20 times more migrants illegally crossing the foundation’s land than last autumn. The situation has “changed so fast, and is so upside down, I don’t know if there’s any guardrails,” says Urbino “Benny” Martinez, the sheriff of Brooks County, which is 70 miles north of the border, and has the morbid distinction of being a hotspot for migrant deaths from dehydration.
This situation poses a huge challenge for Joe Biden, who was elected partly on his promise to enact more humane immigration policies than his predecessor. A rush of migrants to the border could overwhelm an already rickety system and impede his ability to honour that promise.

America has dealt with spikes in illegal immigration before (see chart), often caused by forces beyond a new president’s control. “There was always going to be a surge because of a backlog under Trump,” says Lee Gelernt of the American Civil Liberties Union. Last year Donald Trump in effect sealed the border from entrants by invoking Title 42, a public-health order that authorised the rapid expulsion of all border-crossers and asylum-seekers because of concerns about covid-19. This has resulted in pent-up demand.
But some migrants are arriving because Mr Biden’s actions may have given the impression that America does not intend to enforce its immigration laws, and will put penitence for Mr Trump’s nativist policies ahead of border security. In January the Biden administration ordered a 100-day halt to deportations of illegal immigrants already in America. (This was scuttled by a lawsuit from the state of Texas and a court ruling.) He has ended the Trump-era “remain in Mexico” policy, under which would-be immigrants remain south of the border to await their immigration proceedings; some 20,000 people will soon be allowed to enter America.
His administration has left Title 42 in place, which allows it to expel more border-crossers immediately. It has chosen to accept unaccompanied minors, regardless of whether they qualify for asylum or other special consideration. Some families have sent their children ahead to America because it is their likeliest shot at gaining entry. Having railed against the Trump administration’s “zero tolerance” policy that resulted in family separation, Mr Biden is in the peculiar situation of watching some families voluntarily separate to get their children into the United States.
Rumour has it
“We’ve thrown open the border by rumour,” says Neal Wilkins, who runs the East Foundation. Sister Norma Pimentel, who heads the Catholic Charities of the Rio Grande Valley and interacts with many of the arriving families, blames “organised crime” for spreading the message that now is the time to come. Smugglers are using the change of administration to drum up business. From Central America they charge $10,000, which includes a “coyote” to guide them through harsh terrain and three tries, if they get turned away by Border Patrol on their first two attempts. Many families are hoping to turn themselves in at the border to start the asylum process.
In recent weeks, more families have also been allowed in because of a decision by the Mexican government to stop taking back families with young children that CBP has tried to expel. Pending negative covid-19 tests (Title 42 remains in effect), they are being processed and released into the Rio Grande Valley without needing to make a claim for asylum, whereas families who have children older than seven are, in effect, barred. Those who test positive are being put up at hotels to quarantine.
Catholic Charities of the Rio Grande Valley is helping around 700 new families every day at its shelter in McAllen, opposite the bus station. Your correspondent was there as a dozen new arrivals were dropped off by Border Patrol. All had young children, some only a couple of months old. That fuels news that America’s borders are opening, which encourages others to come. Children may get the most headlines, but, says Andrew Selee, president of the Migration Policy Institute, a think-tank in Washington, “by sheer numbers, there’s a lot more parents with children than unaccompanied minors”.
The system is already buckling. America’s immigration system was designed when single people, mostly Mexican men, were trying to cross the border to find work. In the past decade there have been three demographic shifts among border-crossers: from Mexicans to Central Americans; from single people to families and children; and from those who need no humanitarian protection to those asking for asylum. Although asylum-seekers on the southern border may be fleeing desperate circumstances, most will not meet the standard that lets them stay. But those who pass an interview proving “credible fear” are often released into the United States while their cases are pending.
The overburdened immigration-court system now has 1.3m cases, about two-and-a-half times the number when Mr Trump assumed office. Resolution takes years, and most migrants disappear into their communities while they wait. According to a study by the Department of Homeland Security, among asylum-seekers from the Northern Triangle countries of El Salvador, Guatemala and Honduras who arrived between 2014 and 2019, 28% were repatriated by early 2020. Yet the department has no record of departure for the other 72%. With only 8% being granted some sort of relief from removal, the others are either still awaiting judgments or have decided to stay indefinitely, even though they are not legally allowed to do so.
Much of the burden for helping migrants who arrive in America has long fallen on non-profit groups, especially during the previous surge in 2019 under President Trump. But covid-19 is presenting overstretched charities with additional challenges. “This time around we’re finding it a lot more difficult, because we don’t have volunteers,” says Sister Pimentel. We’re running short of hands to make it right.” The United Way of El Paso County recently asked 100 former volunteers to help, but only six said they were comfortable enough to accept, says Christina Lamour, vice-president of community impact.
This affects communities well beyond the Valley. “Even 80 miles away from the border, people are affected,” says Susan Kibbe of the South Texans’ Property Rights Association. Some ranchers are afraid to go to parts of their land, she says, after being threatened by smugglers and cartel members. Agents who used to patrol farther north have been pulled down to the border.
On the 90-minute drive from Raymondville to Hebronville in the Rio Grande Valley, usually you would see ten Border Patrol officers and six officers from Texas’s Department of Public Safety, reckons Mr Robinson of the East Foundation. When your correspondent did the drive with him, they saw none. On any given day there could be 100 migrants hiding in the brush in Brooks County, says Mr Martinez, the sheriff, but with much of the county’s Border Patrol pulled south, the brushwork is often left undone.
Such chaos has national-security implications. Will Hurd, a former congressman, says intelligence organisations should make ending human smuggling in Central America a priority. It is not just Mexicans and Central Americans who arrive through the southern border but others from Asia, the Middle East and elsewhere, seeking to enter undetected. This month CBP has intercepted at least three groups of more than 100 migrants each, including nine Romanians. In addition to people, smugglers ferry drugs across the border. The more migrants overwhelm the system, the more this distracts from the task of . Between October and February, seizures of fentanyl rose by around 360% from a year ago.
Who said what, when?
Confusion about border policy is rife. Mr Biden has yet to nominate permanent heads of CBP and Immigration and Customs Enforcement (ICE). One law-enforcement official asked your correspondent whether Title 42 was still in effect. Others are unsure whether it was the United States or Mexico that decided not to send back families with young children.
Hugo Zurita, who runs Good Neighbour Settlement House, a non-profit in Brownsville, says there needs to be “more communication with DC and local officials. I’m not saying we need to know every detail, but we need to know what’s going to happen.” Studying conditions at the border first-hand would surely help. “The big problem we continue to have with government is they never seem to get down on the ground and talk to people who are here on the front lines, who live and work in the community,” says Dennis Nixon, the boss of IBC, a bank, in Laredo, Texas.
Mr Biden has already ordered a review of various immigration policies, from the asylum system to how to reunify families separated under Mr Trump. He does not have much time. Already immigrant-rights groups, finding themselves with more sway than they have had in years, are agitating to end Trump-tainted Title 42.
But “if they were to lift that, you’d see the system overwhelmed even more,” says Theresa Cardinal Brown of the Bipartisan Policy Centre, a think-tank. “Right now Title 42 is the only thing that is buying the administration time to put in place the immigration system it wants.” There is talk of creating reception facilities that are not just for detention, so migrants can find out more about the asylum process and get information: the sort some European countries have designed for refugees. “You can rely on the shelters and non-profits for only so long,” says Ms Brown.
In the coming months, Mr Biden will find himself sandwiched between two pugnacious, opposing forces. One is the left flank of his own party, which has become more strident on immigration, staking out positions such as abolishing customs and immigration enforcement and never detaining unaccompanied minors. The other is the Republicans, who have already signalled that they intend to use the border as a wedge issue to take back Congress in the 2022 mid-term elections. Unless Mr Biden can show that he is successfully grappling with the surge of migrants and reining in his own party, the border could cost Democrats seats, much as “defund the police” did in 2020.
The border troubles also pose a threat to Mr Biden’s own agenda. He wants to shepherd through comprehensive immigration reform, offering illegal immigrants already in the United States a path to legal status, and he supports giving citizenship to “Dreamers”, who were brought to America as young children. But those prospects dim as the surge of migrants grows. “Anything we’re trying to get passed connected with immigration is potentially at greater risk, depending on current conditions at the border,” says Woody Hunt, a Texan businessman, who, along with a group of business leaders, supports offering permanent status to Dreamers. For Mr Biden, the southern border is quickly becoming a moral and political quagmire. ■
|
C++
|
UTF-8
| 1,025 | 3.078125 | 3 |
[] |
no_license
|
#pragma once
#include <windows.h>
class GlobalTime
{
private:
static DWORD lastTick;
static DWORD curTick;
static DWORD lastStep;
static DWORD lastTimeGetTime;
static bool paused;
GlobalTime( void );
GlobalTime( const GlobalTime &rhs );
GlobalTime &operator =( const GlobalTime &rhs );
public:
static void Update( void )
{
if ( !paused )
{
lastStep = timeGetTime() - lastTimeGetTime;
lastTick = curTick;
curTick += lastStep;
}
else
{
lastStep = 0;
}
lastTimeGetTime = timeGetTime();
}
static void Pause( void )
{
paused = true;
}
static void Unpause( void )
{
paused = false;
}
static DWORD GetCurTick( void )
{
return curTick;
}
static DWORD GetLastTick( void )
{
return lastTick;
}
static DWORD GetStep( void )
{
return lastStep;
}
};
|
C#
|
UTF-8
| 3,108 | 3.125 | 3 |
[] |
no_license
|
using System;
using System.Text;
namespace Echelon
{
public sealed class Arrays
{
private Arrays()
{
}
public static bool AreEqual(bool[] a, bool[] b)
{
if (a == b)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return Arrays.a(a, b);
}
public static bool AreEqual(char[] a, char[] b)
{
if (a == b)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return Arrays.b(a, b);
}
public static bool AreEqual(byte[] a, byte[] b)
{
if (a == b)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return c(a, b);
}
[Obsolete("Use 'AreEqual' method instead")]
public static bool AreSame(byte[] a, byte[] b)
{
return AreEqual(a, b);
}
public static bool ConstantTimeAreEqual(byte[] a, byte[] b)
{
int num = a.Length;
if (num != b.Length)
{
return false;
}
int num2 = 0;
while (num != 0)
{
num--;
num2 |= (a[num] ^ b[num]);
}
return num2 == 0;
}
public static bool AreEqual(int[] a, int[] b)
{
if (a == b)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return d(a, b);
}
private static bool a(bool[] eg, bool[] eh)
{
int num = eg.Length;
if (num != eh.Length)
{
return false;
}
while (num != 0)
{
num--;
if (eg[num] == eh[num])
{
continue;
}
return false;
}
return true;
}
private static bool b(char[] ei, char[] ej)
{
int num = ei.Length;
if (num != ej.Length)
{
return false;
}
while (num != 0)
{
num--;
if (ei[num] == ej[num])
{
continue;
}
return false;
}
return true;
}
private static bool c(byte[] ek, byte[] el)
{
int num = ek.Length;
if (num != el.Length)
{
return false;
}
while (num != 0)
{
num--;
if (ek[num] == el[num])
{
continue;
}
return false;
}
return true;
}
private static bool d(int[] em, int[] en)
{
int num = em.Length;
if (num != en.Length)
{
return false;
}
while (num != 0)
{
num--;
if (em[num] == en[num])
{
continue;
}
return false;
}
return true;
}
public static string ToString(object[] a)
{
StringBuilder stringBuilder = new StringBuilder(91);
if (a.Length != 0)
{
stringBuilder.Append(a[0]);
for (int i = 1; i < a.Length; i++)
{
stringBuilder.Append(", ").Append(a[i]);
}
}
stringBuilder.Append(']');
return stringBuilder.ToString();
}
public static int GetHashCode(byte[] data)
{
if (data == null)
{
return 0;
}
int num = data.Length;
int num2 = num + 1;
while (--num >= 0)
{
num2 *= 257;
num2 ^= data[num];
}
return num2;
}
public static byte[] Clone(byte[] data)
{
if (data != null)
{
return (byte[])data.Clone();
}
return null;
}
public static int[] Clone(int[] data)
{
if (data != null)
{
return (int[])data.Clone();
}
return null;
}
}
}
|
Markdown
|
UTF-8
| 1,213 | 2.578125 | 3 |
[] |
no_license
|
# Download: Converts .csv transaction files into .txf files.
**Program name:**
## 1099-B Importer 1.2
**Thumbshot:** 
**Download link:** [Download Converts .csv transaction files into .txf files.](http://freesoftwares.boysofts.com/1099-B-Importer_program_64564.html)
**Publisher's Description**
1099-B Importer converts the .csv file provided by your broker into a .txf file that can be easily imported in your tax software. It is completely FREE! No transaction limits, no upsell, no registration, no ads...
It works on virtually any .csv file; just specify the column mapping. No need to upload your financial information to an untrusted website, all the software runs on your computer. No need for Excel or expensive software.
Requires: [Microsoft .NET Framework 2.0](http://www.freewarefiles.com/Microsoft-NET-Framework-20-x86-Final_program_16026.html).
Screenshot: 
**For more freeware softwares visit [Freeware software downloads.](http://freesoftwares.boysofts.com/)**
**And [Free softwares and php script downloads.](http://www.boysofts.com/)**
|
C++
|
UTF-8
| 1,650 | 4.03125 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
int **getData(int &,int &); //Return the 2-D array and its size.
void prntDat(const int* const *,int,int);//Print the 2-D Array
void destroy(int **,int,int); //Deallocate memory
int sum(const int * const *, int,int); //Return the Sum
int main(){
int **array, ROW, COL;
array=getData(ROW, COL);
prntDat(array, ROW, COL);
cout<<sum(array, ROW, COL);
destroy(array, ROW, COL);
return 0;
}
int **getData(int &ROW,int &COL){ //Return the 2-D array and its size.
cin>>ROW>>COL;
int **array = new int *[ROW]; //allocates memory for each row in array
for(int i=0;i<ROW;i++){
array[i] = new int[COL]; //allocates memory for amount of columns in array
for (int j=0;j<COL;j++){
cin>>array[i][j];
}
}
return array;
}
void prntDat(const int* const *array,int ROW,int COL){//Print the 2-D Array
for (int i=0;i<ROW;i++) {
for (int j=0;j<COL;j++){
if (j==COL-1) cout<<array[i][j]; //Excludes space if it the last number
else cout<<array[i][j]<<" ";
}
cout<<endl;
}
}
void destroy(int **array, int ROW, int COL){ //Deallocate memory
for (int i=0;i<ROW;i++) {
delete [] array[i]; //deletes each column
}
delete array;
}
int sum(const int *const *array, int ROW,int COL){ //Return the Sum
int sum=0;
for (int i=0;i<ROW;i++){
for (int j=0;j<COL;j++) {
sum+=array[i][j]; //for loop to sum all elements together
}
}
return sum;
}
|
Markdown
|
UTF-8
| 4,738 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
# 聊聊深拷贝和浅拷贝
## 什么是深拷贝和浅拷贝
1. 浅拷贝:将一个对象(包括数组)的引用赋值给一个新对象,这时新对象也只是原对象的引用
2. 深拷贝:创建一个新的对象(包括数组),将原对象的各个属性值拷贝到新的对象,两个对象都是全新的引用,互不相关,操作也就互不影响了。
***
这里提一下 原始值 和 引用值
1. 原始值:存储在栈中的直接的数据,可以直接访问,存储的是实实在在的值。
~~~
Undefined,Stirng,Boolean,Null, Number
注意:原始值当直接赋值时是等于 复制一个全新的值,两则修改没有任何联系。
~~~
2. 引用值:存储在栈中的名称,只是一个对应堆中的的一个引用地址,每创建一个引用值,则会响应的在堆中创建新的对应空间。
~~~
Object,Function,Array,Date,RegExp
注意:引用值直接赋值,只是创建一个新的引用地址,它们所对应的空间是一个;
所以修改其中一个,等于直接操纵的一个空间,
所对应的其他的值也就随之变了。
~~~
***
## 代码分析 - 深拷贝
浅拷贝不列代码了。
根据深拷贝的原理,列举实现思路
```
深拷贝的思路:
1.便利对象判断是否是原始值
2.判断是否是数组还是对象
3.建立新的响应的数组或对象
4.递归,一直拷贝至最深的节点。
```
列举jq.extend() 方法来说明,下面是源码:
```
jQuery.fn.extend = jQuery.extend = function() {
var target = arguments[0] || {};
var length = arguments.length;
var i = 1;
var deep = false; //是否是深拷贝
var option, name,copy,src,copyIsArray,clone;
if (typeof target === "boolean") { //处理深度复制的情况
deep = target; //是否是深拷贝
target = arguments[1];
i = 2;
}
if (typeof target !== "object") { 当目标是字符串或其他东西时
target = {};
}
//参数的个数 1
if (length === i) {
target = this;
i--;
}
//浅拷贝 深拷贝
for (; i < length; i++) {
if ((option = arguments[i]) != null) { //只处理非空/未定义 的值
for (name in option) {
copy = option[name];
src = target[name];
if(deep && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))){
if(copyIsArray){
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
target[name] = jQuery.extend(deep, clone, copy);
} else if(copy != undefined){
target[name] = copy;
}
}
}
}
return target;
}
```
调用:
```
// 调用:
var ret = {name:"max",list:{age:"30"}};
var res = {list:{sex:"女"},age:'18'};
//浅拷贝 以第一个参数为控制 ,false 或则不传 则为 浅拷贝 ,true则为深拷贝
var objs = $.extend({},ret,res);
console.log(objs);
//任意对象扩展
var obj = $.extend(true,{}, ret, res);
console.log(obj);
```
### 分步解析
1. 做好深浅拷贝的划分(属于优化部分)
```
var target = arguments[0] || {}; // target为最终需要返回的对象
var length = arguments.length; //确定需要合并拷贝的对象个数
var i = 1; // 除了需要合并的对象以外,其余的需要进行拷贝(遍历)
```
2. 便利对象判断是否是原始值 ,如果是原始值 则直接赋予该属性
```
for (name in option) {
copy = option[name];
src = target[name];
if(deep && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))){ //如果深拷贝deep,并且是引用值
if(copyIsArray){
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
target[name] = jQuery.extend(deep, clone, copy);
} else if(copy != undefined){ //如果不是引用值,就直接添加属性入target
target[name] = copy;
}
}
```
3. 如果是引用值则 建立新的对象(数组,或对象) ,并去递归,每一次递归都会检查值得属性并做浅拷贝
```
copy = option[name];
src = target[name];
if(deep && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))){ //如果深拷贝deep,并且是引用值
if(copyIsArray){ //如果是数组
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : []; //建立数组再去递归
} else { //如果是对象 ,建立对象去递归
clone = src && jQuery.isPlainObject(src) ? src : {};
}
target[name] = jQuery.extend(deep, clone, copy);
}
```
4. 直到所有的参数值进行合并,并合并到target上,最后返回新的对象
```
return target;
```
|
JavaScript
|
UTF-8
| 4,704 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
function transpose(A) {
var m = A.length;
var n = A[0].length;
var AT = [];
for (var j = 0; j < n; j++) {
var ATj = [];
for (var i = 0; i < m; i++) {
ATj.push(A[i][j]);
}
AT.push(ATj);
}
return AT;
}
function dot(v1, v2) {
/*
* Compute dot product v1 . v2.
*/
var n = v1.length;
var result = 0.0;
for (var i = 0; i < n; i++) result += v1[i] * v2[i];
return result;
}
function norm(v) {
/*
* 2-norm of a vector
*/
return Math.sqrt(dot(v, v));
}
function mvMult(A, v, diagonalA) {
/*
* Compute dot product A . v, where A is a matrix.
* If diagonalA is true, then A must be a 1-D array.
*/
if (diagonalA) return elementwiseVectorMult(A, v);
else {
return A.map(function (Arow) {
return dot(Arow, v);
});
}
}
function svMult(a, v) {
/*
* Multiply vector v by scalar a.
*/
return v.map(function (x) {
return a * x;
});
}
function smMult(a, A) {
/*
* Multiply matrix A by scalar a.
*/
return A.map(function (Arow) {
return svMult(a, Arow);
});
}
function svAdd(a, v) {
/*
* Add a scalar a to every element of vector v.
*/
return v.map(function (x) {
return a + x;
});
}
function vectorAdd() {
var m = arguments[0].length;
var n = arguments.length;
var result = [];
for (var i = 0; i < m; i++) {
var element = 0.0;
for (var j = 0; j < n; j++) {
element += arguments[j][i];
}
result.push(element);
}
return result;
}
function elementwiseVectorDivide(v1, v2) {
/*
* Compute v1 / v2 elementwise.
*/
var result = [];
n = v1.length;
for (var i = 0; i < n; i++) {
result.push(v1[i] / v2[i]);
}
return result;
}
function elementwiseVectorMult(v1, v2) {
/*
* Compute v1 * v2 elementwise.
*/
var result = [];
n = v1.length;
for (var i = 0; i < n; i++) {
result.push(v1[i] * v2[i]);
}
return result;
}
function svMultAdd(scalars, vectors) {
/*
* Add a set of vectors together, each multiplied by a scalar.
*/
var m = vectors[0].length;
var n = scalars.length;
if (vectors.length != n) {
console.warn("svMultAdd: Difference number of scalars and vectors.");
return null;
}
var result = [];
for (var i = 0; i < m; i++) {
var element = 0.0;
for (var j = 0; j < n; j++) {
element += scalars[j] * vectors[j][i];
}
result.push(element);
}
return result;
}
function absVector(v) {
var result = [];
for (var i = 0; i < v.length; i++) {
result[i] = Math.abs(v[i]);
}
return result;
}
function LUPDecompose(A, eps) {
/*
* LUP decomposition.
*/
var i, j, k, imax;
var maxA, absA;
var Arow;
var p = [];
var n = A.length;
var LU = shallowCopyMatrix(A);
// Permutation matrix
for (i = 0; i <= n; i++) p.push(i);
for (i = 0; i < n; i++) {
maxA = 0.0;
imax = i;
for (k = i; k < n; k++) {
absA = Math.abs(LU[k][i]);
if (absA > maxA) {
maxA = absA;
imax = k;
}
}
// Failure; singular matrix
if (maxA < eps) return [null, null];
if (imax != i) {
// Pivot
j = p[i];
p[i] = p[imax];
p[imax] = j;
// Pivot rows of A
Arow = LU[i];
LU[i] = LU[imax];
LU[imax] = Arow;
// Count pivots
p[n]++;
}
for (j = i + 1; j < n; j++) {
LU[j][i] /= LU[i][i];
for (k = i + 1; k < n; k++) LU[j][k] -= LU[j][i] * LU[i][k];
}
}
return [LU, p];
}
function LUPSolve(LU, p, b) {
/*
* Solve a linear system where LU and p are stored as the
* output of LUPDecompose().
*/
var n = b.length;
var x = [];
for (var i = 0; i < n; i++) {
x.push(b[p[i]]);
for (var k = 0; k < i; k++) x[i] -= LU[i][k] * x[k];
}
for (i = n - 1; i >= 0; i--) {
for (k = i + 1; k < n; k++) x[i] -= LU[i][k] * x[k];
x[i] /= LU[i][i];
}
return x;
}
function solve(A, b) {
/*
* Solve a linear system using LUP decomposition.
*
* Returns null if singular.
*/
var eps = 1.0e-14;
var LU, p;
[LU, p] = LUPDecompose(A, eps);
// Return null if singular
if (LU === null) return null;
return LUPSolve(LU, p, b);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.